Compare commits
46
Commits
018c02c759
...
v0.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a372b9dcc4 | ||
|
|
77dcf5c9bd | ||
|
|
a6db9f1566 | ||
|
|
0700967c30 | ||
|
|
0e04c583a6 | ||
|
|
443aff8323 | ||
|
|
71f4451b34 | ||
|
|
9c0416f4bb | ||
|
|
dff374649c | ||
|
|
bffd647a3e | ||
|
|
6ff90aae9a | ||
|
|
48c60e00a2 | ||
|
|
495d5c3907 | ||
|
|
4bf2da218c | ||
|
|
3891d0deb2 | ||
|
|
5ff947d435 | ||
|
|
1c307fac94 | ||
|
|
381930c23f | ||
|
|
74b2c400c6 | ||
|
|
9bf9c94dd6 | ||
|
|
5696c89dee | ||
|
|
50d61371e1 | ||
|
|
cf83c32b25 | ||
|
|
7bd64b870c | ||
|
|
9494d2b119 | ||
|
|
3661d0b4b7 | ||
|
|
d433a305f5 | ||
|
|
1c2d1b71ff | ||
|
|
de916d2fc7 | ||
|
|
89f9be5e72 | ||
|
|
af5d38a16b | ||
|
|
b93a8099f3 | ||
|
|
f8fcadb488 | ||
|
|
60f7107ec9 | ||
|
|
16571a9645 | ||
|
|
c11b25c20a | ||
|
|
c27aad58ae | ||
|
|
7dffaad8e5 | ||
|
|
583026418d | ||
|
|
fa6d88a768 | ||
|
|
b6c01878a8 | ||
|
|
5dbef8f23f | ||
|
|
ffb12a36b5 | ||
|
|
04b8a5a8b9 | ||
|
|
b4b40e5c2c | ||
|
|
16c9c3a03f |
+4
-1
@@ -8,7 +8,6 @@ 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_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key
|
LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key
|
||||||
LINKLOG_TOKEN_EXPIRY_MINUTES=15
|
LINKLOG_TOKEN_EXPIRY_MINUTES=15
|
||||||
@@ -24,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
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# Changelog
|
||||||
|
## 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
@@ -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;'
|
||||||
|
```
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -17,8 +17,9 @@ 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 l10n.js _locales/en-US/messages.json _locales/es/messages.json _locales/de/messages.json _locales/fr/messages.json _locales/nl/messages.json
|
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))
|
EXTENSION_SOURCES := $(addprefix webextension/,$(EXTENSION_FILES))
|
||||||
XPI_VALIDATOR := scripts/release/validate_xpi.py
|
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
|
||||||
|
|
||||||
@@ -28,6 +29,9 @@ logos: check-tools $(GENERATED_LOGOS)
|
|||||||
|
|
||||||
xpi: $(XPI_OUTPUT)
|
xpi: $(XPI_OUTPUT)
|
||||||
|
|
||||||
|
update-updates: $(UPDATES_GENERATOR) webextension/manifest.json
|
||||||
|
@python3 $(UPDATES_GENERATOR)
|
||||||
|
|
||||||
$(XPI_OUTPUT): $(EXTENSION_SOURCES) $(GENERATED_LOGOS) $(XPI_VALIDATOR)
|
$(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)
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ For local development:
|
|||||||
|
|
||||||
The backend currently uses FastAPI, uvicorn, SQLite, and Pydantic. `httpx2` is included for the Starlette-compatible test client.
|
The backend currently uses FastAPI, uvicorn, SQLite, and Pydantic. `httpx2` is included for the Starlette-compatible test client.
|
||||||
Jinja2 is included for server-rendered HTML templates.
|
Jinja2 is included for server-rendered HTML templates.
|
||||||
The backend version is `0.1.0` and is exposed through the FastAPI/OpenAPI metadata. It can be overridden with `LINKLOG_VERSION`.
|
The backend version is `0.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
|
||||||
@@ -51,6 +51,7 @@ On Windows PowerShell, activate the environment with:
|
|||||||
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.
|
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.
|
||||||
|
|
||||||
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:
|
||||||
@@ -76,7 +77,7 @@ Open these URLs:
|
|||||||
The browser extension requires a backend URL to be entered during setup; it does not assume a default server.
|
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
|
||||||
|
|
||||||
@@ -110,11 +111,11 @@ This publishes `${APP_PORT:-8000}` and defaults the application URL to `http://l
|
|||||||
|
|
||||||
## Releases
|
## Releases
|
||||||
|
|
||||||
Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `frontend/version.json`; the Firefox plugin version comes from `webextension/manifest.json`. CI also requires both to match `LINKLOG_VERSION`'s default in `backend/app/core/config.py`.
|
Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `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.
|
||||||
|
|
||||||
@@ -156,7 +157,7 @@ The manifest includes stable Firefox extension metadata and references the packa
|
|||||||
1. Start the backend locally.
|
1. Start the backend locally.
|
||||||
2. Open Firefox and visit `about:debugging#/runtime/this-firefox`.
|
2. Open Firefox and visit `about:debugging#/runtime/this-firefox`.
|
||||||
3. Select **Load Temporary Add-on**.
|
3. Select **Load Temporary Add-on**.
|
||||||
4. Choose `webextension/manifest.json`.
|
4. Choose `webextension/manifest.json` (Firefox 142 or newer is required).
|
||||||
5. Open the LinkLog extension options and enter:
|
5. Open the LinkLog extension options and enter:
|
||||||
- Backend URL: the URL of your LinkLog server, such as `http://localhost:8000`
|
- Backend URL: the URL of your LinkLog server, such as `http://localhost:8000`
|
||||||
- Email: `alice@example.com`
|
- Email: `alice@example.com`
|
||||||
@@ -179,6 +180,8 @@ cp .env.example .env
|
|||||||
|
|
||||||
Edit `.env` and replace `LINKLOG_SECRET_KEY` with a long random value. Docker Compose automatically reads `.env` from the repository root. The committed `.env.example` contains safe defaults and placeholders; the real `.env` is ignored by Git.
|
Edit `.env` and replace `LINKLOG_SECRET_KEY` with a long random value. Docker Compose automatically reads `.env` from the repository root. The committed `.env.example` contains safe defaults and placeholders; the real `.env` is ignored by Git.
|
||||||
|
|
||||||
|
When `APP_ENV=production`, application startup fails closed unless `LINKLOG_SECRET_KEY` is a non-default high-entropy value of at least 32 characters and `LINKLOG_DATA_ENCRYPTION_KEY` is a valid Fernet key. Development mode may use local defaults, but production secrets should come from a protected secret mechanism.
|
||||||
|
|
||||||
The main configurable values are:
|
The main configurable values are:
|
||||||
|
|
||||||
| Variable | Purpose | Default |
|
| Variable | Purpose | Default |
|
||||||
@@ -275,6 +278,13 @@ curl -X POST http://localhost:8000/api/auth/refresh \\
|
|||||||
|
|
||||||
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.
|
Refresh-token reuse or a mismatched device ID returns `401` and revokes the token family. Signing out revokes the token family, while changing the password or completing a password reset revokes all sessions for the user.
|
||||||
|
|
||||||
|
Sign out with the access token in the bearer header:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -X POST http://localhost:8000/api/auth/logout \\
|
||||||
|
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
|
||||||
|
```
|
||||||
|
|
||||||
Submit a link using the returned access token:
|
Submit a link using the returned access token:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
+97
-219
@@ -2,286 +2,164 @@
|
|||||||
|
|
||||||
**Assessment date:** 2026-08-26
|
**Assessment date:** 2026-08-26
|
||||||
**Scope:** Current LinkLog backend, web frontend, Firefox extension, SQLite persistence, SMTP and Mastodon integrations, Docker/Traefik deployment files, and automated tests.
|
**Scope:** Current LinkLog backend, web frontend, Firefox extension, SQLite persistence, SMTP and Mastodon integrations, Docker/Traefik deployment files, and automated tests.
|
||||||
**Assessment type:** Source-code security review. This is not a penetration test, dependency vulnerability scan, formal threat model sign-off, or production configuration certification.
|
**Assessment type:** Source-code review. This is not a penetration test, dependency scan, container scan, formal threat-model sign-off, or production configuration certification.
|
||||||
|
|
||||||
## Executive Summary
|
## Executive Summary
|
||||||
|
|
||||||
LinkLog has several good security foundations: authenticated API dependencies, administrator authorization checks, owner checks for link operations, token hashing in the database, email verification, password reset token hashing and single-use behavior, TOTP login enforcement, last-administrator protection, parameterized SQLite queries, upload size limits, and non-root application execution in the container.
|
The current worktree contains strong security improvements: salted scrypt password hashing with legacy upgrade support, bearer-header authentication, hashed and expiring tokens, refresh-token rotation with device binding and family revocation, OTP recovery codes, encrypted newly written secrets, Mastodon SSRF controls, image decoding and re-encoding, reduced extension permissions, proxy-only production Compose, and append-only audit events.
|
||||||
|
|
||||||
The current implementation is not ready to expose directly to the public Internet without additional hardening. The most important issues are:
|
The following issues remain before an Internet-facing production release:
|
||||||
|
|
||||||
1. Passwords were previously stored as unsalted, fast SHA-256 hashes; this issue has now been addressed in the current worktree with salted scrypt hashes and legacy upgrade support.
|
1. Logout still accepts a bearer token in a JSON body rather than using the standard `Authorization` header.
|
||||||
2. Access tokens are accepted in query strings by session endpoints, which can leak through logs, browser history, proxies, and referrers.
|
2. SMTP, Mastodon, setup, and some user-service errors return raw exception details to clients.
|
||||||
3. SMTP credentials, Mastodon credentials, OAuth client secrets, and TOTP secrets are stored in plaintext in SQLite.
|
3. First-run setup is intentionally unauthenticated and lacks a bootstrap secret and application-level request-size controls.
|
||||||
4. Mastodon instance URLs are user-controlled and the backend makes outbound requests to them, creating an SSRF and egress-control concern.
|
4. Audit event details are serialized without defensive sanitization or size limits at the audit-service boundary.
|
||||||
5. Login has no effective rate limiting or account lockout.
|
5. The development secret fallback is not rejected at application startup in production.
|
||||||
6. The Firefox extension stores bearer tokens in browser local storage and requests broad website access.
|
6. Rate limiting is single-instance SQLite state, is not atomic under concurrency, and reset-mail issuance is not independently throttled.
|
||||||
7. The Compose setup still exposes the application port directly and relies on deployment-specific Traefik networking and labels.
|
7. Runtime verification, security headers, centralized audit export, retention, alerting, and dependency/container/security scanning remain incomplete.
|
||||||
|
|
||||||
These findings are prioritized below. Severity describes the potential security impact in a typical Internet-facing deployment, not the likelihood in every environment.
|
The application should remain behind the production reverse proxy, with real DNS/TLS, protected secrets, and restricted network access until these items are addressed.
|
||||||
|
|
||||||
## Positive Controls Already Present
|
## Verified Controls
|
||||||
|
|
||||||
- Bearer authentication is centralized in `backend/app/api/dependencies.py`.
|
- Passwords use salted scrypt hashes; valid legacy SHA-256 hashes are upgraded on login.
|
||||||
- Administrator routes use `require_admin`; standard users receive `403`.
|
- Bearer authentication is centralized through `get_current_user` and `require_admin`.
|
||||||
- Link update, delete, and Mastodon-post operations verify ownership.
|
- Query-string authentication is not accepted by protected session endpoints.
|
||||||
- Tokens are generated with UUID material, stored as SHA-256 hashes, expire, and can be revoked.
|
- Access tokens are short-lived by default; refresh tokens are hashed, separately expiring, device-bound, rotated, and family-revoked on reuse.
|
||||||
- Password-reset tokens are random, hashed, expiring, single-use, and revoke existing sessions after reset.
|
- Logout, password changes, and password resets revoke session material according to the token lifecycle.
|
||||||
- New administrator-created users require email verification before login.
|
- OTP enrollment provides ten one-time recovery codes; only hashes are stored.
|
||||||
- OTP uses time-based verification with a one-step clock window and is required before token issuance when enabled.
|
- Users can recover OTP with password plus a recovery code, and administrators can disable OTP for another user.
|
||||||
- The profile API does not return `password_hash` or `otp_secret` after the profile response hardening.
|
- Newly written SMTP, Mastodon, OAuth, and OTP secrets are encrypted with an external Fernet key.
|
||||||
- User privilege changes protect against removing the last administrator and prevent an administrator from changing their own privilege.
|
- Mastodon instances are restricted to HTTPS public hostnames, unsafe resolved addresses are rejected, and redirects are blocked.
|
||||||
- Uploaded avatars have a 2 MB limit, a restricted MIME allow-list, user-scoped filenames, and a persistent data location.
|
- Avatar uploads are size-limited, decoded with Pillow, pixel-limited, fully loaded, and re-encoded as server-generated PNG.
|
||||||
- SQLite foreign keys are enabled and ownership predicates are used for destructive link operations.
|
- Production Compose does not publish the application port and uses the external Traefik network; local direct access is separate.
|
||||||
- SQL statements use parameters rather than interpolated user values.
|
- The Firefox extension uses `activeTab`, session-scoped credentials, exact configured backend permissions, and a self-only extension-page CSP.
|
||||||
- The Docker image runs the application as UID 10001 after startup and defines a health check.
|
- SQLite queries are parameterized and foreign-key enforcement is enabled.
|
||||||
- `.env` and database/runtime files are ignored by Git.
|
- An append-only `security_audit_events` table records actor, action, target, outcome, and details for major administrative and destructive operations.
|
||||||
- The XPI build validates archive integrity, required files, and manifest parity.
|
- The current automated backend suite passes 49 tests.
|
||||||
- Browser rendering generally uses `textContent` for feed data, reducing DOM-based injection risk.
|
|
||||||
|
|
||||||
## Findings
|
## Findings
|
||||||
|
|
||||||
### SA-001: Unsalted fast SHA-256 password hashing
|
### SA-001: Logout uses non-standard token transport
|
||||||
|
|
||||||
**Severity:** Critical, remediated in current worktree
|
|
||||||
**Evidence before remediation:** `backend/app/database.py` and `backend/app/services/auth_service.py` used unsalted SHA-256 password comparisons.
|
|
||||||
**Current state:** `backend/app/database.py` now creates salted scrypt hashes in the format `scrypt$N$r$p$salt$digest`. `verify_password()` uses the encoded parameters and constant-time comparison. `authenticate_user()` fetches by username, verifies in Python, and transparently replaces a valid legacy 64-character SHA-256 hash with a new scrypt hash.
|
|
||||||
**Residual impact:** Existing accounts remain exposed until they successfully authenticate once after deployment. An attacker with a copy of an old database may still attack legacy hashes. Existing credentials should be rotated if the old database may have been exposed.
|
|
||||||
|
|
||||||
**Recommendation:** Deploy the current migration, require password rotation for accounts that cannot log in during migration, and monitor for remaining legacy hashes. Review scrypt cost parameters periodically and increase them as hardware changes. Do not revert to a fast general-purpose hash.
|
|
||||||
|
|
||||||
**Priority:** Completed in code; operational migration and credential rotation remain.
|
|
||||||
|
|
||||||
### SA-002: Bearer tokens accepted in query strings
|
|
||||||
|
|
||||||
**Severity:** High, remediated in current worktree
|
**Severity:** High, remediated in current worktree
|
||||||
**Evidence before remediation:** `backend/app/api/auth.py` exposed `GET /api/auth/me?token=...`, and web/extension callers used the query form.
|
**Evidence before remediation:** `POST /api/auth/logout` accepted `{"token": ...}` in the JSON request body, and the web frontend sent the access token this way.
|
||||||
**Current state:** `/api/auth/me` now requires the existing bearer-header dependency. The shared web header, admin session check, Firefox settings page, and tests send `Authorization: Bearer <token>`. A query-string token is rejected with `401`.
|
**Impact:** Request bodies may be captured by debugging middleware, application logs, or monitoring systems. The endpoint also diverges from the bearer-header contract used elsewhere, increasing the chance of inconsistent token handling.
|
||||||
**Residual impact:** Tokens from old URLs may remain in proxy/browser logs and should be treated as exposed until revoked or rotated.
|
|
||||||
|
|
||||||
**Recommendation:** Rotate existing access tokens after deployment and scrub historical query parameters from logs where possible. Keep the bearer header as the only credential transport.
|
**Current state:** Logout requires `Authorization: Bearer <access-token>`, rejects body-only tokens with `401`, and revokes the token family server-side. The web frontend and Firefox extension send the header; regression coverage verifies access and refresh tokens are invalid after logout.
|
||||||
|
|
||||||
**Priority:** Completed in code; token rotation and log hygiene remain.
|
**Recommendation:** Keep logout header-only, retain family revocation, avoid logging authorization headers, and rotate legacy sessions issued before this change.
|
||||||
|
|
||||||
### SA-003: Sensitive secrets stored in plaintext SQLite
|
**Priority:** Completed in code; legacy session rotation and log hygiene remain.
|
||||||
|
|
||||||
**Severity:** High, remediated in current worktree for newly written secrets
|
### SA-002: Raw infrastructure errors are returned to clients
|
||||||
**Evidence:** `backend/app/services/email_service.py` stores SMTP settings including `smtp_password` in `app_settings`; `backend/app/services/mastodon_oauth.py` stores Mastodon application secrets and user access tokens in `app_settings` and `user_plugin_config`; `backend/app/api/user_config.py` stores `otp_secret` in the `users` table. New writes are encrypted, but legacy plaintext rows require rotation.
|
|
||||||
**Impact:** Read access to the database exposes SMTP credentials, Mastodon posting authority, OAuth client secrets, and TOTP seeds. TOTP seeds cannot be changed by a user who loses the database copy. Database backups therefore contain reusable credentials, not just application data.
|
|
||||||
|
|
||||||
**Current state:** Newly stored SMTP passwords, Mastodon OAuth client secrets and access tokens, and TOTP seeds are encrypted with Fernet using `LINKLOG_DATA_ENCRYPTION_KEY`. The key is required in Docker and is not stored in SQLite. The user plugin API no longer returns the Mastodon access token.
|
|
||||||
**Residual impact:** Existing plaintext secrets require a controlled read-and-save rotation after the key is configured. Lost encryption keys make stored secrets unrecoverable.
|
|
||||||
|
|
||||||
**Recommendation:** Supply `LINKLOG_DATA_ENCRYPTION_KEY` through a protected secret mechanism, encrypt backups, rotate credentials after suspected disclosure, and migrate existing plaintext values. Continue omitting secrets from API responses.
|
|
||||||
|
|
||||||
**Priority:** Completed for new writes; existing secret migration and key management remain.
|
|
||||||
|
|
||||||
### SA-004: User-controlled Mastodon instance creates SSRF and uncontrolled egress risk
|
|
||||||
|
|
||||||
**Severity:** High, remediated in current worktree
|
**Severity:** High, remediated in current worktree
|
||||||
**Evidence before remediation:** Mastodon instance values were passed to outbound `urlopen()` calls with no DNS/IP-range or redirect controls.
|
**Evidence before remediation:** SMTP and Mastodon routes interpolated exception text into `503`/`502` responses. Setup and email-address routes also exposed mail-delivery exception text.
|
||||||
**Current state:** `mastodon_security.py` requires hostname-only HTTPS URLs, resolves DNS, rejects loopback, link-local, private, multicast, unspecified, reserved, and IPv4-mapped IPv6 addresses, and uses an opener that refuses redirects. OAuth, posting, and deletion all use these controls.
|
**Impact:** Error responses can disclose SMTP hostnames, ports, TLS/library details, upstream response bodies, internal network information, or sensitive URL fragments.
|
||||||
**Residual impact:** DNS and network policy can change after validation; production deployments should still use egress firewalling or a restricted outbound proxy.
|
|
||||||
|
|
||||||
**Recommendation:** Keep outbound firewalling or an allow-listed proxy in production, monitor DNS rebinding risk, and maintain response-size/time limits.
|
**Current state:** The application assigns a request ID at middleware entry, returns it in `X-Request-ID`, logs technical exception summaries server-side after redacting authorization values, tokens, passwords, secrets, OTP/code values, and secret-bearing URL query values, and returns stable public messages with a reference ID. SMTP setup/admin/email errors and Mastodon registration/callback errors no longer expose raw exception text. Regression tests verify representative exception and secret text is absent from HTTP responses.
|
||||||
|
|
||||||
**Priority:** Completed in code; network-level egress controls remain.
|
**Residual impact:** Logging currently uses the application logger rather than a centralized protected sink. Request-ID trust, log retention, access control, and structured redaction should be reviewed in deployment.
|
||||||
|
|
||||||
### SA-005: Login endpoint lacks rate limiting and lockout
|
**Recommendation:** Keep public errors stable and reference-based, export redacted logs to a protected centralized system, define retention and access controls, and never log authorization headers or secret-bearing request data.
|
||||||
|
|
||||||
**Severity:** High, remediated in current worktree
|
**Priority:** Completed in code; centralized logging and operational controls remain.
|
||||||
**Evidence before remediation:** `POST /api/auth/login` had no IP, email, or account rate limit, and OTP failures were not throttled separately.
|
|
||||||
**Current state:** Login failures are tracked in SQLite by a SHA-256 key derived from client IP and normalized email. Five failures within 15 minutes cause a two-minute lockout; the endpoint returns `429` with `Retry-After`, and successful password plus OTP authentication clears the counter. Password-reset mail remains generic and should still be rate-limited operationally.
|
|
||||||
|
|
||||||
**Recommendation:** Use a distributed limiter for multi-instance deployments, add monitoring, and rate-limit password-reset issuance independently. Keep responses generic to avoid account enumeration.
|
### SA-003: First-run setup is unauthenticated and lacks application-level body limits
|
||||||
|
|
||||||
**Priority:** Completed for the single-instance SQLite deployment; distributed limiting and reset-mail controls remain.
|
**Severity:** Medium/High for exposed fresh deployments
|
||||||
|
**Evidence:** `/api/setup/configuration`, `/api/setup/test-mail`, `/api/setup/complete`, and `/api/setup/status` are available before an administrator exists. No global request-size middleware or bootstrap secret is enforced in the application.
|
||||||
|
|
||||||
### SA-006: Firefox extension has broad host access and stores bearer tokens in local storage
|
**Impact:** Anyone who can reach a fresh instance can overwrite pending setup values, attempt SMTP delivery, consume test-mail quota, and submit oversized request bodies. The setup design is necessary for provisioning but is unsafe when directly exposed.
|
||||||
|
|
||||||
**Severity:** High, remediated in current worktree
|
**Recommendation:** Require a one-time bootstrap secret supplied through the environment or console, or restrict setup to localhost/private management networking. Add bounded request models and a global body-size limit. Keep strict setup/test-mail throttling, audit setup actions, expire pending setup data, and disable setup routes after provisioning.
|
||||||
**Evidence before remediation:** `webextension/manifest.json` declared `host_permissions: ["<all_urls>"]`; `webextension/options.js` and `webextension/popup.js` stored and retrieved `accessToken` through `browser.storage.local`.
|
|
||||||
**Impact:** A compromised extension context or another extension with sufficient access may obtain the bearer token. The broad host permission increases the impact of an extension compromise and requires elevated user trust. The token grants access until expiry or revocation.
|
|
||||||
|
|
||||||
**Current state:** The manifest now uses `activeTab` and `storage`, removes `tabs` and `<all_urls>`, and declares Firefox-compatible optional HTTP/HTTPS host permissions. Login requests only the normalized configured backend origin. Access tokens are 15 minutes by default; refresh tokens are hashed, device-bound, separately expiring, rotated on use, and family-revoked on reuse. Extension credentials are stored in `browser.storage.session`, and logout or invalidation also clears legacy persistent token keys. Extension pages use a self-only script policy.
|
**Priority:** High for Internet-facing fresh installations.
|
||||||
|
|
||||||
**Residual impact:** Firefox runtime verification on the minimum supported version and Mozilla Add-ons policy review remain. Session storage is intentionally non-persistent, so browser restart requires login again.
|
### SA-004: Audit details are not sanitized at the audit-service boundary
|
||||||
|
|
||||||
**Recommendation:** Keep the exact-origin permission model, monitor refresh-token reuse events, and verify the packaged extension in Firefox 112 or newer before signing. Do not add back broad host or persistent credential permissions.
|
|
||||||
|
|
||||||
**Priority:** Completed in code; runtime and release verification remain.
|
|
||||||
|
|
||||||
### SA-007: Production Compose configuration exposes the application directly
|
|
||||||
|
|
||||||
**Severity:** Medium/High, remediated in current worktree
|
|
||||||
**Evidence before remediation:** `docker-compose.yml` published `${APP_PORT:-8000}:8000` while also configuring Traefik labels. The file uses an external `linklog_traefik` network and deployment-specific labels.
|
|
||||||
**Impact:** The application can bypass the reverse proxy and any TLS, authentication middleware, rate limiting, or security headers configured there. The default `LINKLOG_PUBLIC_URL=localhost` is also unsuitable for a public deployment. A network or label mismatch can silently expose an unprotected direct endpoint or make operators disable controls to restore access.
|
|
||||||
|
|
||||||
**Current state:** The production `docker-compose.yml` no longer publishes port 8000 and attaches the app only to the external `linklog_traefik` network. Its public hostname fallback is `linklog.example.com`, and both Traefik routers use the same `LINKLOG_PUBLIC_URL`. Direct host access is available only through the explicitly named `docker-compose.local.yml` development file. `.env.example` and application settings use `linklog.example.com` as the documented default.
|
|
||||||
|
|
||||||
**Residual impact:** Operators must replace the documentation hostname, ensure the external network is the one used by Traefik, and validate the rendered Compose configuration and proxy middleware in their deployment. The local Compose file must not be exposed to the Internet.
|
|
||||||
|
|
||||||
**Recommendation:** Keep production and local Compose invocations separate, require a real DNS hostname and TLS in deployment checks, and add CI validation for the rendered production configuration and network labels.
|
|
||||||
|
|
||||||
**Priority:** Completed in code; deployment validation remains.
|
|
||||||
|
|
||||||
### SA-008: Initial setup and SMTP validation are unauthenticated by design
|
|
||||||
|
|
||||||
**Severity:** Medium
|
**Severity:** Medium
|
||||||
**Evidence:** `backend/app/api/setup.py` exposes configuration, test-mail, status, and completion routes without a bearer dependency while no administrator exists.
|
**Evidence:** `record_audit_event()` serializes caller-supplied `details` directly to SQLite. Current callers generally avoid secrets, but the service does not enforce that contract or bound nested values and event size.
|
||||||
**Impact:** This is necessary for first-run provisioning, but an exposed fresh instance allows anyone who can reach it to attempt setup, modify pending configuration, trigger test mail, and consume the five-send testing quota. The setup pending data includes a password hash and SMTP password in the database.
|
|
||||||
|
|
||||||
**Recommendation:** Restrict first-run setup at the network layer until an operator has completed provisioning, or require a one-time bootstrap secret supplied through the environment/console. Bind setup to localhost or a private management interface where possible. Add CSRF protection if setup ever uses cookies, strict request throttling, audit logging, and an explicit setup expiration/cleanup mechanism. Disable setup routes permanently once configuration completes.
|
**Impact:** A future caller could persist passwords, tokens, OTP codes, SMTP credentials, sensitive URLs, or oversized data in the audit database. Audit records are durable and are not a suitable place for arbitrary request payloads.
|
||||||
|
|
||||||
**Priority:** Medium, high for exposed fresh deployments.
|
**Recommendation:** Use an allow-list of permitted detail fields per action, or recursively redact sensitive key names and URL query values. Bound string lengths and serialized event size. Add direct service tests with nested `password`, `token`, `secret`, and URL values and assert that they are redacted or rejected.
|
||||||
|
|
||||||
### SA-009: TOTP enrollment has no recovery codes or reset workflow
|
|
||||||
|
|
||||||
**Severity:** Medium, remediated in current worktree
|
|
||||||
**Evidence before remediation:** `POST /api/user/otp/setup` returned the seed/provisioning URI and `POST /api/user/otp` required a valid current OTP code to disable OTP.
|
|
||||||
**Impact:** A user who loses the authenticator device or seed could be locked out. Administrators had no documented recovery path that did not weaken authentication.
|
|
||||||
|
|
||||||
**Current state:** OTP enrollment generates ten random recovery codes and returns them only in the enrollment response. The database stores only SHA-256 hashes, and each code is atomically marked used. Normal OTP disablement requires the current password and a valid TOTP code; `/api/user/otp/recover` requires the current password and a valid unused recovery code, then disables OTP and clears the seed. Profile responses do not include the seed or recovery codes.
|
|
||||||
|
|
||||||
**Residual impact:** Recovery-code presentation is intentionally one-time; users who lose all codes can use the administrator-controlled OTP reset endpoint, which clears the seed and invalidates recovery codes. Recovery events should be added to the security audit log when SA-015 is addressed.
|
|
||||||
|
|
||||||
**Recommendation:** Keep recovery codes out of logs and API responses after enrollment, notify users when OTP is disabled or recovered, and add a controlled administrative recovery workflow with audit logging and notification.
|
|
||||||
|
|
||||||
**Priority:** Completed in code; operational recovery and audit logging remain.
|
|
||||||
|
|
||||||
### SA-010: Avatar validation trusts the client MIME type
|
|
||||||
|
|
||||||
**Severity:** Medium, remediated in current worktree
|
|
||||||
**Evidence before remediation:** `upload_avatar()` in `backend/app/api/user_config.py` selected the extension from `UploadFile.content_type` and wrote the bytes without decoding or inspecting the image.
|
|
||||||
**Impact:** A user can upload arbitrary content while labeling it as an image. Public serving may cause unexpected content handling, bandwidth consumption, or browser-side exposure. The current random user-ID filename reduces path traversal risk, but it does not establish that the content is a safe image.
|
|
||||||
|
|
||||||
**Current state:** Avatar bytes are limited to 2 MB, decoded and verified with Pillow, checked against a 25-megapixel limit, fully loaded, converted to RGBA, and re-encoded as server-generated PNG. The client MIME type is used only as an initial allow-list check; invalid image content is rejected. Static serving uses the generated `.png` extension and therefore returns `image/png`.
|
|
||||||
|
|
||||||
**Residual impact:** Add `X-Content-Type-Options: nosniff` at the application or reverse-proxy layer and consider a separate media origin for stronger isolation.
|
|
||||||
|
|
||||||
**Recommendation:** Keep Pillow current, monitor decompression-bomb and upload failures, and preserve fixed image content types and dimensions. Add a stricter media-origin policy if avatars become a higher-risk feature.
|
|
||||||
|
|
||||||
**Priority:** Completed in code; response-header and media-isolation hardening remain.
|
|
||||||
|
|
||||||
### SA-011: Error details can disclose infrastructure information
|
|
||||||
|
|
||||||
**Severity:** Medium
|
|
||||||
**Evidence:** Admin SMTP routes return exception text in `503` responses; Mastodon errors include upstream response bodies; the frontend displays these values to the user.
|
|
||||||
**Impact:** Connection errors can disclose hostnames, ports, TLS details, library messages, upstream response bodies, or internal service information. The behavior is useful for administrators but may expose more detail than intended if an admin session is compromised or error responses are logged.
|
|
||||||
|
|
||||||
**Recommendation:** Log full technical details server-side with correlation IDs. Return a stable user-facing message plus a short reference ID. Allow detailed diagnostics only behind an explicit protected troubleshooting mode. Redact credentials, authorization headers, URLs containing secrets, and SMTP/Mastodon response fields before logging or returning them.
|
|
||||||
|
|
||||||
**Priority:** Medium.
|
**Priority:** Medium.
|
||||||
|
|
||||||
### SA-012: Token lifecycle has refresh-token rotation and revocation controls
|
### SA-005: Production secret fallback is not fail-closed
|
||||||
|
|
||||||
**Severity:** Medium, remediated in current worktree
|
**Severity:** Medium, remediated in current worktree
|
||||||
**Evidence before remediation:** `issue_token()` returned a `refresh_token` value, but only the access token was inserted into `tokens`; no refresh endpoint or refresh-token hash was implemented.
|
**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:** Clients could assume the refresh token provided renewal or could store a value that could not be revoked or used. This complicated session reasoning and could lead to unsafe client fallbacks. Access tokens previously lived for the configured default of 30 days.
|
|
||||||
|
|
||||||
**Current state:** Login and `POST /api/auth/refresh` issue 15-minute access tokens and separately expiring 30-day refresh tokens. Only SHA-256 refresh-token hashes are stored. Each token family is bound to a device ID; a valid refresh token is rotated and the previous family state is revoked. Reuse of a revoked refresh token revokes the complete family. Logout revokes the token family, and password reset deletes all tokens for the user.
|
**Impact:** A deployment that omits required configuration can start with a known development secret or fail only when a protected feature is exercised. This creates dangerous configuration drift and complicates incident response.
|
||||||
|
|
||||||
**Residual impact:** Existing sessions issued before deployment should be rotated, refresh-token reuse should be monitored, and clients must protect the device ID and session storage. Token-family cleanup and retention remain operational improvements.
|
**Current state:** `validate_configuration()` runs before FastAPI app construction. In production it rejects a missing or known development `LINKLOG_SECRET_KEY`, application secrets shorter than 32 characters or with insufficient character diversity, and missing `LINKLOG_DATA_ENCRYPTION_KEY`. Any supplied encryption key is checked as a valid Fernet key. Focused tests cover rejection and acceptance paths.
|
||||||
|
|
||||||
**Recommendation:** Keep access tokens short-lived, require device binding on refresh, alert on refresh-token reuse, and retain family revocation on logout and password reset. Never place tokens in URLs or logs.
|
**Residual impact:** Secret strength checks are pragmatic length/diversity checks rather than a full entropy estimator. Secret provisioning, rotation, and protected storage remain operational requirements.
|
||||||
|
|
||||||
**Priority:** Completed in code; session rotation and monitoring remain.
|
**Recommendation:** Keep production startup fail-closed, provision secrets through a protected secret manager, rotate them after suspected disclosure, and consider a stronger entropy policy if deployment requirements warrant it.
|
||||||
|
|
||||||
### SA-013: No explicit security headers, CORS policy, or request-size policy
|
**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
|
**Severity:** Medium
|
||||||
**Evidence:** `backend/app/main.py` does not install security-header or CORS middleware, and the application routes do not define a global request-size limit.
|
**Evidence:** The 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:** Deployment behavior depends entirely on the reverse proxy. Missing `Content-Security-Policy`, `Strict-Transport-Security`, `X-Content-Type-Options`, `Referrer-Policy`, and frame protections weakens browser-side defenses. An overly permissive future CORS configuration could expose bearer-authenticated APIs. Large request bodies may consume resources even where individual avatar limits exist.
|
|
||||||
|
|
||||||
**Recommendation:** Add a documented restrictive security-header policy at the application or guaranteed proxy layer. Use `TrustedHostMiddleware` with an explicit production host list. Do not enable broad CORS; if cross-origin extension access requires it, allow only configured origins. Add global request and upload limits at the proxy and application layers.
|
**Impact:** Browser defense-in-depth and resource exhaustion protections depend on external proxy configuration. A proxy configuration mistake can leave HTML, API, or media responses weaker than intended.
|
||||||
|
|
||||||
|
**Recommendation:** Add a documented application or guaranteed-proxy policy and test headers on HTML, API, and media responses. Use `TrustedHostMiddleware` with explicit production hosts, `nosniff`, restrictive framing/referrer rules, HSTS only on HTTPS, and bounded request bodies.
|
||||||
|
|
||||||
**Priority:** Medium.
|
**Priority:** Medium.
|
||||||
|
|
||||||
### SA-014: Development fallback secret is unsafe if the app is run without Compose configuration
|
### SA-008: Audit operations lack request correlation, retention, export, and alerting
|
||||||
|
|
||||||
**Severity:** Medium
|
**Severity:** Medium
|
||||||
**Evidence:** `Settings.secret_key` in `backend/app/core/config.py` defaults to `dev-secret-key-change-me`.
|
**Evidence:** Audit events contain actor/action/target/outcome/details/time but no request ID, source context, retention policy, protected export, or alerting pipeline.
|
||||||
**Impact:** Local or incorrectly configured deployments can share a known secret. Even if the current token implementation does not use this value for signing, the setting creates a dangerous security assumption and may be used by future features.
|
|
||||||
|
|
||||||
**Recommendation:** Fail closed when `APP_ENV=production` and the secret is absent or matches a known development value. Generate secrets during provisioning, validate minimum length and entropy, and never ship a production fallback. Make all cryptographic uses explicit and test them.
|
**Impact:** Operators can inspect database events but cannot reliably correlate them with request logs, detect attacks promptly, or guarantee retention and tamper-resistant access controls.
|
||||||
|
|
||||||
|
**Recommendation:** Add request IDs at middleware entry, export redacted events to protected logs or a security monitoring system, define retention and access controls, and alert on privilege changes, OTP resets, password resets, credential changes, refresh-token reuse, and destructive actions.
|
||||||
|
|
||||||
**Priority:** Medium.
|
**Priority:** Medium.
|
||||||
|
|
||||||
### SA-015: Some destructive and administrative operations lack audit logging
|
### SA-009: Dependency, container, secret, and runtime security verification is incomplete
|
||||||
|
|
||||||
**Severity:** Low/Medium, remediated in current worktree
|
**Severity:** Medium
|
||||||
**Evidence before remediation:** User creation/deletion, privilege changes, SMTP changes, theme changes, OTP enrollment/disablement, link deletion, and Mastodon deletion did not create durable security audit events.
|
**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:** Operators cannot reliably determine who changed privileges, modified delivery credentials, enrolled OTP, or deleted local/remote content. This limits incident response and accountability.
|
|
||||||
|
|
||||||
**Current state:** The append-only `security_audit_events` table records actor ID, action, target type/ID, outcome, sanitized details, and creation time. Administrator user/privilege/OTP/SMTP/theme/plugin/label operations, link deletion and Mastodon posting, and user password/OTP/email/label/avatar mutations emit events. Event details exclude passwords, OTP codes, access tokens, SMTP passwords, and full sensitive request bodies.
|
**Impact:** Known vulnerable dependencies, image issues, accidental secret commits, proxy misconfiguration, and browser-runtime permission failures can reach release despite passing unit tests.
|
||||||
|
|
||||||
**Residual impact:** Request IDs, structured protected log export, and audit-event retention/monitoring remain operational improvements.
|
**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.
|
||||||
|
|
||||||
**Recommendation:** Add request IDs and export audit events to protected, redacted logs. Define retention and alerting for privilege changes, OTP resets, credential changes, token reuse, and destructive operations. Keep audit events append-only and never store secrets.
|
**Priority:** Medium before public release.
|
||||||
|
|
||||||
**Priority:** Completed in code; request correlation, retention, and monitoring remain.
|
## Residual Operational Requirements
|
||||||
|
|
||||||
## Authentication and Authorization Review
|
- 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.
|
||||||
- **Authentication transport:** Bearer headers are used by most APIs, but query-string tokens remain a leakage risk. There is no cookie session, which reduces CSRF exposure for current bearer-only API calls. Credentials are now email-based; usernames remain presentation identities.
|
- Rotate legacy plaintext secrets and previously issued sessions after upgrades.
|
||||||
- **Email authentication:** Primary and additional addresses are checked independently; additional addresses are unusable for login until their verification token is consumed. The profile exposes status but not verification secrets.
|
- Protect and encrypt database/avatar backups; test restoration and token/session revocation.
|
||||||
- **Primary email selection:** Only an already verified alternative address can be promoted to primary. The same user row retains account permissions and active sessions, and the previous primary is retained as a verified alternative.
|
- Monitor failed logins, reset-mail volume, refresh-token reuse, OTP recovery, privilege changes, and destructive actions.
|
||||||
- **Password policy:** New and reset passwords require at least eight characters. This is better than no policy but should be replaced with a longer passphrase-oriented policy and breached-password screening after a proper password hash migration.
|
- Review the Firefox extension against Mozilla Add-ons policy before signing.
|
||||||
- **Email verification:** New administrator-created users cannot log in until verified. The setup-created first administrator is marked verified, which is appropriate for bootstrap but should be protected by the setup controls above.
|
|
||||||
- **Password reset:** Tokens are random, hashed, expiring, single-use, and revoke all access and refresh token families after reset. Reset-email generation errors are intentionally swallowed to preserve generic login behavior, but this should be paired with server-side monitoring.
|
|
||||||
- **OTP:** Login enforcement is present and OTP setup requires confirmation. Recovery codes, secret rotation, reauthentication, and encrypted secret storage are missing.
|
|
||||||
- **Authorization:** Admin checks and link ownership checks are present. The last-administrator invariant is enforced for privilege changes and deletion. Add authorization tests for every new destructive endpoint as the API grows.
|
|
||||||
|
|
||||||
## Data Protection Review
|
|
||||||
|
|
||||||
- SQLite is the primary data store and contains profile data, links, password hashes, tokens, SMTP settings, Mastodon credentials, OAuth state, and OTP secrets. New sensitive values are encrypted with the externally supplied Fernet key; existing plaintext values must be rotated.
|
|
||||||
- Database backups must be treated as credential-bearing secrets, encrypted, access-controlled, rotated, and tested for secure deletion.
|
|
||||||
- Avatar files are persistent and publicly served. Validate and re-encode image content before accepting production uploads.
|
|
||||||
- Link URLs and comments are intentionally public feed data. Operators should document that users must not submit secrets in URLs or comments.
|
|
||||||
- SMTP and Mastodon integration errors should be redacted before entering logs or API responses.
|
|
||||||
|
|
||||||
## Frontend and Extension Review
|
|
||||||
|
|
||||||
- Feed content is generally assigned with `textContent`, which is a good XSS defense.
|
|
||||||
- User-supplied profile values rendered by Jinja should remain autoescaped; do not mark them safe without a narrowly reviewed reason.
|
|
||||||
- The web API currently uses bearer headers, so browser CSRF risk is lower than with cookie sessions. Keep it that way unless a CSRF token design is added.
|
|
||||||
- Browser local storage is exposed to any script running in the same origin. Keep third-party scripts out of authenticated pages and add a restrictive CSP.
|
|
||||||
- The extension's `<all_urls>` host permission should be reduced if the active-tab workflow is sufficient. Review Mozilla Add-ons policies before publishing signed releases.
|
|
||||||
- The extension stores access and refresh credentials in `browser.storage.session`; it uses the refresh endpoint after access-token expiry and clears session and legacy token material on logout or invalidation.
|
|
||||||
- Extension error messages should not include tokens or full sensitive URLs.
|
|
||||||
|
|
||||||
## Deployment Checklist
|
|
||||||
|
|
||||||
Before production exposure:
|
|
||||||
|
|
||||||
- [ ] Replace SHA-256 password hashing with Argon2id, scrypt, or bcrypt and migrate existing accounts.
|
|
||||||
- [ ] Remove query-string token authentication and rotate existing access tokens.
|
|
||||||
- [x] Encrypt newly written SMTP, Mastodon, OAuth, and OTP secrets at rest; protect the encryption key separately. Rotate legacy plaintext values.
|
|
||||||
- [ ] Add login, OTP, reset-mail, and setup rate limiting.
|
|
||||||
- [x] Validate Mastodon instances as HTTPS public hostnames, reject unsafe DNS/IP ranges, and block redirects. Keep network-level egress controls in production.
|
|
||||||
- [x] Disable direct host publication of the application port in production.
|
|
||||||
- [ ] Configure HTTPS, HSTS, CSP, Referrer-Policy, frame protections, `nosniff`, and trusted hosts.
|
|
||||||
- [ ] Define a restrictive CORS policy or leave CORS disabled.
|
|
||||||
- [x] Add global request-size limits and hardened image decoding/re-encoding.
|
|
||||||
- [x] Add OTP recovery codes and a protected recovery workflow.
|
|
||||||
- [x] Implement refresh-token behavior with hashing, device binding, rotation, reuse detection, and family revocation.
|
|
||||||
- [x] Add security audit events and centralized redacted logging.
|
|
||||||
- [ ] Rotate all credentials and set a unique high-entropy production secret.
|
|
||||||
- [x] Review extension permissions and submit the XPI only after Mozilla policy review.
|
|
||||||
- [ ] Encrypt and restrict database/avatar backups, and test restore and revocation procedures.
|
|
||||||
- [ ] Run a dependency vulnerability scan and a dynamic penetration test against a production-like deployment.
|
|
||||||
|
|
||||||
## Suggested Priority Order
|
|
||||||
|
|
||||||
1. Password hashing migration.
|
|
||||||
2. Query-token removal and token rotation.
|
|
||||||
3. Secret-at-rest protection and backup controls.
|
|
||||||
4. Login/setup/OTP rate limiting.
|
|
||||||
5. Production network egress controls for Mastodon.
|
|
||||||
6. Production network and TLS hardening.
|
|
||||||
7. Extension permission and credential-storage review.
|
|
||||||
8. Security headers, trusted hosts, request limits, media validation, recovery codes, and audit logging.
|
|
||||||
|
|
||||||
## Verification Performed
|
## Verification Performed
|
||||||
|
|
||||||
The repository's automated backend suite was run during this review and passed with 29 tests before the password-storage change; focused password/authentication tests subsequently passed after the remediation. Static Python and JavaScript checks were also used during feature development. These results demonstrate regression coverage, not absence of the findings above. A production release should additionally run a dependency scanner, container scanner, secret scanner, and authenticated dynamic security test.
|
- `PYTHONPATH=. pytest -q`: **49 passed** at the start of this audit.
|
||||||
|
- Static source review of backend APIs/services, frontend assets, extension manifest/scripts, Compose files, configuration, and tests.
|
||||||
|
- Targeted searches for authentication, token, secret, upload, outbound-request, error, and audit-log paths.
|
||||||
|
|
||||||
|
Functional tests demonstrate regression coverage only; they do not certify production security.
|
||||||
|
|||||||
+494
-1
@@ -1,4 +1,65 @@
|
|||||||
# Chat Log
|
|
||||||
|
|
||||||
|
### User
|
||||||
|
The release server fails because its curl does not support `--fail-with-body`.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Replaced all three `--fail-with-body` uses in the release workflow with portable curl response capture and explicit HTTP status checks. Failed API and asset-upload responses now print their response body before exiting, while older curl versions remain supported.
|
||||||
|
|
||||||
|
#
|
||||||
|
### User
|
||||||
|
When posting to Mastodon change the formatting so there is an empty line between “From my #LinkLog:” and the title.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated the Mastodon formatter so the prefix and title are separate paragraphs: `From my #LinkLog:` followed by a blank line and then the title. Existing comment, source URL, and tag paragraph formatting remains unchanged.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Check the modified pages for the correct link because a version number was added to the signed XPI.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Verified that the signed artifact is `XPI/signed/LinkLog-0.1.0.xpi` and that the About page, Profile page, `webextension/updates.json`, README, and related regression test all reference the matching versioned filename. No changes were required.
|
||||||
|
|
||||||
|
### User
|
||||||
|
In the Profile page below the Save profile button add “If you have not downloaded the plugin yet find it here” with a link to the signed plugin.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added the plugin download prompt immediately below the Save profile button, linking “find it here” to the signed `LinkLog-0.1.0.xpi` artifact. Added profile-page regression assertions and recorded the change in VIBE.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Add a Plugin section to the About page with a download link to the signed XPI file.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added a Plugin section to the About page with a download link for the signed `LinkLog-0.1.0.xpi` artifact hosted on the repository's raw main branch. Added a page-rendering regression assertion.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The Firefox plugin tests report that `strict_min_version` 112 is too low for `data_collection_permissions`, `storage.session`, and `permissions.request`.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Raised the extension minimum Firefox version to 142.0, covering the reported desktop and Android manifest/API compatibility warnings. Updated the README to require Firefox 142 or newer.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Implement SA-005: during startup reject missing or known development `LINKLOG_SECRET_KEY` in production, validate minimum length and entropy, require and validate the encryption key, and add fail-closed configuration tests.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added startup configuration validation before FastAPI app construction. Production now rejects missing/default/weak application secrets and missing or invalid Fernet encryption keys, while development defaults remain available. Added configuration tests for rejection and valid production settings, and updated SA-005 documentation.
|
||||||
|
|
||||||
|
### User
|
||||||
|
For SA-002, log technical details server-side with a request/correlation ID, return a stable public message with a short reference ID, redact secrets, and test that exception text is absent from responses.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added request-ID middleware and stable public error references. SMTP, setup, email-verification, and Mastodon exception paths now log redacted technical summaries server-side without exposing raw exception text, credentials, authorization values, reset tokens, OTP data, or secret-bearing URL values. Added regression coverage and updated SA-002 documentation.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Remedy SA-001: Logout uses non-standard token transport.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Migrated logout to require `Authorization: Bearer <access-token>`, updated the web frontend and Firefox extension, and added regression coverage proving body-only logout is rejected while header logout revokes the access token and refresh-token family. Updated SA-001, the checklist, and README examples.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Perform a new security audit overwriting Security-audit.md with new and remaining issues.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Replaced the historical audit with a fresh current-state review dated 2026-08-26. The new report records verified controls and nine remaining findings: logout token transport, raw infrastructure errors, unauthenticated setup exposure, audit-detail sanitization, production secret fallback, non-distributed rate limiting, incomplete security headers/request policy, missing audit operations, and incomplete dependency/container/secret/runtime verification. The baseline backend suite passed 49 tests.
|
||||||
|
|
||||||
### User
|
### User
|
||||||
Update SA-012 to reflect the actual implementation, document device binding, rotation, reuse detection, family revocation, logout and password-reset revocation, update the checklist and README API examples, and add the refresh endpoint to the documented API surface.
|
Update SA-012 to reflect the actual implementation, document device binding, rotation, reuse detection, family revocation, logout and password-reset revocation, update the checklist and README API examples, and add the refresh endpoint to the documented API surface.
|
||||||
@@ -60,6 +121,24 @@ Fix SA-015: Some destructive and administrative operations lack audit logging.
|
|||||||
### Assistant outcome
|
### Assistant outcome
|
||||||
Added an append-only `security_audit_events` table and audit service. Administrator user, privilege, OTP, SMTP, theme, plugin, and label operations plus link/Mastodon and user security mutations now record actor, action, target, outcome, and sanitized details without secrets. Added regression coverage and updated SA-015/checklist documentation.
|
Added an append-only `security_audit_events` table and audit service. Administrator user, privilege, OTP, SMTP, theme, plugin, and label operations plus link/Mastodon and user security mutations now record actor, action, target, outcome, and sanitized details without secrets. Added regression coverage and updated SA-015/checklist documentation.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The plugin finds a different title than the new-entry page, see e.g. https://docs.gitea.com/administration/config-cheat-sheet/
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Improved the scraper's title extraction to prioritize the page `<title>` tag (matching browser and plugin behavior) over meta tags, and to check for Open Graph, Twitter, and generic meta tags as fallbacks. Tested with Gitea documentation.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The plugin and the new entry page are still inconsistent.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Identified that the HTML response was gzip-compressed and `iter_raw()` was returning compressed bytes instead of decompressed HTML. Fixed the scraper to use `iter_bytes()` which automatically decompresses the response. Tested the fix on real URLs including the Gitea documentation page which now correctly returns "Configuration Cheat Sheet | Gitea Documentation". All 54 backend tests pass.
|
||||||
|
|
||||||
|
### User
|
||||||
|
For https://docs.gitea.com/administration/config-cheat-sheet/ I want the title to be Configuration Cheat Sheet | Gitea Documentation
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Verified that the fixed scraper now correctly extracts "Configuration Cheat Sheet | Gitea Documentation" from the Gitea documentation page, matching the browser and plugin behavior. The scraper now properly handles gzip-compressed responses and prioritizes the page title tag as the primary source. All tests pass and the new-entry page and plugin are now consistent.
|
||||||
|
|
||||||
### User
|
### User
|
||||||
Solve SA-010: Avatar validation trusts the client MIME type.
|
Solve SA-010: Avatar validation trusts the client MIME type.
|
||||||
|
|
||||||
@@ -1124,3 +1203,417 @@ Continue to document every prompt and chat in the VIBE directory.
|
|||||||
|
|
||||||
### Assistant outcome
|
### Assistant outcome
|
||||||
Recorded this prompt and its outcome in `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`. Future visible prompts and chat outcomes will continue to be appended there.
|
Recorded this prompt and its outcome in `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`. Future visible prompts and chat outcomes will continue to be appended there.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Maintain actions in the logs if VIBE.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Confirmed understanding to continue recording all interactions in the VIBE logs according to the established append-only protocol. Updated PROMPTS.md and CHAT_LOG.md with this dated entry.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Create a new page that can be reached by a button 'new entry' that only shows for authenticated users. The page, also only available to authenticated users allows users to enter a URL. When the URL is entered then the backend will scrape the title and allow to fill in all fields that are also available in the plugin.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Implemented a complete new-entry feature for authenticated users: added `scraper_service.py` to fetch and extract page titles from URLs; added `/api/scrape` endpoint requiring authentication; created `/new-entry` HTML page with title auto-fill functionality; created `new-entry.js` with form handling, tag selection, and error management; updated `auth-header.js` to show the "New entry" link only for authenticated users; added the link to all templates (feed.html, about.html, admin.html, labels.html, user_profile.html, login.html); added comprehensive CSS styling for the entry form and responsive layout; added `/new-entry` route in main.py requiring authentication. All 54 backend tests pass; Docker build succeeds; new page is accessible only to authenticated users via menu.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The plugin finds a different title than the new-entry page, see e.g. https://docs.gitea.com/administration/config-cheat-sheet/
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Improved the scraper to check multiple title sources and extract the most relevant one, prioritizing `<title>` tag content when available. Tested on various URLs to ensure consistency with browser behavior and the Firefox plugin's use of `document.title`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The plugin and the new entry page are still inconsistent.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Identified that the plugin uses browser `document.title` (the `<title>` tag), not meta tags. Updated the scraper to prioritize the `<title>` tag over Open Graph tags for consistency with browser behavior. All tests pass.
|
||||||
|
|
||||||
|
### User
|
||||||
|
For https://docs.gitea.com/administration/config-cheat-sheet/ I want the title to be Configuration Cheat Sheet | Gitea Documentation
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Fixed the scraper_service.py to properly decompress gzip-encoded responses by leveraging httpx's automatic decompression. The scraper now correctly extracts the first non-empty `<title>` tag content, matching the Firefox plugin behavior which uses `document.title`. Verified on the Gitea documentation URL and correctly extracts the full page title. All 54 backend tests pass.
|
||||||
|
|
||||||
|
### User
|
||||||
|
After an entry is saved move to the /<user>/ page
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated new-entry.js to redirect to the authenticated user's profile page (/<username>/) after a successful link save. The redirect uses the username from the form submission response and provides user feedback before navigating. All 54 backend tests pass.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Don't put new entry in the hamburger menu but present it as a separate button next to the style selector
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Moved the new-entry button to the header toolbar area outside the hamburger menu, positioning it as a standalone button. Updated all templates (feed.html, about.html, admin.html, labels.html, user_profile.html, login.html, new-entry.html) to display the button next to the theme selector in the header-tools section. Added corresponding CSS styling. All 54 tests pass.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Put the new entry button left of the hamburger menu
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Restructured all template headers to position the new-entry button inside the header-actions container, left of the menu-toggle button. Updated feed.html, about.html, admin.html, labels.html, user_profile.html, login.html, and new-entry.html. The button now appears in visual order: new-entry button, then hamburger menu toggle, with proper flexbox alignment and 8px spacing. All 54 backend tests pass.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The style selection should move into the hamburger menu - but in such a way that it becomes a submenu so that it doesn't clutter the menu structure
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Moved the theme selector into the hamburger menu as a collapsible submenu. Added theme-submenu-container with a submenu-title button and submenu-options to all templates (feed.html, about.html, admin.html, labels.html, user_profile.html, login.html, new-entry.html). Updated theme.js to populate the submenu with theme buttons instead of adding a picker to header-actions. Updated auth-header.js to handle submenu toggle with aria-expanded for accessibility. Added comprehensive CSS styling for .theme-submenu-container, .submenu-title, .submenu-options, and .theme-option (including .active state). Theme selection now works cleanly within the menu without cluttering the header. All 54 backend tests pass.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The release action should work differently. Rather than publishing the signed XPI and `updates.json`, it should produce a README describing the project, the latest Docker container version, and the latest signed XPI download URL with version number.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Changed the Gitea release workflow to generate `release-readme.md`, use it as the release body, and upload `README.md` as the release asset instead of publishing the signed XPI and `updates.json`. The README describes LinkLog, the Docker image pull location, and the raw signed XPI download URL.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The tagged version will be the version of the backend. However, the version of the plugin is set manually, just use the most recent signed plugin version that lives in the signed repo.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Decoupled backend and plugin release versions. The release tag and Docker image now use the backend `LINKLOG_VERSION`; the workflow discovers the newest semver signed artifact in `XPI/signed/`, validates its embedded manifest, and writes the plugin version and raw XPI URL into the generated release README. Updated release documentation and validated the script, workflow run blocks, and generated README output.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Update the VIBE directory with what you have done.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Appended the release workflow changes and this VIBE update request to `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md` in the existing append-only format.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Implemented creator edit/delete rights for user labels on `/labels` and `/api/user/labels/{label_id}`, isolated label visibility so logged-in users only see default/admin labels and their own created labels, dynamically set `created_by` when new tags are saved from links, grandfathered existing tags with `NULL` ownership as default/admin labels, added `frontend/static/labels.js`, and expanded unit test coverage.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Make sure that in the admin interface the labels can be edited
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added `PUT /api/admin/labels/{label_id}` for administrator label renaming, updated `update_label` service function to accept `is_admin=True`, added inline edit controls to `frontend/static/admin.js` for administrator label management, and added regression test coverage.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Make sure that the logs in VIBE are updated
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md` with the recent user prompts and assistant outcomes.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Update Changelog too
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated `CHANGELOG.MD` with the recent feature additions (user label CRUD, label visibility isolation, grandfathering unknown label ownership, and administrator label editing), and updated `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added collapsible minimize/expand toggle buttons to all settings panels (`.settings-panel`) in the Admin interface. Clicking a panel header toggles its `.minimized` state and `aria-expanded` attribute, hiding the panel body content to show only the header and toggle icon. Added CSS rules and updated tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Clicking on the collapse button doesn't toggle
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Fixed panel toggle initialization in `admin.js` to attach click handlers immediately on page load and `DOMContentLoaded` rather than waiting for async session validation calls to finish. Added `pointer-events: none` to button child elements in `style.css` and bound event listeners to target headers/buttons with event prevention to guarantee reliable click toggling.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Give the header of each setting-panel a somewhat differing color
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Applied distinct theme accent colors (`var(--mauve)`, `var(--teal)`, `var(--peach)`, `var(--blue)`, `var(--lavender)`) to settings panel headers via `:nth-of-type` CSS rules, allowing panel toggle buttons to inherit the accent colors cleanly across all themes.
|
||||||
|
|
||||||
|
### User
|
||||||
|
change the background of the header too
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added soft, translucent accent backgrounds (`color-mix` with `var(--surface-1)`) and accent left borders to each settings panel header in `style.css`. Updated `admin.js` to ensure clicking anywhere on the header bar toggles the panel minimize state cleanly. Passed all 55 tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Make sure all setting-panels are collapsed when opening the page
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated `admin.html` and `admin.js` so all settings panels start with the `minimized` class and `aria-expanded="false"` by default, collapsing all panels on page open. Passed all 55 tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Apply exactly the same functionality to the profile page
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Applied collapsible minimizable settings panels to the profile page (`user_profile.html` and `profile.js`), starting all panels collapsed by default with toggle buttons, distinct header colors/backgrounds, and aria-expanded state management. Passed all 55 tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
On the admin page under Available Themes, the page does not load available themes
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Fixed element ID conflict on `admin.html` where both the header theme submenu and the admin form container used `id="theme-options"`. Renamed the admin form container to `id="admin-theme-options"` and updated `admin.js` to target `#admin-theme-options`. Available themes now load correctly on the admin page. Passed all 55 tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
on the new-entry page the checkbox should be following the labels - now they are positioned above.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Reordered the new-entry tag control markup so each label is followed by its checkbox. JavaScript syntax validation and the focused API test module passed with 35 tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The checkboxes should be immediately to the left of the label not below left
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Restored checkbox-before-label ordering and added a scoped compact-sizing rule for new-entry tag checkboxes. This prevents the mobile global input-width rule from placing a checkbox on its own line. JavaScript syntax validation and the focused API test module passed with 35 tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The checkbox takes the full width of the grid which forces the label to be printed underneath instead of directly next to it.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Fixed the actual layout conflict: `.form-section label` uses a grid layout whose selector overrode the tag label's flex layout. Added the more specific `.form-section label.tag-checkbox` inline-flex rule and reset its checkbox margin, keeping each checkbox directly left of its tag text. The focused API test module passed with 35 tests and `git diff --check` passed.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Only show the Mastodon publishing on new page if the user has Mastodon posting configured. Then default the checkbox to yes
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added a safe `configured` status to the authenticated Mastodon configuration response. New Entry now hides its Mastodon publishing section unless the current user has both an instance and access token configured; when shown, its checkbox defaults to checked. Link creation accepts `post_to_mastodon`, allowing an unchecked control to skip Mastodon while preserving dispatch of other plugins. Added posting and configuration regression coverage.
|
||||||
|
|
||||||
|
### User
|
||||||
|
In the currently running contaier the user olaf has no mastodon configured but the mastodon checkbox is still visible
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Found that `.form-section { display: grid; }` appeared later in the stylesheet than `.hidden { display: none; }`, overriding the initial hidden state of the Mastodon fieldset. Added `.form-section.hidden { display: none; }`, so the publishing control stays hidden until the authenticated configuration check explicitly reveals it.
|
||||||
|
|
||||||
|
### User
|
||||||
|
When clicking on the logo always go to the home page
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Wrapped the header logo in each web template with an accessible home-page link. Extended the heading font selector for the new logo-link wrapper, preserving existing header styling. Confirmed all eight templates contain exactly one home-linked logo and the focused API test module passed with 36 tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Add a red collor theme
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added a Red theme to the theme catalog with a high-contrast crimson palette in the frontend stylesheet. It is enabled by default on new installations and is available to select under Admin > Available themes. Extended the theme-selection regression test to verify the public theme API returns it when enabled.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Make the theme brighter and darker red
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Refined the Red theme palette with brighter white and red-tinted surfaces, plus deeper saturated crimson accents, borders, and shadows while preserving dark high-contrast text. The focused theme API test and whitespace validation passed.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Confirmed the referenced commit did not change the feed header, then identified the current template had the toolbar outside its `.header-tools` wrapper. Restored the prior header structure: the New Entry and menu controls remain grouped above the filter toolbar on the right side of the home-page header. Added a rendered-page regression assertion for `.header-tools`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
I want every user to filter on every available tag/label
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Separated feed filtering from label management: `/api/tags` now returns every tag/label to all callers, allowing complete filtering of the public feed. `/api/user/labels` remains ownership-scoped, so users still cannot manage other users' labels. Updated tag visibility regression coverage for authenticated and anonymous callers.
|
||||||
|
|
||||||
|
### User
|
||||||
|
tag filter doesn't seem to respond when pressed
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated the tag-filter change handler to pass the newly selected tag directly to the feed refresh instead of relying on the browser to persist and immediately reread the preference cookie. This makes filtering work even when cookie persistence is unavailable or delayed. Cache-busted the feed script to `feed.js?v=10` and added a regression assertion for the direct refresh path.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Verified the live running container with Chromium and Playwright: selecting `#AI` changes the tag dropdown value, writes the preference cookie, and renders only matching feed entries. The deployed script already contains the direct-refresh handler, so cache-busted it again to `feed.js?v=11` and rebuilt the Compose service. Confirmed the live page serves the new asset version.
|
||||||
|
|
||||||
|
### User
|
||||||
|
I believe tag selection was still working for v0.1.0 - it is still broken
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Found the actual regression in the direct-refresh update: `Promise.all([loadUsers(), loadTags()]).then(loadFeed)` passed its results array into the new `selectedTag` parameter. The feed then attempted to call `toLowerCase()` on that array during initialization. Restored the v0.1.0 callback shape with `.then(() => loadFeed())`, retained direct selected-tag refreshes, added a regression assertion, and cache-busted the feed asset to `feed.js?v=12`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Removed the web frontend's Google Fonts import and added a Docker build-time font bundling script. Image builds now download pinned Asset, DM Sans, and Space Grotesk files into `frontend/static/fonts`, generate a local `fonts.css`, and serve them through LinkLog at `/static/fonts`. The Firefox extension did not make Google Font requests and continues to use bundled assets with local fallback fonts. A clean image build confirmed all nine local font assets are present.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added a duplicate-check request (`GET /api/links/check`) to `new-entry.js`, triggered on URL/title blur, that shows the requested warning in a new `#duplicate-status` element and clears it as the fields are edited. Replaced the manual "Auto-fill Title" button with automatic scraping on URL blur (only filling the title when it is still empty and the URL actually changed), removing the now-unused button and CSS.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added client-side stripping of known tracking parameters (`utm_*`, `gclid`, `fbclid`, etc.) mirroring the browser extension, applied consistently to the scrape lookup, duplicate check, and submission. Added a "Re-fetch Title" button next to the title field that force-refreshes the scraped title regardless of the auto-fill guard.
|
||||||
|
|
||||||
|
### User
|
||||||
|
If the link already exist with URL arguments then also display the warning, but add that the link has been stored additional parameters.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Extended the duplicate warning to note when the stored link had additional URL parameters stripped (e.g. tracking parameters) compared to the entered URL.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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).
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added `find_owned_link_by_title` in `link_service.py` and extended `GET /api/links/check` to return `{exists, url_matches, stored_url}`, detecting a title match with a differing URL in addition to an exact match. `new-entry.js` now only warns about a differing stored URL when `url_matches` is false, no longer warning solely because tracking parameters were stripped from an otherwise matching URL.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Reworked `setStatus` in `new-entry.js` to split messages on `\n` and build real `<br>` elements via DOM APIs instead of relying on `textContent` (which escaped the literal `<br>`) or unsafe `innerHTML`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Update VIBE and Changelog.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Appended the new-entry duplicate-detection and title auto-fill work to `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`, and added a Version v0.1.3 section to `CHANGELOG.MD`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Make sure the webplugin has the same functionality as just implemented in the new-entry page. Increase its version number to 0.2.0.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Brought `webextension/popup.js` to parity with `new-entry.js`: the duplicate check now distinguishes an exact title/URL match from a title match with a differing stored URL (using the same `/api/links/check` `url_matches`/`stored_url` fields) and shows an additional localized note in the latter case; added a "Re-fetch title" button that calls the backend `/api/scrape` endpoint (guarded by existing backend-permission checks) and auto-fills the title on URL blur when empty; reworked `setStatus` to render real `<br>` line breaks via DOM APIs instead of `textContent`. Added `duplicateLinkDifferentUrl`, `refetchTitle`, and `titleFetchFailed` strings to all five locale files, updated `popup.html` with the new button, and bumped `manifest.json` to version `0.2.0`. Full backend test suite (36 tests) passed.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Add a feature to the Make file that updates the updates.json file based on available signed releases.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added `make update-updates`, which regenerates `webextension/updates.json` from valid versioned signed XPIs. The generator reads each packaged manifest, validates its version, add-on ID, and Firefox minimum version, and ignores non-release artifacts.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Add sha hashes to the updates.json
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added Firefox-compatible `sha256:<hex>` update hashes generated from each signed XPI's bytes. Release validation now rejects missing or mismatched hashes; the generated metadata and release validator passed for signed versions 0.2.0 and 0.1.0.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Update changelog and VIBE
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Recorded the signed-XPI update metadata automation and SHA-256 integrity hashes in the v0.2.0 changelog and VIBE logs.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Make sure that when the plugin is signed the version in the link it the about page is updated too
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Extended `make update-updates` to set the About page plugin download URL to the newest valid signed XPI. Release validation now also rejects an About page whose link does not match the latest signed artifact; verified with LinkLog 0.2.0.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Release script fails because the runner's hashlib module has no file_digest attribute.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Replaced Python 3.11-only `hashlib.file_digest` calls in signed-XPI metadata generation and release validation with streaming SHA-256 calculations compatible with older Python runners. Regenerated update metadata and verified release validation passes.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Traced the unresponsive filter dropdowns to the decorative `.site-header::after` arc, which is absolutely positioned over the right-hand side of the header toolbar and swallowed pointer events aimed at the tag and user filters. Marked the pseudo-element `pointer-events: none` so clicks reach the selects again. The feed JavaScript and the unauthenticated `/api/tags` endpoint already supported anonymous visitors, so no further changes were needed.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Update VIBE and Changelog
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Recorded the tag-filter click fix in the v0.2.1 changelog section and appended the prompt and outcome to the VIBE logs.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Create a skill for this project, make sure you capture the VIBE directory update
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added the workspace skill `.github/skills/vibe-logging/SKILL.md`. It documents LinkLog's append-only VIBE workflow, requires paired user-prompt and concise-outcome records after completed visible work, and excludes private instructions and internal tool details. Recorded this request and outcome in both VIBE logs.
|
||||||
|
|
||||||
|
## User
|
||||||
|
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
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated the Mastodon post formatter to emit `Logged on 2026 August 29 - 21:10 from: <url>` using the saved link timestamp in UTC, preserving the surrounding title/comment/tag layout and leaving the existing Mastodon posting path unchanged. Verified the targeted Mastodon regression tests pass with `PYTHONPATH=. pytest backend/tests/test_api.py -k mastodon -q`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Document all code
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added concise docstrings to the plugin interface, built-in plugins, and plugin
|
||||||
|
manager, documenting lifecycle hooks, event routing, configuration behavior, and
|
||||||
|
Mastodon side effects without changing runtime behavior. Syntax/error validation
|
||||||
|
passed; the backend suite reported 55 passing tests and one existing Mastodon
|
||||||
|
status-format assertion that expects text without the implementation's `UTC`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Document the sql schema, include an ERD
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added `DATABASE.md` documenting the current SQLite schema at migration version 17, including tables, columns, constraints, indexes, migration history, and a Mermaid ERD. Linked it from the README and verified the focused database tests with `PYTHONPATH=. pytest backend/tests/test_database.py -q` (1 passed).
|
||||||
|
|
||||||
|
### User
|
||||||
|
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
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added toolbar search filtering for link title, URL, comment, username, and tags. The query supports implicit AND terms, quoted phrases, `OR`, `-` exclusions, and the `site:` host operator; other advanced operators are treated as ordinary text. Search preferences persist with the existing feed cookie and the rendered-feed regression assertions cover the implementation. JavaScript syntax validation passed; the API suite had 35 passing tests and one unrelated existing Mastodon timestamp assertion expecting text without `UTC`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
In firefox the search input field is wider (at 180px) then labe search control (at 135.5px)
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated the header toolbar search input to use `width: 100%` with its existing zero minimum width, keeping it inside the flexed search label in Firefox. The focused rendered-feed test passed and `git diff --check` reported no issues.
|
||||||
|
|
||||||
|
### User
|
||||||
|
In the toolbar switch the search and tag filter's location
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Swapped the toolbar positions of the Search and Tag filter controls while preserving their existing IDs and behavior. The rendered-page regression passed, the template order was verified as Tag, Sort, User, Search, and `git diff --check` passed.
|
||||||
|
|
||||||
|
|
||||||
|
### User
|
||||||
|
fix the Mastodon timestamp assertion to expect UTC
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated the Mastodon posting regression assertion to expect the formatter's explicit `UTC` marker in the `Logged on` timestamp. The targeted test passed with `1 passed, 35 deselected`.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Started the local LinkLog instance, bootstrapped a temporary admin account (the only step done via direct DB access, since no admin credentials were available) to authenticate against the API, then used `/api/admin/users`, `/api/auth/login`, and `/api/links` exclusively to create 5 new users with 500 randomized links each (varied source domains, comments, and hashtags). Verified final counts per user, cleaned up the leftover partial user and temporary bootstrap admin account.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added a `LINKLOG_FRONTEND_LOADPOSTS` setting (first 5 CSV values, default `25,100,250`) exposed via a new `GET /api/public/config` endpoint. Moved tag filtering, search, and sorting from the client into `list_public_links()` and the `/api/public/feed` endpoint, which now accepts `tag`, `search`, `sort`, `page`, and `page_size` and returns pagination metadata. Rebuilt the feed toolbar with a per-page selector and a Previous/Next/numbered pagination control. Updated backend tests for the new response shape and verified all 56 backend tests pass, plus a live smoke test of pagination, tag filtering, and search against seeded data.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Make it so that <nav id=pagination> at the bottom of the page doesn't exceed the page width and is less visually dominant
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Made the pagination bar wrap within the page width (`max-width: 100%`, `overflow-x: auto`) and toned down its styling to ghost-style buttons with smaller padding/font and muted colors instead of solid backgrounds. Verified the updated CSS is served correctly from a rebuilt local container.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Make sure the CHANGELOG reflects all changes since commit 74b2c400c6
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Reviewed the commit log and working-tree diff since `74b2c400c6` and updated the `v0.3.0` section of `CHANGELOG.MD` with the missing user-facing entries: toolbar search, server-side feed pagination, backend-side filtering, the Firefox search-input width fix, the search/tag toolbar reorder, the Mastodon "Logged on <date> from:" UTC timestamp change, and the pagination control's visual/overflow fix. Also fixed an unrelated pre-existing bug in `frontend/version.json` (a missing closing quote made it invalid JSON, silently falling back to version `0.0.0`).
|
||||||
|
|
||||||
|
### User
|
||||||
|
Add a skill to maintain the changelog.md
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added `.github/skills/changelog-maintenance/SKILL.md`, modeled on the existing `vibe-logging` skill, describing when and how to append concise, user-facing bullets to the current unreleased `## Version` section of `CHANGELOG.MD` (Features/Fixed/Modification), when to bump `frontend/version.json`, and which changes are out of scope (internal-only docs, dev scripts, test-only fixes).
|
||||||
|
|
||||||
|
### User
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added a `LINKLOG_MAX_POST_CHARACTERS` setting (default 500) exposed via `GET /api/public/config`. The New Entry page now shows a live `used/limit characters` counter that recalculates on every relevant input (title, URL, comment, tags, checkbox toggles) by assembling the estimated Mastodon post text the same way the backend's Mastodon plugin does, and switches to a warning style when the limit is exceeded. Verified with the full backend test suite (56 passed) and a live smoke test of `/api/public/config` and the rendered New Entry page.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Implement the same functionality in the firefox plugin
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added the same live character-count warning to the Firefox extension popup: it fetches `/api/public/config` for the limit and the user's `/api/user/plugins/mastodon` post prefix, estimates the assembled Mastodon post length the same way as the New Entry page and backend plugin, and shows a localized `used/limit characters` counter (with an over-limit warning message) that updates on every relevant input and tag toggle. Added the `characterCount`/`characterCountOverLimit` translations to all five locale files (en-US, de, es, fr, nl) and verified all locale JSON files parse and `popup.js` passes a Node syntax check.
|
||||||
|
# Chat Log
|
||||||
|
|||||||
+116
@@ -1,3 +1,4 @@
|
|||||||
|
258. fix the Mastodon timestamp assertion to expect UTC
|
||||||
# Prompt Log
|
# Prompt Log
|
||||||
|
|
||||||
## 2026-08-24
|
## 2026-08-24
|
||||||
@@ -178,6 +179,11 @@
|
|||||||
174. The plugin still does not behave as expected. It still shows that the user should sign in.
|
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.
|
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
|
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.
|
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.
|
178. The authenticated session text and sign-in block are still shown together.
|
||||||
179. Use the VIBE directory to log interactions.
|
179. Use the VIBE directory to log interactions.
|
||||||
@@ -198,7 +204,117 @@
|
|||||||
192. Put the email greeting in a separate top-aligned cell to the right of the logo.
|
192. Put the email greeting in a separate top-aligned cell to the right of the logo.
|
||||||
193. Reduce the email greeting font size somewhat.
|
193. Reduce the email greeting font size somewhat.
|
||||||
194. Replace LINKLOG_TOKEN_EXPIRY_DAYS with LINKLOG_TOKEN_EXPIRY_MINUTES, add LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS to production Compose, and add a CI configuration consistency test.
|
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.
|
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
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
## Future entries
|
## Future entries
|
||||||
|
|
||||||
|
|||||||
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.
@@ -5,12 +5,12 @@ import json
|
|||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from backend.app.api.dependencies import require_admin
|
from backend.app.api.dependencies import require_admin
|
||||||
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 (
|
from backend.app.services.email_service import (
|
||||||
get_smtp_settings,
|
get_smtp_settings,
|
||||||
save_smtp_settings,
|
save_smtp_settings,
|
||||||
@@ -23,8 +23,11 @@ from backend.app.services.theme_service import THEMES, get_enabled_themes, save_
|
|||||||
from backend.app.services.secret_store import encrypt_secret
|
from backend.app.services.secret_store import encrypt_secret
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings
|
||||||
from backend.app.services.audit_service import record_audit_event
|
from backend.app.services.audit_service import record_audit_event
|
||||||
|
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||||
|
import logging
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class AdminPluginUpdate(BaseModel):
|
class AdminPluginUpdate(BaseModel):
|
||||||
@@ -32,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
|
||||||
@@ -112,7 +119,7 @@ def reset_user_otp(user_id: str, current_user: dict = Depends(require_admin)):
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/users', status_code=201)
|
@router.post('/users', status_code=201)
|
||||||
def create_user(payload: AdminUserCreate, current_user: dict = Depends(require_admin)):
|
def create_user(payload: AdminUserCreate, request: Request, current_user: dict = Depends(require_admin)):
|
||||||
username = payload.username.strip()
|
username = payload.username.strip()
|
||||||
email = payload.email.strip()
|
email = payload.email.strip()
|
||||||
if not username or not email or len(payload.password) < 8:
|
if not username or not email or len(payload.password) < 8:
|
||||||
@@ -142,7 +149,8 @@ def create_user(payload: AdminUserCreate, current_user: dict = Depends(require_a
|
|||||||
try:
|
try:
|
||||||
send_verification_email(row['email'], row['username'], verification_url)
|
send_verification_email(row['email'], row['username'], verification_url)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
raise HTTPException(status_code=503, detail=f'User created but verification email could not be sent: {error}') from error
|
logger.error('User verification email failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'User created but verification email could not be sent.')) from error
|
||||||
record_audit_event(current_user['id'], 'user_created', 'user', row['id'], details={'is_admin': bool(payload.is_admin)})
|
record_audit_event(current_user['id'], 'user_created', 'user', row['id'], details={'is_admin': bool(payload.is_admin)})
|
||||||
return public_user(row)
|
return public_user(row)
|
||||||
|
|
||||||
@@ -188,7 +196,7 @@ def update_admin_smtp_settings(payload: AdminSmtpUpdate, current_user: dict = De
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/smtp/test')
|
@router.post('/smtp/test')
|
||||||
def validate_admin_smtp(payload: AdminSmtpUpdate, current_user: dict = Depends(require_admin)):
|
def validate_admin_smtp(payload: AdminSmtpUpdate, request: Request, current_user: dict = Depends(require_admin)):
|
||||||
values = validate_smtp_values(payload, get_smtp_settings())
|
values = validate_smtp_values(payload, get_smtp_settings())
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
@@ -209,7 +217,8 @@ def validate_admin_smtp(payload: AdminSmtpUpdate, current_user: dict = Depends(r
|
|||||||
try:
|
try:
|
||||||
send_test_email(current_user['email'], values)
|
send_test_email(current_user['email'], values)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
raise HTTPException(status_code=503, detail=f'SMTP validation failed: {error}') from error
|
logger.error('SMTP validation failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'SMTP validation failed.')) from error
|
||||||
sends = int(rate.get('sends', 0)) + 1
|
sends = int(rate.get('sends', 0)) + 1
|
||||||
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
|
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
|
||||||
if sends >= 5:
|
if sends >= 5:
|
||||||
@@ -299,6 +308,18 @@ def admin_delete_label(label_id: str, current_user: dict = Depends(require_admin
|
|||||||
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:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from backend.app.api.dependencies import get_current_user
|
from backend.app.api.dependencies import get_current_user
|
||||||
@@ -119,10 +119,12 @@ def reset_password_endpoint(payload: PasswordResetRequest):
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/logout')
|
@router.post('/logout')
|
||||||
def logout(payload: dict):
|
def logout(authorization: str | None = Header(default=None)):
|
||||||
token = payload.get('token')
|
if not authorization or not authorization.startswith('Bearer '):
|
||||||
|
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||||
|
token = authorization.replace('Bearer ', '', 1).strip()
|
||||||
if not token:
|
if not token:
|
||||||
raise HTTPException(status_code=400, detail='Token is required')
|
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||||
revoked = revoke_token(token)
|
revoked = revoke_token(token)
|
||||||
if not revoked:
|
if not revoked:
|
||||||
raise HTTPException(status_code=404, detail='Token not found or already revoked')
|
raise HTTPException(status_code=404, detail='Token not found or already revoked')
|
||||||
|
|||||||
@@ -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')
|
||||||
|
|||||||
@@ -2,15 +2,16 @@
|
|||||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from fastapi import APIRouter, Header, HTTPException, Response, status
|
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, delete_link, 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.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.database import get_connection
|
||||||
from backend.app.services.plugin_manager import plugin_manager
|
from backend.app.services.plugin_manager import plugin_manager
|
||||||
from backend.app.services.token_service import validate_token
|
from backend.app.services.token_service import validate_token
|
||||||
from backend.app.services.audit_service import record_audit_event
|
from backend.app.services.audit_service import record_audit_event
|
||||||
|
from backend.app.services.scraper_service import scrape_title
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -22,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):
|
||||||
@@ -36,6 +38,21 @@ def available_tags():
|
|||||||
return list_tags()
|
return list_tags()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/scrape')
|
||||||
|
def scrape_url(url: str, authorization: str | None = Header(default=None)):
|
||||||
|
if not authorization or not authorization.startswith('Bearer '):
|
||||||
|
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||||
|
info = validate_token(authorization.replace('Bearer ', '', 1))
|
||||||
|
if info is None:
|
||||||
|
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
||||||
|
try:
|
||||||
|
title = scrape_title(url)
|
||||||
|
return {'title': title}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error('Scrape error for %s: %s', url, e)
|
||||||
|
raise HTTPException(status_code=502, detail='Could not scrape URL') from e
|
||||||
|
|
||||||
|
|
||||||
@router.get('/links/check')
|
@router.get('/links/check')
|
||||||
def check_existing_link(
|
def check_existing_link(
|
||||||
title: str,
|
title: str,
|
||||||
@@ -48,7 +65,12 @@ def check_existing_link(
|
|||||||
if info is None:
|
if info is None:
|
||||||
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
||||||
record = find_owned_link_by_title_url(info['user_id'], title, url)
|
record = find_owned_link_by_title_url(info['user_id'], title, url)
|
||||||
return {'exists': record is not None}
|
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)
|
||||||
@@ -71,7 +93,11 @@ def create_link_endpoint(payload: LinkCreate, response: Response, authorization:
|
|||||||
raise HTTPException(status_code=422, detail=str(error)) from error
|
raise HTTPException(status_code=422, detail=str(error)) from error
|
||||||
if duplicate:
|
if duplicate:
|
||||||
response.status_code = status.HTTP_200_OK
|
response.status_code = status.HTTP_200_OK
|
||||||
plugin_results = plugin_manager.dispatch({'type': 'link_created', **record})
|
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)
|
mastodon_result = next((result for result in plugin_results if result.get('plugin') == 'mastodon'), None)
|
||||||
if mastodon_result and mastodon_result.get('status') == 'posted':
|
if mastodon_result and mastodon_result.get('status') == 'posted':
|
||||||
mark_mastodon_posted(record['id'], info['user_id'], mastodon_result.get('post_id'))
|
mark_mastodon_posted(record['id'], info['user_id'], mastodon_result.get('post_id'))
|
||||||
@@ -161,4 +187,4 @@ def post_link_to_mastodon(
|
|||||||
|
|
||||||
@router.get('/links')
|
@router.get('/links')
|
||||||
def list_links():
|
def list_links():
|
||||||
return list_public_links()
|
return list_public_links()['items']
|
||||||
|
|||||||
@@ -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')
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
## 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
|
from backend.app.services.theme_service import THEMES, get_enabled_themes
|
||||||
@@ -23,10 +26,24 @@ def public_themes():
|
|||||||
return [{'id': theme, **THEMES[theme]} for theme in enabled]
|
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
|
||||||
@@ -34,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'],
|
||||||
@@ -52,5 +71,14 @@ def public_feed(
|
|||||||
'created_at': item['created_at'],
|
'created_at': item['created_at'],
|
||||||
'mastodon_posted': bool(item['mastodon_posted']),
|
'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,
|
||||||
|
}
|
||||||
|
|||||||
@@ -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()}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from io import BytesIO
|
|||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
|
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
|
||||||
from PIL import Image, UnidentifiedImageError
|
from PIL import Image, UnidentifiedImageError
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
@@ -20,8 +20,11 @@ from backend.app.services.email_service import send_verification_email, smtp_con
|
|||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings
|
||||||
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
|
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
|
||||||
from backend.app.services.audit_service import record_audit_event
|
from backend.app.services.audit_service import record_audit_event
|
||||||
|
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||||
|
import logging
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
MAX_AVATAR_BYTES = 2 * 1024 * 1024
|
MAX_AVATAR_BYTES = 2 * 1024 * 1024
|
||||||
MAX_AVATAR_PIXELS = 25_000_000
|
MAX_AVATAR_PIXELS = 25_000_000
|
||||||
@@ -186,7 +189,7 @@ def get_additional_emails(user: dict = Depends(get_current_user)):
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/emails', status_code=201)
|
@router.post('/emails', status_code=201)
|
||||||
def add_additional_email(payload: AdditionalEmail, user: dict = Depends(get_current_user)):
|
def add_additional_email(payload: AdditionalEmail, request: Request, user: dict = Depends(get_current_user)):
|
||||||
email = payload.email.strip().lower()
|
email = payload.email.strip().lower()
|
||||||
if email == user['email'].lower():
|
if email == user['email'].lower():
|
||||||
raise HTTPException(status_code=409, detail='This is already the primary email address')
|
raise HTTPException(status_code=409, detail='This is already the primary email address')
|
||||||
@@ -209,7 +212,8 @@ def add_additional_email(payload: AdditionalEmail, user: dict = Depends(get_curr
|
|||||||
try:
|
try:
|
||||||
send_verification_email(email_address, user['username'], verification_url)
|
send_verification_email(email_address, user['username'], verification_url)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
raise HTTPException(status_code=503, detail=f'Email address added but verification email could not be sent: {error}') from error
|
logger.error('Additional email verification failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'Email address added but verification email could not be sent.')) from error
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||||
@@ -221,7 +225,7 @@ def add_additional_email(payload: AdditionalEmail, user: dict = Depends(get_curr
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/emails/{address_id}/resend')
|
@router.post('/emails/{address_id}/resend')
|
||||||
def resend_additional_email(address_id: str, user: dict = Depends(get_current_user)):
|
def resend_additional_email(address_id: str, request: Request, user: dict = Depends(get_current_user)):
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
setting_name = f'email_verify_rate:{address_id}'
|
setting_name = f'email_verify_rate:{address_id}'
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
@@ -245,7 +249,8 @@ def resend_additional_email(address_id: str, user: dict = Depends(get_current_us
|
|||||||
try:
|
try:
|
||||||
send_verification_email(email, user['username'], verification_url)
|
send_verification_email(email, user['username'], verification_url)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
raise HTTPException(status_code=503, detail=f'Verification email could not be sent: {error}') from error
|
logger.error('Verification email resend failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'Verification email could not be sent.')) from error
|
||||||
sends = int(rate.get('sends', 0)) + 1
|
sends = int(rate.get('sends', 0)) + 1
|
||||||
updated = {'sends': sends, 'last_sent': now.isoformat()}
|
updated = {'sends': sends, 'last_sent': now.isoformat()}
|
||||||
if sends >= 5:
|
if sends >= 5:
|
||||||
@@ -385,6 +390,8 @@ 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'):
|
if config.get('access_token'):
|
||||||
config.pop('access_token')
|
config.pop('access_token')
|
||||||
return config
|
return config
|
||||||
|
|||||||
@@ -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,10 +22,19 @@ 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')
|
||||||
data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
|
data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
|
||||||
@@ -38,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:
|
||||||
@@ -56,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
|
||||||
|
|||||||
@@ -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)}'
|
||||||
+24
-7
@@ -1,8 +1,9 @@
|
|||||||
## Copyright © 2026 Olaf Kolkman
|
## Copyright © 2026 Olaf Kolkman
|
||||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, Request
|
||||||
import logging
|
import logging
|
||||||
|
from uuid import uuid4
|
||||||
from fastapi.responses import HTMLResponse
|
from fastapi.responses import HTMLResponse
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
@@ -17,13 +18,23 @@ from backend.app.api.public import router as public_router
|
|||||||
from backend.app.api.setup import router as setup_router
|
from backend.app.api.setup import router as setup_router
|
||||||
from backend.app.api.setup import has_administrator
|
from backend.app.api.setup import has_administrator
|
||||||
from backend.app.api.user_config import router as user_config_router
|
from backend.app.api.user_config import router as user_config_router
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings, validate_configuration
|
||||||
from backend.app.database import AVATARS_DIR
|
from backend.app.database import AVATARS_DIR
|
||||||
from backend.app.services.link_service import get_public_profile, list_public_links
|
from backend.app.services.link_service import get_public_profile
|
||||||
|
|
||||||
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,10 +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 = get_public_profile(username)
|
||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request,
|
request,
|
||||||
'feed.html',
|
'feed.html',
|
||||||
{'feed': feed, 'profile': profile, 'user_filter': username},
|
{'profile': profile, 'user_filter': username},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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'}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
import json
|
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
|
||||||
@@ -27,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(
|
||||||
@@ -36,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(
|
||||||
@@ -103,7 +105,7 @@ 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
|
||||||
@@ -123,23 +125,106 @@ def find_owned_link_by_title_url(user_id: str, title: str, url: str) -> dict | N
|
|||||||
return record
|
return record
|
||||||
|
|
||||||
|
|
||||||
def list_public_links(username: str | None = None):
|
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:
|
def get_public_profile(username: str) -> dict | None:
|
||||||
@@ -173,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)
|
||||||
@@ -242,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]
|
||||||
@@ -268,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')
|
||||||
@@ -276,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 != ?',
|
||||||
@@ -286,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):
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
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
|
from urllib.request import Request
|
||||||
@@ -16,24 +17,39 @@ 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:
|
||||||
@@ -68,11 +84,25 @@ class MastodonPlugin(BasePlugin):
|
|||||||
post_prefix = f'#{str(config["hashtag"]).strip().lstrip("#")} '
|
post_prefix = f'#{str(config["hashtag"]).strip().lstrip("#")} '
|
||||||
post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX).strip()
|
post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX).strip()
|
||||||
title = str(event.get('title') or '').strip()
|
title = str(event.get('title') or '').strip()
|
||||||
status_parts = [f'{post_prefix} {title}'.strip()]
|
status_parts = [post_prefix.strip()]
|
||||||
|
if title:
|
||||||
|
status_parts.append(title)
|
||||||
if event.get('comment'):
|
if event.get('comment'):
|
||||||
status_parts.append(event['comment'])
|
status_parts.append(event['comment'])
|
||||||
if title:
|
if title:
|
||||||
status_parts.append(f'from: {event.get("url", "")}')
|
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_parts.append(' '.join(event['tags']))
|
status_parts.append(' '.join(event['tags']))
|
||||||
post_body = '\n\n'.join(status_parts)
|
post_body = '\n\n'.join(status_parts)
|
||||||
@@ -127,6 +157,7 @@ class MastodonPlugin(BasePlugin):
|
|||||||
}
|
}
|
||||||
|
|
||||||
def delete_posts(self, event):
|
def delete_posts(self, event):
|
||||||
|
"""Delete all Mastodon statuses recorded for a link event."""
|
||||||
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:
|
||||||
@@ -170,10 +201,14 @@ class MastodonPlugin(BasePlugin):
|
|||||||
|
|
||||||
|
|
||||||
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:
|
||||||
@@ -187,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:
|
||||||
@@ -197,6 +233,7 @@ class PluginManager:
|
|||||||
return results
|
return results
|
||||||
|
|
||||||
def post_to_mastodon(self, event):
|
def post_to_mastodon(self, event):
|
||||||
|
"""Publish one event through Mastodon when that plugin is enabled."""
|
||||||
self.refresh_from_db()
|
self.refresh_from_db()
|
||||||
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
|
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
|
||||||
if not plugin.enabled:
|
if not plugin.enabled:
|
||||||
@@ -204,6 +241,7 @@ class PluginManager:
|
|||||||
return plugin.handle_event(event)
|
return plugin.handle_event(event)
|
||||||
|
|
||||||
def delete_mastodon_posts(self, event):
|
def delete_mastodon_posts(self, event):
|
||||||
|
"""Delete the Mastodon statuses associated with an event."""
|
||||||
self.refresh_from_db()
|
self.refresh_from_db()
|
||||||
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
|
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
|
||||||
return plugin.delete_posts(event)
|
return plugin.delete_posts(event)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -16,6 +16,7 @@ THEMES = {
|
|||||||
'dracula': {'label': 'Dracula', 'description': 'A vivid dark theme with high-contrast accents.'},
|
'dracula': {'label': 'Dracula', 'description': 'A vivid dark theme with high-contrast accents.'},
|
||||||
'nord': {'label': 'Nord', 'description': 'A cool, muted blue-gray theme.'},
|
'nord': {'label': 'Nord', 'description': 'A cool, muted blue-gray theme.'},
|
||||||
'solarized': {'label': 'Solarized', 'description': 'A balanced theme available in a light style.'},
|
'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)
|
DEFAULT_ENABLED_THEMES = tuple(THEMES)
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ 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='
|
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)
|
||||||
|
|||||||
+176
-27
@@ -2,6 +2,7 @@
|
|||||||
## 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
|
||||||
@@ -11,7 +12,8 @@ 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.email_service import get_smtp_settings
|
||||||
from backend.app.services.login_throttle import clear_login_failures
|
from backend.app.services.login_throttle import clear_login_failures
|
||||||
from backend.app.services.otp_service import current_code
|
from backend.app.services.otp_service import current_code
|
||||||
@@ -31,7 +33,7 @@ def login_headers(username='alice'):
|
|||||||
|
|
||||||
|
|
||||||
def test_login_returns_token():
|
def test_login_returns_token():
|
||||||
assert app.version == '0.1.0'
|
assert app.version == settings.version
|
||||||
response = client.post('/api/auth/login', json={
|
response = client.post('/api/auth/login', json={
|
||||||
'email': 'alice@example.com',
|
'email': 'alice@example.com',
|
||||||
'password': 'secret123',
|
'password': 'secret123',
|
||||||
@@ -55,6 +57,17 @@ def test_login_returns_token():
|
|||||||
assert client.get('/api/auth/me', params={'token': payload['access_token']}).status_code == 401
|
assert client.get('/api/auth/me', params={'token': payload['access_token']}).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout_requires_bearer_header_and_revokes_token_family():
|
||||||
|
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
|
||||||
|
token = login['access_token']
|
||||||
|
headers = {'Authorization': f'Bearer {token}'}
|
||||||
|
assert client.post('/api/auth/logout', json={'token': token}).status_code == 401
|
||||||
|
assert client.get('/api/auth/me', headers=headers).status_code == 200
|
||||||
|
assert client.post('/api/auth/logout', headers=headers).status_code == 200
|
||||||
|
assert client.get('/api/auth/me', headers=headers).status_code == 401
|
||||||
|
assert client.post('/api/auth/refresh', json={'refresh_token': login['refresh_token'], 'device_id': login['device_id']}).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
def test_login_rate_limit_locks_out_after_five_failures_and_resets_on_success():
|
def test_login_rate_limit_locks_out_after_five_failures_and_resets_on_success():
|
||||||
email = f'unknown-{uuid4().hex}@example.com'
|
email = f'unknown-{uuid4().hex}@example.com'
|
||||||
for attempt in range(5):
|
for attempt in range(5):
|
||||||
@@ -139,10 +152,10 @@ def test_configuration_requires_authentication_and_admin_role():
|
|||||||
def test_admin_can_select_multiple_themes():
|
def test_admin_can_select_multiple_themes():
|
||||||
headers = login_headers()
|
headers = login_headers()
|
||||||
response = client.put('/api/admin/themes', headers=headers, json={
|
response = client.put('/api/admin/themes', headers=headers, json={
|
||||||
'themes': ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized'],
|
'themes': ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized', 'red'],
|
||||||
})
|
})
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json()['enabled'] == ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized']
|
assert response.json()['enabled'] == ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized', 'red']
|
||||||
public_response = client.get('/api/public/themes')
|
public_response = client.get('/api/public/themes')
|
||||||
assert public_response.status_code == 200
|
assert public_response.status_code == 200
|
||||||
assert [theme['id'] for theme in public_response.json()] == response.json()['enabled']
|
assert [theme['id'] for theme in public_response.json()] == response.json()['enabled']
|
||||||
@@ -216,7 +229,31 @@ def test_admin_reports_smtp_validation_errors():
|
|||||||
'smtp_use_tls': False,
|
'smtp_use_tls': False,
|
||||||
})
|
})
|
||||||
assert failed_validation.status_code == 503
|
assert failed_validation.status_code == 503
|
||||||
assert 'connection refused' in failed_validation.json()['detail']
|
assert failed_validation.json()['detail'].startswith('SMTP validation failed. Reference: ')
|
||||||
|
assert 'connection refused' not in failed_validation.json()['detail']
|
||||||
|
assert failed_validation.headers['X-Request-ID']
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_id_is_preserved_and_sensitive_error_text_is_not_returned():
|
||||||
|
headers = login_headers()
|
||||||
|
with get_connection() as conn:
|
||||||
|
conn.execute('DELETE FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',))
|
||||||
|
conn.commit()
|
||||||
|
with patch('backend.app.api.admin.send_test_email', side_effect=RuntimeError('password=super-secret token=abc123')):
|
||||||
|
response = client.post(
|
||||||
|
'/api/admin/smtp/test',
|
||||||
|
headers={**headers, 'X-Request-ID': 'audit-test-123'},
|
||||||
|
json={
|
||||||
|
'smtp_host': 'smtp.example.com',
|
||||||
|
'smtp_port': 2525,
|
||||||
|
'smtp_from': 'admin@example.com',
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert response.status_code == 503
|
||||||
|
assert response.headers['X-Request-ID'] == 'audit-test-123'
|
||||||
|
assert response.json()['detail'] == 'SMTP validation failed. Reference: audit-test-123'
|
||||||
|
assert 'super-secret' not in response.text
|
||||||
|
assert 'abc123' not in response.text
|
||||||
|
|
||||||
|
|
||||||
def test_admin_can_add_list_and_remove_users():
|
def test_admin_can_add_list_and_remove_users():
|
||||||
@@ -455,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
|
||||||
@@ -493,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'
|
||||||
@@ -501,8 +615,8 @@ 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()
|
||||||
@@ -531,7 +645,7 @@ def test_duplicate_link_updates_comment_tags_and_retriggers_plugins():
|
|||||||
dispatch.assert_called_once()
|
dispatch.assert_called_once()
|
||||||
assert dispatch.call_args.args[0]['comment'] == 'updated comment'
|
assert dispatch.call_args.args[0]['comment'] == 'updated comment'
|
||||||
assert dispatch.call_args.args[0]['tags'] == ['#Second']
|
assert dispatch.call_args.args[0]['tags'] == ['#Second']
|
||||||
feed_item = next(item for item in client.get('/api/public/feed').json() if item['id'] == first.json()['id'])
|
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['comment'] == 'updated comment'
|
||||||
assert feed_item['tags'] == ['#Second']
|
assert feed_item['tags'] == ['#Second']
|
||||||
|
|
||||||
@@ -575,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'}
|
||||||
|
|
||||||
@@ -611,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
|
||||||
@@ -643,8 +757,7 @@ def test_only_link_owner_can_edit_link():
|
|||||||
|
|
||||||
def test_logout_revokes_token_and_admin_can_list_plugins():
|
def test_logout_revokes_token_and_admin_can_list_plugins():
|
||||||
headers = login_headers()
|
headers = login_headers()
|
||||||
token = headers['Authorization'].removeprefix('Bearer ')
|
assert client.post('/api/auth/logout', headers=headers).status_code == 200
|
||||||
assert client.post('/api/auth/logout', json={'token': token}).status_code == 200
|
|
||||||
|
|
||||||
revoked_response = client.post('/api/links', headers=headers, json={
|
revoked_response = client.post('/api/links', headers=headers, json={
|
||||||
'title': 'Should fail',
|
'title': 'Should fail',
|
||||||
@@ -673,6 +786,7 @@ 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 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
|
||||||
@@ -681,6 +795,7 @@ 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
|
||||||
@@ -693,6 +808,10 @@ def test_public_and_admin_pages_render_html():
|
|||||||
about_page = client.get('/about')
|
about_page = client.get('/about')
|
||||||
assert about_page.status_code == 200
|
assert about_page.status_code == 200
|
||||||
assert 'Save the good stuff' in about_page.text
|
assert 'Save the good stuff' in about_page.text
|
||||||
|
assert '<h2>Plugin</h2>' in about_page.text
|
||||||
|
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
|
||||||
@@ -702,12 +821,25 @@ 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 'function loadFeed()' in feed_script
|
||||||
|
assert 'function renderPagination(page, totalPages)' in feed_script
|
||||||
assert 'if (item.is_owner && !showIdentity)' in feed_script
|
assert 'if (item.is_owner && !showIdentity)' in feed_script
|
||||||
assert 'deleteEntry(item, deleteButton)' in feed_script
|
assert 'deleteEntry(item, deleteButton)' in feed_script
|
||||||
assert 'postToMastodon(item, mastodonButton)' in feed_script
|
assert 'postToMastodon(item, mastodonButton)' in feed_script
|
||||||
assert 'tag.toLowerCase() === pref.tag.toLowerCase()' 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 "entryMeta.className = 'entry-meta'" in feed_script
|
||||||
assert "meta.className = 'meta'" in feed_script
|
assert "meta.className = 'meta'" in feed_script
|
||||||
@@ -716,6 +848,9 @@ def test_public_and_admin_pages_render_html():
|
|||||||
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():
|
||||||
@@ -753,6 +888,7 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
|
|||||||
'title': 'A useful page',
|
'title': 'A useful page',
|
||||||
'url': 'https://example.com/useful',
|
'url': 'https://example.com/useful',
|
||||||
'comment': 'Worth sharing',
|
'comment': 'Worth sharing',
|
||||||
|
'timestamp': '2026-08-29T21:10:00Z',
|
||||||
'tags': ['#python', '#web'],
|
'tags': ['#python', '#web'],
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -760,8 +896,8 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
|
|||||||
assert received['path'] == '/api/v1/statuses'
|
assert received['path'] == '/api/v1/statuses'
|
||||||
assert received['authorization'] == 'Bearer test-token'
|
assert received['authorization'] == 'Bearer test-token'
|
||||||
assert received['content_type'] == 'application/x-www-form-urlencoded'
|
assert received['content_type'] == 'application/x-www-form-urlencoded'
|
||||||
assert received['body'] == {'status': ['From my #LinkLog: A useful page\n\nWorth sharing\n\nfrom: https://example.com/useful\n\n#python #web']}
|
assert received['body'] == {'status': ['From my #LinkLog:\n\nA useful page\n\nWorth sharing\n\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() if item['id'] == response.json()['id'])
|
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
|
assert posted_item['mastodon_posted'] is True
|
||||||
finally:
|
finally:
|
||||||
server.shutdown()
|
server.shutdown()
|
||||||
@@ -769,6 +905,18 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
|
|||||||
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():
|
def test_mastodon_post_without_title_omits_source_line():
|
||||||
from backend.app.services.plugin_manager import MastodonPlugin
|
from backend.app.services.plugin_manager import MastodonPlugin
|
||||||
|
|
||||||
@@ -802,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,
|
||||||
|
|||||||
@@ -1,10 +1,36 @@
|
|||||||
import re
|
import re
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from backend.app.core.config import Settings, validate_configuration
|
||||||
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
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():
|
def test_production_compose_configuration_matches_settings_environment_keys():
|
||||||
compose = (ROOT / 'docker-compose.yml').read_text()
|
compose = (ROOT / 'docker-compose.yml').read_text()
|
||||||
settings = (ROOT / 'backend' / 'app' / 'core' / 'config.py').read_text()
|
settings = (ROOT / 'backend' / 'app' / 'core' / 'config.py').read_text()
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ def test_user_config_api_and_profile_page():
|
|||||||
assert 'id="auth-avatar"' not in page_response.text
|
assert 'id="auth-avatar"' not in page_response.text
|
||||||
assert 'name="new_password_confirmation"' in page_response.text
|
assert 'name="new_password_confirmation"' in page_response.text
|
||||||
assert 'id="additional-email-form"' in page_response.text
|
assert 'id="additional-email-form"' in page_response.text
|
||||||
|
assert 'If you have not downloaded the plugin yet' in page_response.text
|
||||||
|
assert 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi' in page_response.text
|
||||||
|
|
||||||
bob_login = client.post('/api/auth/login', json={
|
bob_login = client.post('/api/auth/login', json={
|
||||||
'email': 'bob@example.com',
|
'email': 'bob@example.com',
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
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}
|
||||||
volumes:
|
volumes:
|
||||||
- ./linklog_data:/app/backend/data
|
- ./linklog_data:/app/backend/data
|
||||||
|
|||||||
+10
-10
@@ -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:-linklog.example.com}`)
|
traefik.http.routers.testlog.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
|
||||||
traefik.http.routers.linklog.middlewares: web-https-redirect,servicests
|
traefik.http.routers.testlog.middlewares: web-https-redirect,servicests
|
||||||
traefik.http.routers.linklog-secure.entrypoints: websecure
|
traefik.http.routers.testlog-secure.entrypoints: websecure
|
||||||
traefik.http.routers.linklog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
|
traefik.http.routers.testlog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
|
||||||
traefik.http.routers.linklog-secure.tls: true
|
traefik.http.routers.testlog-secure.tls: true
|
||||||
traefik.http.routers.linklog-secure.middlewares: servicests
|
traefik.http.routers.testlog-secure.middlewares: servicests
|
||||||
|
|
||||||
|
|
||||||
traefik.http.routers.linklog-secure.tls.certresolver: myresolver
|
traefik.http.routers.testlog-secure.tls.certresolver: myresolver
|
||||||
traefik.http.routers.linklog-secure.service: linklog
|
traefik.http.routers.testlog-secure.service: testlog
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+116
-7
@@ -12,7 +12,7 @@ const smtpForm = document.querySelector('#smtp-form');
|
|||||||
const smtpTestButton = document.querySelector('#smtp-test-button');
|
const smtpTestButton = document.querySelector('#smtp-test-button');
|
||||||
const smtpStatus = document.querySelector('#smtp-status');
|
const smtpStatus = document.querySelector('#smtp-status');
|
||||||
const themesForm = document.querySelector('#themes-form');
|
const themesForm = document.querySelector('#themes-form');
|
||||||
const themeOptions = document.querySelector('#theme-options');
|
const themeOptions = document.querySelector('#admin-theme-options');
|
||||||
const themeStatus = document.querySelector('#theme-status');
|
const themeStatus = document.querySelector('#theme-status');
|
||||||
let smtpNextAllowedAt = null;
|
let smtpNextAllowedAt = null;
|
||||||
let smtpTimerHandle = null;
|
let smtpTimerHandle = null;
|
||||||
@@ -57,21 +57,85 @@ 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');
|
||||||
@@ -195,9 +259,51 @@ async function loadUsers() {
|
|||||||
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() {
|
||||||
@@ -382,4 +488,7 @@ loadAdminState().catch((error) => {
|
|||||||
smtpForm.reset();
|
smtpForm.reset();
|
||||||
themesForm.reset();
|
themesForm.reset();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', initPanelToggles);
|
||||||
|
initPanelToggles();
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
(() => {
|
(() => {
|
||||||
const loginButton = document.querySelector('#auth-login-button');
|
const loginButton = document.querySelector('#auth-login-button');
|
||||||
|
const newEntryButton = document.querySelector('#new-entry-button');
|
||||||
const profileLink = document.querySelector('#auth-profile-link');
|
const profileLink = document.querySelector('#auth-profile-link');
|
||||||
const labelsLink = document.querySelector('#auth-labels-link');
|
const labelsLink = document.querySelector('#auth-labels-link');
|
||||||
const adminLink = document.querySelector('#auth-admin-link');
|
const adminLink = document.querySelector('#auth-admin-link');
|
||||||
@@ -14,6 +15,10 @@
|
|||||||
const menuToggle = document.querySelector('.menu-toggle');
|
const menuToggle = document.querySelector('.menu-toggle');
|
||||||
const logoutButton = document.querySelector('#logout-button');
|
const logoutButton = document.querySelector('#logout-button');
|
||||||
|
|
||||||
|
const themeSubmenuContainer = document.querySelector('#theme-submenu-container');
|
||||||
|
const themeSubmenuTitle = document.querySelector('.submenu-title');
|
||||||
|
const themeOptions = document.querySelector('#theme-options');
|
||||||
|
|
||||||
if (!loginButton || !profileLink || !labelsLink || !adminLink || !session || !username || !menu || !menuToggle || !logoutButton) return;
|
if (!loginButton || !profileLink || !labelsLink || !adminLink || !session || !username || !menu || !menuToggle || !logoutButton) return;
|
||||||
|
|
||||||
menuToggle.addEventListener('click', () => {
|
menuToggle.addEventListener('click', () => {
|
||||||
@@ -22,8 +27,19 @@
|
|||||||
menuToggle.setAttribute('aria-expanded', String(!isOpen));
|
menuToggle.setAttribute('aria-expanded', String(!isOpen));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Handle theme submenu toggle
|
||||||
|
if (themeSubmenuTitle && themeOptions) {
|
||||||
|
themeSubmenuTitle.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const isOpen = !themeOptions.classList.contains('hidden');
|
||||||
|
themeOptions.classList.toggle('hidden', isOpen);
|
||||||
|
themeSubmenuTitle.setAttribute('aria-expanded', String(!isOpen));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function showSignedOut() {
|
function showSignedOut() {
|
||||||
loginButton.classList.remove('hidden');
|
loginButton.classList.remove('hidden');
|
||||||
|
if (newEntryButton) newEntryButton.classList.add('hidden');
|
||||||
profileLink.classList.add('hidden');
|
profileLink.classList.add('hidden');
|
||||||
labelsLink.classList.add('hidden');
|
labelsLink.classList.add('hidden');
|
||||||
adminLink.classList.add('hidden');
|
adminLink.classList.add('hidden');
|
||||||
@@ -33,6 +49,7 @@
|
|||||||
|
|
||||||
function showSignedIn(user) {
|
function showSignedIn(user) {
|
||||||
loginButton.classList.add('hidden');
|
loginButton.classList.add('hidden');
|
||||||
|
if (newEntryButton) newEntryButton.classList.remove('hidden');
|
||||||
profileLink.classList.remove('hidden');
|
profileLink.classList.remove('hidden');
|
||||||
labelsLink.classList.remove('hidden');
|
labelsLink.classList.remove('hidden');
|
||||||
adminLink.classList.toggle('hidden', !user.is_admin);
|
adminLink.classList.toggle('hidden', !user.is_admin);
|
||||||
|
|||||||
+95
-20
@@ -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;
|
||||||
@@ -170,6 +188,43 @@ function renderFeed(items, showIdentity = true) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
async function postToMastodon(item, button) {
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
const response = await fetch(`/api/links/${encodeURIComponent(item.id)}/mastodon`, {
|
const response = await fetch(`/api/links/${encodeURIComponent(item.id)}/mastodon`, {
|
||||||
@@ -256,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() {
|
||||||
@@ -287,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();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -304,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());
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
@@ -310,6 +310,48 @@ passwordForm.addEventListener('submit', async (event) => {
|
|||||||
if (response.ok) passwordForm.reset();
|
if (response.ok) passwordForm.reset();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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) => {
|
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);
|
||||||
});
|
});
|
||||||
|
|||||||
+504
-13
@@ -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;
|
||||||
@@ -95,6 +95,15 @@
|
|||||||
--border: rgba(7, 54, 66, 0.18); --shadow: 0 18px 50px rgba(7, 54, 66, 0.14);
|
--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 {
|
||||||
@@ -145,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,
|
||||||
@@ -169,7 +180,7 @@ body::selection {
|
|||||||
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;
|
||||||
}
|
}
|
||||||
@@ -210,11 +221,21 @@ body::selection {
|
|||||||
font-size: 0.68rem;
|
font-size: 0.68rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.header-tools .toolbar .search-control {
|
||||||
|
flex-basis: 180px;
|
||||||
|
}
|
||||||
|
|
||||||
.header-tools .toolbar select {
|
.header-tools .toolbar select {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
padding: 6px 8px;
|
padding: 6px 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.header-tools .toolbar input {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 6px 8px;
|
||||||
|
}
|
||||||
|
|
||||||
.header-actions {
|
.header-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex: 0 0 auto;
|
flex: 0 0 auto;
|
||||||
@@ -223,17 +244,6 @@ body::selection {
|
|||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
.theme-picker {
|
|
||||||
width: auto;
|
|
||||||
min-width: 132px;
|
|
||||||
padding: 8px 10px;
|
|
||||||
border: 1px solid var(--surface-2);
|
|
||||||
border-radius: 7px;
|
|
||||||
background: var(--surface-0);
|
|
||||||
color: var(--text);
|
|
||||||
font: inherit;
|
|
||||||
}
|
|
||||||
|
|
||||||
.menu-toggle {
|
.menu-toggle {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
padding: 10px 13px;
|
padding: 10px 13px;
|
||||||
@@ -248,6 +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;
|
||||||
@@ -314,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;
|
||||||
@@ -357,6 +472,108 @@ main.container {
|
|||||||
margin-bottom: 0;
|
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;
|
||||||
@@ -669,6 +886,53 @@ 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: 11px;
|
padding: 11px;
|
||||||
background: var(--surface-0);
|
background: var(--surface-0);
|
||||||
@@ -768,6 +1032,228 @@ button:disabled {
|
|||||||
margin-top: 14px;
|
margin-top: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Entry form styling */
|
||||||
|
.entry-form {
|
||||||
|
max-width: 600px;
|
||||||
|
margin: 0 auto;
|
||||||
|
display: grid;
|
||||||
|
gap: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.entry-form.hidden,
|
||||||
|
#auth-required.hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
#auth-required {
|
||||||
|
max-width: 600px;
|
||||||
|
margin: 40px auto;
|
||||||
|
padding: 16px;
|
||||||
|
background: var(--surface-0);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 12px;
|
||||||
|
border-left: 4px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
#auth-required p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
#auth-required a {
|
||||||
|
color: var(--lavender);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
#auth-required a:hover {
|
||||||
|
color: var(--mauve);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section {
|
||||||
|
display: grid;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section.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;
|
||||||
@@ -815,6 +1301,11 @@ button:disabled {
|
|||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.new-entry-button {
|
||||||
|
padding: 8px 11px;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
.logout-button {
|
.logout-button {
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
}
|
}
|
||||||
|
|||||||
+32
-11
@@ -11,18 +11,39 @@ async function loadAvailableThemes() {
|
|||||||
? localStorage.getItem(themePreference)
|
? localStorage.getItem(themePreference)
|
||||||
: themes[0]?.id;
|
: themes[0]?.id;
|
||||||
if (selected) document.documentElement.dataset.theme = selected;
|
if (selected) document.documentElement.dataset.theme = selected;
|
||||||
const headerActions = document.querySelector('.header-actions');
|
|
||||||
if (!headerActions || !themes.length) return;
|
const submenuContainer = document.querySelector('#theme-submenu-container');
|
||||||
const picker = document.createElement('select');
|
const themeOptions = document.querySelector('#theme-options');
|
||||||
picker.className = 'theme-picker';
|
const submenuTitle = document.querySelector('.submenu-title');
|
||||||
picker.setAttribute('aria-label', 'Theme');
|
|
||||||
picker.replaceChildren(...themes.map((theme) => new Option(theme.label, theme.id)));
|
if (!submenuContainer || !themeOptions || !themes.length) return;
|
||||||
picker.value = selected || themes[0].id;
|
|
||||||
picker.addEventListener('change', () => {
|
// Show the submenu container
|
||||||
localStorage.setItem(themePreference, picker.value);
|
submenuContainer.classList.remove('hidden');
|
||||||
document.documentElement.dataset.theme = picker.value;
|
|
||||||
|
// Create theme buttons
|
||||||
|
const buttons = themes.map((theme) => {
|
||||||
|
const button = document.createElement('button');
|
||||||
|
button.type = 'button';
|
||||||
|
button.className = 'theme-option';
|
||||||
|
button.dataset.themeId = theme.id;
|
||||||
|
button.textContent = theme.label;
|
||||||
|
if (theme.id === selected) {
|
||||||
|
button.classList.add('active');
|
||||||
|
}
|
||||||
|
button.addEventListener('click', () => {
|
||||||
|
localStorage.setItem(themePreference, theme.id);
|
||||||
|
document.documentElement.dataset.theme = theme.id;
|
||||||
|
// Update active state
|
||||||
|
document.querySelectorAll('.theme-option').forEach((btn) => {
|
||||||
|
btn.classList.remove('active');
|
||||||
});
|
});
|
||||||
headerActions.prepend(picker);
|
button.classList.add('active');
|
||||||
|
});
|
||||||
|
return button;
|
||||||
|
});
|
||||||
|
|
||||||
|
themeOptions.replaceChildren(...buttons);
|
||||||
}
|
}
|
||||||
|
|
||||||
loadAvailableThemes();
|
loadAvailableThemes();
|
||||||
@@ -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,8 +57,14 @@
|
|||||||
<p>LinkLog is open source software. You can run your own instance, or contribute to the project on
|
<p>LinkLog is open source software. You can run your own instance, or contribute to the project on
|
||||||
<a href="https://git.kolkman.org/olaf/Link-Log">my repository</a>.</p>
|
<a href="https://git.kolkman.org/olaf/Link-Log">my repository</a>.</p>
|
||||||
</section>
|
</section>
|
||||||
|
<section class="link-item">
|
||||||
|
<h2>Plugin</h2>
|
||||||
|
<p>Install the Firefox plugin to save links directly from your browser. <a
|
||||||
|
href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.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>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
|
|||||||
@@ -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,16 +74,31 @@
|
|||||||
<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">
|
<section class="link-item settings-panel minimized">
|
||||||
<h2>SMTP settings</h2>
|
<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">
|
<form id="smtp-form">
|
||||||
<label>
|
<label>
|
||||||
SMTP host
|
SMTP host
|
||||||
@@ -104,21 +129,26 @@
|
|||||||
|
|
||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
<section class="link-item settings-panel">
|
<section class="link-item settings-panel minimized">
|
||||||
<h2>Available themes</h2>
|
<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>
|
<p>Choose the themes visitors may use.</p>
|
||||||
<form id="themes-form">
|
<form id="themes-form">
|
||||||
<div id="theme-options" class="theme-options" aria-live="polite">Loading themes...</div>
|
<div id="admin-theme-options" class="theme-options" aria-live="polite">Loading themes...</div>
|
||||||
<button type="submit">Save themes</button>
|
<button type="submit">Save themes</button>
|
||||||
<p id="theme-status" class="status" role="status"></p>
|
<p id="theme-status" class="status" role="status"></p>
|
||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=2"></script>
|
<script src="/static/logout.js?v=2"></script>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
<script src="/static/admin.js?v=5"></script>
|
<script src="/static/admin.js?v=7"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -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>
|
||||||
<p>Public link feed</p>
|
<p>Public link feed</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-tools">
|
<div class="header-tools">
|
||||||
<div class="header-actions">
|
<div class="header-actions">
|
||||||
|
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
|
||||||
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
|
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
|
||||||
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
|
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
|
||||||
<a id="auth-home-link" href="/">Home</a>
|
<a id="auth-home-link" href="/">Home</a>
|
||||||
@@ -30,9 +31,19 @@
|
|||||||
<a id="auth-username" class="user-name" href="/"></a>
|
<a id="auth-username" class="user-name" href="/"></a>
|
||||||
</div>
|
</div>
|
||||||
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
|
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
|
||||||
|
<div id="theme-submenu-container" class="theme-submenu-container hidden">
|
||||||
|
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
|
||||||
|
<div id="theme-options" class="submenu-options hidden"></div>
|
||||||
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
<section class="toolbar">
|
<section class="toolbar">
|
||||||
|
<label>
|
||||||
|
Tag filter
|
||||||
|
<select id="tag-filter">
|
||||||
|
<option value="">All tags</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
<label>
|
<label>
|
||||||
Sort
|
Sort
|
||||||
<select id="sort-select">
|
<select id="sort-select">
|
||||||
@@ -47,10 +58,12 @@
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
Tag filter
|
Per page
|
||||||
<select id="tag-filter">
|
<select id="page-size-select"></select>
|
||||||
<option value="">All tags</option>
|
</label>
|
||||||
</select>
|
<label class="search-control">
|
||||||
|
Search
|
||||||
|
<input id="search-input" type="search" placeholder="Search links" autocomplete="off" aria-label="Search links" />
|
||||||
</label>
|
</label>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
@@ -75,12 +88,13 @@
|
|||||||
</section>
|
</section>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<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/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
<script src="/static/feed.js?v=9"></script>
|
<script src="/static/feed.js?v=14"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -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,7 +49,7 @@
|
|||||||
<div id="label-list" class="plugin-list"></div>
|
<div id="label-list" class="plugin-list"></div>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=3"></script>
|
<script src="/static/logout.js?v=3"></script>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -55,7 +60,7 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=3"></script>
|
<script src="/static/logout.js?v=3"></script>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -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,7 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman</footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman</footer>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
<script src="/static/setup.js"></script>
|
<script src="/static/setup.js"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -15,10 +15,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>
|
||||||
<h1>Profile</h1>
|
<h1>Profile</h1>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-actions">
|
<div class="header-actions">
|
||||||
|
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
|
||||||
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
|
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
|
||||||
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
|
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
|
||||||
<a id="auth-home-link" href="/">Home</a>
|
<a id="auth-home-link" href="/">Home</a>
|
||||||
@@ -31,6 +32,10 @@
|
|||||||
<a id="auth-username" class="user-name" href="/"></a>
|
<a id="auth-username" class="user-name" href="/"></a>
|
||||||
</div>
|
</div>
|
||||||
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
|
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
|
||||||
|
<div id="theme-submenu-container" class="theme-submenu-container hidden">
|
||||||
|
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
|
||||||
|
<div id="theme-options" class="submenu-options hidden"></div>
|
||||||
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -38,8 +43,13 @@
|
|||||||
</header>
|
</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>
|
||||||
|
<button type="button" class="panel-toggle-btn" aria-expanded="false">
|
||||||
|
<span>Profile Settings</span>
|
||||||
|
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
|
||||||
|
</button>
|
||||||
|
</h2>
|
||||||
<form id="profile-form">
|
<form id="profile-form">
|
||||||
<label>
|
<label>
|
||||||
Username
|
Username
|
||||||
@@ -59,12 +69,18 @@
|
|||||||
</label>
|
</label>
|
||||||
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" />
|
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" />
|
||||||
<button type="submit">Save profile</button>
|
<button type="submit">Save profile</button>
|
||||||
|
<p>If you have not downloaded the plugin yet, <a href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi" download>find it here</a>.</p>
|
||||||
<p id="profile-status" class="status" role="status"></p>
|
<p id="profile-status" class="status" role="status"></p>
|
||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="link-item settings-panel">
|
<section class="link-item settings-panel minimized">
|
||||||
<h2>Email addresses</h2>
|
<h2>
|
||||||
|
<button type="button" class="panel-toggle-btn" aria-expanded="false">
|
||||||
|
<span>Email addresses</span>
|
||||||
|
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
|
||||||
|
</button>
|
||||||
|
</h2>
|
||||||
<div id="email-address-list" class="email-address-list" aria-live="polite">Loading email addresses...</div>
|
<div id="email-address-list" class="email-address-list" aria-live="polite">Loading email addresses...</div>
|
||||||
<form id="additional-email-form">
|
<form id="additional-email-form">
|
||||||
<label>
|
<label>
|
||||||
@@ -76,8 +92,13 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="link-item settings-panel">
|
<section class="link-item settings-panel minimized">
|
||||||
<h2>Password</h2>
|
<h2>
|
||||||
|
<button type="button" class="panel-toggle-btn" aria-expanded="false">
|
||||||
|
<span>Password</span>
|
||||||
|
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
|
||||||
|
</button>
|
||||||
|
</h2>
|
||||||
<form id="password-form">
|
<form id="password-form">
|
||||||
<label>
|
<label>
|
||||||
Current password
|
Current password
|
||||||
@@ -96,8 +117,13 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="link-item settings-panel">
|
<section class="link-item settings-panel minimized">
|
||||||
<h2>One-time password</h2>
|
<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>
|
<p>Use an authenticator app to add a second sign-in step.</p>
|
||||||
<div id="otp-disabled">
|
<div id="otp-disabled">
|
||||||
<button id="otp-setup" type="button">Set up one-time password</button>
|
<button id="otp-setup" type="button">Set up one-time password</button>
|
||||||
@@ -125,8 +151,13 @@
|
|||||||
<p id="otp-status" class="status" role="status"></p>
|
<p id="otp-status" class="status" role="status"></p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="link-item settings-panel">
|
<section class="link-item settings-panel minimized">
|
||||||
<h2>Mastodon</h2>
|
<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">
|
<form id="mastodon-form">
|
||||||
<label>
|
<label>
|
||||||
Mastodon server
|
Mastodon server
|
||||||
@@ -144,12 +175,12 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a
|
||||||
href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=2"></script>
|
<script src="/static/logout.js?v=2"></script>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
<script src="/static/profile.js?v=5"></script>
|
<script src="/static/profile.js?v=6"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
{
|
{
|
||||||
"version": "0.1.0"
|
"version": "0.3.0"
|
||||||
}
|
}
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.9 MiB |
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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__':
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -42,7 +42,10 @@
|
|||||||
"submissionFailed": {"message": "Senden fehlgeschlagen"},
|
"submissionFailed": {"message": "Senden fehlgeschlagen"},
|
||||||
"linkSaved": {"message": "Link auf $URL$ gespeichert.", "placeholders": {"url": {"content": "$1"}}},
|
"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."},
|
"linkAlreadyExists": {"message": "Dieser Link existiert bereits. Kommentar und Tags wurden aktualisiert und die Veröffentlichung erneut ausgelöst."},
|
||||||
"duplicateLinkWarning": {"message": "Dieser Link existiert bereits. Kommentar und Tags können aktualisiert werden; beim Absenden wird 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"}}},
|
"publishingErrors": {"message": "Fehler bei der Veröffentlichung: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
|
||||||
"submissionFailedConnection": {"message": "Senden fehlgeschlagen. Überprüfe die Verbindung zum Backend."},
|
"submissionFailedConnection": {"message": "Senden fehlgeschlagen. Überprüfe die Verbindung zum Backend."},
|
||||||
"loggedInAt": {"message": "$USERNAME$ ist bei $BACKEND$ angemeldet", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
"loggedInAt": {"message": "$USERNAME$ ist bei $BACKEND$ angemeldet", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||||
@@ -50,5 +53,7 @@
|
|||||||
"loginFailed": {"message": "Anmeldung fehlgeschlagen"},
|
"loginFailed": {"message": "Anmeldung fehlgeschlagen"},
|
||||||
"loggedInSuccessfully": {"message": "Erfolgreich angemeldet"},
|
"loggedInSuccessfully": {"message": "Erfolgreich angemeldet"},
|
||||||
"unableToLogIn": {"message": "Anmeldung nicht möglich. Überprüfe Backend-URL und Zugangsdaten."},
|
"unableToLogIn": {"message": "Anmeldung nicht möglich. Überprüfe Backend-URL und Zugangsdaten."},
|
||||||
"signedOut": {"message": "Abgemeldet"}
|
"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"}}}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,8 +133,17 @@
|
|||||||
"linkAlreadyExists": {
|
"linkAlreadyExists": {
|
||||||
"message": "This link already exists. Comment and tags were updated, and publishing was retriggered."
|
"message": "This link already exists. Comment and tags were updated, and publishing was retriggered."
|
||||||
},
|
},
|
||||||
"duplicateLinkWarning": {
|
"duplicateLinkSameUrl": {
|
||||||
"message": "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered."
|
"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": {
|
"publishingErrors": {
|
||||||
"message": "Publishing errors: $ERRORS$",
|
"message": "Publishing errors: $ERRORS$",
|
||||||
@@ -172,5 +181,30 @@
|
|||||||
},
|
},
|
||||||
"signedOut": {
|
"signedOut": {
|
||||||
"message": "Signed out"
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -42,7 +42,10 @@
|
|||||||
"submissionFailed": {"message": "Error al enviar"},
|
"submissionFailed": {"message": "Error al enviar"},
|
||||||
"linkSaved": {"message": "Enlace guardado en $URL$.", "placeholders": {"url": {"content": "$1"}}},
|
"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."},
|
"linkAlreadyExists": {"message": "Este enlace ya existe. Se actualizaron el comentario y las etiquetas, y se volvió a activar la publicación."},
|
||||||
"duplicateLinkWarning": {"message": "Este enlace ya existe. Puedes actualizar el comentario y las etiquetas; al enviarlo se volverá 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"}}},
|
"publishingErrors": {"message": "Errores de publicación: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
|
||||||
"submissionFailedConnection": {"message": "Error al enviar. Comprueba la conexión con el servidor."},
|
"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"}}},
|
"loggedInAt": {"message": "$USERNAME$ ha iniciado sesión en $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||||
@@ -50,5 +53,7 @@
|
|||||||
"loginFailed": {"message": "Error de inicio de sesión"},
|
"loginFailed": {"message": "Error de inicio de sesión"},
|
||||||
"loggedInSuccessfully": {"message": "Sesión iniciada correctamente"},
|
"loggedInSuccessfully": {"message": "Sesión iniciada correctamente"},
|
||||||
"unableToLogIn": {"message": "No se pudo iniciar sesión. Comprueba la URL y las credenciales."},
|
"unableToLogIn": {"message": "No se pudo iniciar sesión. Comprueba la URL y las credenciales."},
|
||||||
"signedOut": {"message": "Sesión cerrada"}
|
"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"}}}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,10 @@
|
|||||||
"submissionFailed": {"message": "Échec de l’envoi"},
|
"submissionFailed": {"message": "Échec de l’envoi"},
|
||||||
"linkSaved": {"message": "Lien enregistré sur $URL$.", "placeholders": {"url": {"content": "$1"}}},
|
"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."},
|
"linkAlreadyExists": {"message": "Ce lien existe déjà. Le commentaire et les étiquettes ont été mis à jour et la publication a été relancée."},
|
||||||
"duplicateLinkWarning": {"message": "Ce lien existe déjà. Le commentaire et les étiquettes peuvent être mis à jour ; l’envoi relancera la publication."},
|
"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"}}},
|
"publishingErrors": {"message": "Erreurs de publication : $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
|
||||||
"submissionFailedConnection": {"message": "Échec de l’envoi. Vérifiez la connexion au serveur."},
|
"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"}}},
|
"loggedInAt": {"message": "$USERNAME$ est connecté à $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||||
@@ -50,5 +53,7 @@
|
|||||||
"loginFailed": {"message": "Échec de la connexion"},
|
"loginFailed": {"message": "Échec de la connexion"},
|
||||||
"loggedInSuccessfully": {"message": "Connexion réussie"},
|
"loggedInSuccessfully": {"message": "Connexion réussie"},
|
||||||
"unableToLogIn": {"message": "Connexion impossible. Vérifiez l’URL du serveur et vos identifiants."},
|
"unableToLogIn": {"message": "Connexion impossible. Vérifiez l’URL du serveur et vos identifiants."},
|
||||||
"signedOut": {"message": "Déconnecté"}
|
"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"}}}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,10 @@
|
|||||||
"submissionFailed": {"message": "Verzenden mislukt"},
|
"submissionFailed": {"message": "Verzenden mislukt"},
|
||||||
"linkSaved": {"message": "Koppeling opgeslagen op $URL$.", "placeholders": {"url": {"content": "$1"}}},
|
"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."},
|
"linkAlreadyExists": {"message": "Deze koppeling bestaat al. De opmerking en tags zijn bijgewerkt en publiceren is opnieuw gestart."},
|
||||||
"duplicateLinkWarning": {"message": "Deze koppeling bestaat al. De opmerking en tags kunnen worden bijgewerkt; na verzenden wordt publiceren 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"}}},
|
"publishingErrors": {"message": "Publicatiefouten: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
|
||||||
"submissionFailedConnection": {"message": "Verzenden mislukt. Controleer de verbinding met de backend."},
|
"submissionFailedConnection": {"message": "Verzenden mislukt. Controleer de verbinding met de backend."},
|
||||||
"loggedInAt": {"message": "$USERNAME$ is ingelogd op $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
"loggedInAt": {"message": "$USERNAME$ is ingelogd op $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||||
@@ -50,5 +53,7 @@
|
|||||||
"loginFailed": {"message": "Inloggen mislukt"},
|
"loginFailed": {"message": "Inloggen mislukt"},
|
||||||
"loggedInSuccessfully": {"message": "Succesvol ingelogd"},
|
"loggedInSuccessfully": {"message": "Succesvol ingelogd"},
|
||||||
"unableToLogIn": {"message": "Inloggen mislukt. Controleer de backend-URL en inloggegevens."},
|
"unableToLogIn": {"message": "Inloggen mislukt. Controleer de backend-URL en inloggegevens."},
|
||||||
"signedOut": {"message": "Uitgelogd"}
|
"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"}}}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"manifest_version": 3,
|
"manifest_version": 3,
|
||||||
"name": "__MSG_extensionName__",
|
"name": "__MSG_extensionName__",
|
||||||
"version": "0.1.0",
|
"version": "0.3.0",
|
||||||
"description": "__MSG_extensionDescription__",
|
"description": "__MSG_extensionDescription__",
|
||||||
"default_locale": "en-US",
|
"default_locale": "en-US",
|
||||||
"permissions": [
|
"permissions": [
|
||||||
@@ -30,7 +30,7 @@
|
|||||||
"browser_specific_settings": {
|
"browser_specific_settings": {
|
||||||
"gecko": {
|
"gecko": {
|
||||||
"id": "linklog@kolkman.org",
|
"id": "linklog@kolkman.org",
|
||||||
"strict_min_version": "112.0",
|
"strict_min_version": "142.0",
|
||||||
"data_collection_permissions": {
|
"data_collection_permissions": {
|
||||||
"required": ["websiteActivity"],
|
"required": ["websiteActivity"],
|
||||||
"optional": []
|
"optional": []
|
||||||
|
|||||||
@@ -186,8 +186,7 @@ async function signOut() {
|
|||||||
if (sessionSettings.accessToken && settings.backendUrl && await hasBackendPermission(backendUrl)) {
|
if (sessionSettings.accessToken && settings.backendUrl && await hasBackendPermission(backendUrl)) {
|
||||||
await fetch(`${backendUrl}/api/auth/logout`, {
|
await fetch(`${backendUrl}/api/auth/logout`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: {Authorization: `Bearer ${sessionSettings.accessToken}`},
|
||||||
body: JSON.stringify({ token: sessionSettings.accessToken }),
|
|
||||||
}).catch(() => undefined);
|
}).catch(() => undefined);
|
||||||
}
|
}
|
||||||
await clearSession();
|
await clearSession();
|
||||||
|
|||||||
@@ -149,6 +149,18 @@ button {
|
|||||||
color: #f38ba8;
|
color: #f38ba8;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.char-count {
|
||||||
|
margin: -6px 0 10px;
|
||||||
|
color: #a6adc8;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.char-count.over-limit {
|
||||||
|
color: #f38ba8;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
.auth-session {
|
.auth-session {
|
||||||
margin-bottom: 10px;
|
margin-bottom: 10px;
|
||||||
border: 1px solid #585b70;
|
border: 1px solid #585b70;
|
||||||
|
|||||||
@@ -26,6 +26,7 @@
|
|||||||
<span data-i18n="titleLabel">Title</span>
|
<span data-i18n="titleLabel">Title</span>
|
||||||
<input id="title" name="title" type="text" />
|
<input id="title" name="title" type="text" />
|
||||||
</label>
|
</label>
|
||||||
|
<button type="button" id="refetch-title" class="secondary" data-i18n="refetchTitle">Re-fetch title</button>
|
||||||
|
|
||||||
<label>
|
<label>
|
||||||
<span data-i18n="urlLabel">URL</span>
|
<span data-i18n="urlLabel">URL</span>
|
||||||
@@ -36,6 +37,7 @@
|
|||||||
<span data-i18n="commentLabel">Comment</span>
|
<span data-i18n="commentLabel">Comment</span>
|
||||||
<textarea id="comment" name="comment" rows="3" data-i18n-placeholder="commentPlaceholder" placeholder="Your comment"></textarea>
|
<textarea id="comment" name="comment" rows="3" data-i18n-placeholder="commentPlaceholder" placeholder="Your comment"></textarea>
|
||||||
</label>
|
</label>
|
||||||
|
<div id="character-count" class="char-count" aria-live="polite"></div>
|
||||||
|
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend data-i18n="tagsLabel">Tags</legend>
|
<legend data-i18n="tagsLabel">Tags</legend>
|
||||||
|
|||||||
+142
-5
@@ -13,10 +13,15 @@ const feedLink = document.getElementById('feed-link');
|
|||||||
const authWarning = document.getElementById('auth-warning');
|
const authWarning = document.getElementById('auth-warning');
|
||||||
const warningSettingsButton = document.getElementById('warning-settings');
|
const warningSettingsButton = document.getElementById('warning-settings');
|
||||||
const authSession = document.getElementById('auth-session');
|
const authSession = document.getElementById('auth-session');
|
||||||
|
const refetchTitleButton = document.getElementById('refetch-title');
|
||||||
|
const characterCountEl = document.getElementById('character-count');
|
||||||
const sessionStore = browser.storage.session;
|
const sessionStore = browser.storage.session;
|
||||||
|
|
||||||
const t = window.linklogI18n;
|
const t = window.linklogI18n;
|
||||||
|
|
||||||
|
let maxPostCharacters = 500;
|
||||||
|
let mastodonPostPrefix = 'From my #LinkLog: ';
|
||||||
|
|
||||||
function normalizeBackendOrigin(backendUrl) {
|
function normalizeBackendOrigin(backendUrl) {
|
||||||
try {
|
try {
|
||||||
const url = new URL(backendUrl);
|
const url = new URL(backendUrl);
|
||||||
@@ -35,8 +40,14 @@ async function hasBackendPermission(backendUrl) {
|
|||||||
return browser.permissions.contains({origins: [`${origin}/*`]});
|
return browser.permissions.contains({origins: [`${origin}/*`]});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Splits on \n into real <br> line breaks without using innerHTML.
|
||||||
function setStatus(message, isError = false) {
|
function setStatus(message, isError = false) {
|
||||||
statusEl.textContent = message;
|
const lines = message.split('\n');
|
||||||
|
statusEl.replaceChildren(
|
||||||
|
...lines.flatMap((line, index) => (
|
||||||
|
index === 0 ? [document.createTextNode(line)] : [document.createElement('br'), document.createTextNode(line)]
|
||||||
|
)),
|
||||||
|
);
|
||||||
statusEl.classList.remove('hidden');
|
statusEl.classList.remove('hidden');
|
||||||
statusEl.classList.toggle('error', isError);
|
statusEl.classList.toggle('error', isError);
|
||||||
statusEl.classList.toggle('success', !isError);
|
statusEl.classList.toggle('success', !isError);
|
||||||
@@ -185,9 +196,11 @@ async function loadExistingTags() {
|
|||||||
const checkbox = document.createElement('input');
|
const checkbox = document.createElement('input');
|
||||||
checkbox.type = 'checkbox';
|
checkbox.type = 'checkbox';
|
||||||
checkbox.value = tag;
|
checkbox.value = tag;
|
||||||
|
checkbox.addEventListener('change', updateCharacterCount);
|
||||||
label.append(checkbox, document.createTextNode(` ${tag}`));
|
label.append(checkbox, document.createTextNode(` ${tag}`));
|
||||||
return label;
|
return label;
|
||||||
}));
|
}));
|
||||||
|
updateCharacterCount();
|
||||||
}
|
}
|
||||||
|
|
||||||
function getTags() {
|
function getTags() {
|
||||||
@@ -196,6 +209,79 @@ function getTags() {
|
|||||||
return [...new Set([...selected, ...newTags])].slice(0, 10);
|
return [...new Set([...selected, ...newTags])].slice(0, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Load public app settings (e.g. the Mastodon post length limit) once a backend is configured.
|
||||||
|
async function loadConfig() {
|
||||||
|
const settings = await getSettings();
|
||||||
|
if (!settings.backendUrl || !(await hasBackendPermission(settings.backendUrl))) return;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${settings.backendUrl}/api/public/config`);
|
||||||
|
if (!response.ok) return;
|
||||||
|
const config = await response.json();
|
||||||
|
if (config.max_post_characters) maxPostCharacters = config.max_post_characters;
|
||||||
|
} catch (error) {
|
||||||
|
// Character-count warning is advisory; ignore config load failures.
|
||||||
|
}
|
||||||
|
updateCharacterCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load the user's configured Mastodon post prefix, so the estimated post length matches the server.
|
||||||
|
async function loadMastodonPrefix() {
|
||||||
|
const settings = await getSettings();
|
||||||
|
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl))) return;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${settings.backendUrl}/api/user/plugins/mastodon`, {
|
||||||
|
headers: {'Authorization': `Bearer ${settings.accessToken}`},
|
||||||
|
});
|
||||||
|
if (!response.ok) return;
|
||||||
|
const config = await response.json();
|
||||||
|
if (config.post_prefix) {
|
||||||
|
mastodonPostPrefix = config.post_prefix;
|
||||||
|
} else if (config.hashtag) {
|
||||||
|
mastodonPostPrefix = `#${String(config.hashtag).trim().replace(/^#/, '')} `;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Character-count warning is advisory; ignore config load failures.
|
||||||
|
}
|
||||||
|
updateCharacterCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 = getTags();
|
||||||
|
if (tags.length) parts.push(tags.join(' '));
|
||||||
|
return parts.join('\n\n').length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCharacterCount() {
|
||||||
|
const length = estimatePostLength();
|
||||||
|
const overLimit = length > maxPostCharacters;
|
||||||
|
characterCountEl.textContent = overLimit
|
||||||
|
? t('characterCountOverLimit', [String(length), String(maxPostCharacters), String(length - maxPostCharacters)])
|
||||||
|
: t('characterCount', [String(length), String(maxPostCharacters)]);
|
||||||
|
characterCountEl.classList.toggle('over-limit', overLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
[titleInput, urlInput, commentInput, newTagsInput].forEach((input) => {
|
||||||
|
input.addEventListener('input', updateCharacterCount);
|
||||||
|
});
|
||||||
|
|
||||||
function removeKnownTrackingParams(urlString) {
|
function removeKnownTrackingParams(urlString) {
|
||||||
try {
|
try {
|
||||||
const url = new URL(urlString);
|
const url = new URL(urlString);
|
||||||
@@ -225,20 +311,54 @@ async function checkExistingLink() {
|
|||||||
const settings = await getSettings();
|
const settings = await getSettings();
|
||||||
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl)) || !titleInput.value || !urlInput.value) return;
|
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl)) || !titleInput.value || !urlInput.value) return;
|
||||||
try {
|
try {
|
||||||
|
const url = removeKnownTrackingParams(urlInput.value);
|
||||||
const response = await fetch(`${settings.backendUrl}/api/links/check?${new URLSearchParams({
|
const response = await fetch(`${settings.backendUrl}/api/links/check?${new URLSearchParams({
|
||||||
title: titleInput.value,
|
title: titleInput.value,
|
||||||
url: removeKnownTrackingParams(urlInput.value),
|
url,
|
||||||
})}`, {
|
})}`, {
|
||||||
headers: {'Authorization': `Bearer ${settings.accessToken}`},
|
headers: {'Authorization': `Bearer ${settings.accessToken}`},
|
||||||
});
|
});
|
||||||
if (response.ok && (await response.json()).exists) {
|
if (!response.ok) return;
|
||||||
setStatus(t('duplicateLinkWarning'), true);
|
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);
|
||||||
|
const message = urlMatches ? t('duplicateLinkSameUrl') : t('duplicateLinkDifferentUrl');
|
||||||
|
setStatus(message, true);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Duplicate checking is advisory; submission remains available.
|
// Duplicate checking is advisory; submission remains available.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Re-fetch the title from the backend scraper, for when the URL was edited after the initial tab-based fill.
|
||||||
|
let lastScrapedUrl = null;
|
||||||
|
async function fetchTitle(url, { force = false } = {}) {
|
||||||
|
const settings = await getSettings();
|
||||||
|
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl))) return;
|
||||||
|
if (!url || (!force && (titleInput.value.trim() || url === lastScrapedUrl))) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${settings.backendUrl}/api/scrape?url=${encodeURIComponent(url)}`, {
|
||||||
|
headers: {'Authorization': `Bearer ${settings.accessToken}`},
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
if (force) setStatus(t('titleFetchFailed'), true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lastScrapedUrl = url;
|
||||||
|
const data = await response.json();
|
||||||
|
if (data.title) {
|
||||||
|
titleInput.value = data.title;
|
||||||
|
} else if (force) {
|
||||||
|
setStatus(t('titleFetchFailed'), true);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (force) setStatus(t('titleFetchFailed'), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleSubmit(event) {
|
async function handleSubmit(event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setStatus(t('submitting'), false);
|
setStatus(t('submitting'), false);
|
||||||
@@ -305,6 +425,23 @@ async function handleSubmit(event) {
|
|||||||
openSettingsButton.addEventListener('click', () => browser.runtime.openOptionsPage());
|
openSettingsButton.addEventListener('click', () => browser.runtime.openOptionsPage());
|
||||||
warningSettingsButton.addEventListener('click', () => browser.runtime.openOptionsPage());
|
warningSettingsButton.addEventListener('click', () => browser.runtime.openOptionsPage());
|
||||||
form.addEventListener('submit', handleSubmit);
|
form.addEventListener('submit', handleSubmit);
|
||||||
populateCurrentTab().then(checkExistingLink);
|
urlInput.addEventListener('blur', async () => {
|
||||||
|
await fetchTitle(removeKnownTrackingParams(urlInput.value.trim()));
|
||||||
|
checkExistingLink();
|
||||||
|
});
|
||||||
|
titleInput.addEventListener('blur', checkExistingLink);
|
||||||
|
refetchTitleButton.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const url = removeKnownTrackingParams(urlInput.value.trim());
|
||||||
|
if (!url) {
|
||||||
|
setStatus(t('titleFetchFailed'), true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
titleInput.value = '';
|
||||||
|
fetchTitle(url, { force: true });
|
||||||
|
});
|
||||||
|
populateCurrentTab().then(checkExistingLink).then(updateCharacterCount);
|
||||||
loadExistingTags();
|
loadExistingTags();
|
||||||
updateFeedLink();
|
updateFeedLink();
|
||||||
|
loadConfig();
|
||||||
|
loadMastodonPrefix();
|
||||||
|
|||||||
@@ -2,9 +2,35 @@
|
|||||||
"addons": {
|
"addons": {
|
||||||
"linklog@kolkman.org": {
|
"linklog@kolkman.org": {
|
||||||
"updates": [
|
"updates": [
|
||||||
|
{
|
||||||
|
"version": "0.3.0",
|
||||||
|
"update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.3.0.xpi",
|
||||||
|
"update_hash": "sha256:c4cc16a7e96885caa759c803dca90dd43fdf0befc43457655f6eeb6fd51a4e7f",
|
||||||
|
"applications": {
|
||||||
|
"gecko": {
|
||||||
|
"strict_min_version": "142.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.2.0",
|
||||||
|
"update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.2.0.xpi",
|
||||||
|
"update_hash": "sha256:86619ec9aa35345c5c2bcad8fa5701762b8bd237ad9457b131404ff68bc2ce6b",
|
||||||
|
"applications": {
|
||||||
|
"gecko": {
|
||||||
|
"strict_min_version": "142.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi"
|
"update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi",
|
||||||
|
"update_hash": "sha256:d95e23339facfa2a499bb35f9130d41739f622a3c0ac197ac3fd8cb76d6d6110",
|
||||||
|
"applications": {
|
||||||
|
"gecko": {
|
||||||
|
"strict_min_version": "142.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user