Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c11b25c20a | ||
|
|
c27aad58ae | ||
|
|
7dffaad8e5 | ||
|
|
583026418d | ||
|
|
fa6d88a768 | ||
|
|
b6c01878a8 | ||
|
|
5dbef8f23f | ||
|
|
ffb12a36b5 | ||
|
|
04b8a5a8b9 | ||
|
|
b4b40e5c2c | ||
|
|
16c9c3a03f | ||
|
|
018c02c759 | ||
|
|
b03a241be2 | ||
|
|
314959c7bf | ||
|
|
ed76b35600 | ||
|
|
b971d2ed97 | ||
|
|
580c2a4257 | ||
|
|
c3c3c8e1a6 | ||
|
|
4049a197b9 | ||
|
|
1a24d21d0a | ||
|
|
7e9bf81bd1 | ||
|
|
27f26e615a | ||
|
|
c70850b44d | ||
|
|
3e61302bf6 | ||
|
|
94997752b6 | ||
|
|
01a4ed42bd | ||
|
|
6772bf7107 | ||
|
|
0287305884 | ||
|
|
fec7836384 | ||
|
|
079eb146f6 | ||
|
|
dd44b380ce | ||
|
|
b3383e29a7 | ||
|
|
d18acf813a | ||
|
|
6f1fbaa5ea | ||
|
|
f503dbaef2 | ||
|
|
80a3a3d541 | ||
|
|
4854eb8df6 | ||
|
|
134e463a81 | ||
|
|
72a4741cac | ||
|
|
fec4c8def5 | ||
|
|
158bc64268 | ||
|
|
3fdf146498 | ||
|
|
f0ae526a96 | ||
|
|
6651ce8993 | ||
|
|
dd450ea3b5 | ||
|
|
c012f1edfa | ||
|
|
c748241291 | ||
|
|
95accdf436 | ||
|
|
9deb28330a | ||
|
|
2e5610555e | ||
|
|
22add753fe | ||
|
|
333aab8e8a | ||
|
|
b35249cb86 | ||
|
|
57e9775882 | ||
|
|
102d8e533c | ||
|
|
defe7a83a9 | ||
|
|
07e520e03f | ||
|
|
bd78e3b86e | ||
|
|
05c4ebe526 | ||
|
|
d38db06c30 | ||
|
|
442a28e741 | ||
|
|
38908b9a25 | ||
|
|
08b0ee013f | ||
|
|
5d60bd801c | ||
|
|
d896d3d068 | ||
|
|
1cba4e8649 | ||
|
|
f6077f0063 | ||
|
|
315a89380f | ||
|
|
4dc8fcfa9c | ||
|
|
759c284b26 | ||
|
|
4ae184f24c |
@@ -8,21 +8,25 @@ APP_HEALTHCHECK_TIMEOUT=5s
|
||||
APP_HEALTHCHECK_START_PERIOD=10s
|
||||
APP_HEALTHCHECK_RETRIES=3
|
||||
LINKLOG_APP_NAME=LinkLog
|
||||
LINKLOG_VERSION=0.1.0
|
||||
LINKLOG_SECRET_KEY=replace-with-a-long-random-secret
|
||||
LINKLOG_TOKEN_EXPIRY_DAYS=30
|
||||
LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key
|
||||
LINKLOG_TOKEN_EXPIRY_MINUTES=15
|
||||
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS=30
|
||||
LINKLOG_PUBLIC_URL=linklog.example.com
|
||||
LINKLOG_SMTP_HOST=
|
||||
LINKLOG_SMTP_PORT=587
|
||||
LINKLOG_SMTP_USERNAME=
|
||||
LINKLOG_SMTP_PASSWORD=
|
||||
LINKLOG_SMTP_FROM=LinkLog <no-reply@localhost>
|
||||
LINKLOG_SMTP_USE_TLS=true
|
||||
LINKLOG_EMAIL_VERIFICATION_EXPIRY_HOURS=24
|
||||
LINKLOG_PASSWORD_RESET_EXPIRY_HOURS=1
|
||||
LINKLOG_MASTODON_CLIENT_NAME=LinkLog
|
||||
LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES=10
|
||||
LINKLOG_LOG_LEVEL=INFO
|
||||
# Optional comma-separated override. Leave empty to use the built-in list.
|
||||
LINKLOG_TRACKING_PARAMS=
|
||||
# Keep the default path when using the named linklog_data volume.
|
||||
LINKLOG_DATABASE_PATH=/app/backend/data/linklog.db
|
||||
|
||||
# Traefik
|
||||
TRAEFIK_IMAGE=traefik:v3.1
|
||||
TRAEFIK_CONTAINER_NAME=linklog-traefik
|
||||
TRAEFIK_HOST=localhost
|
||||
TRAEFIK_HTTP_PORT=80
|
||||
TRAEFIK_HTTP_INTERNAL_PORT=80
|
||||
TRAEFIK_DASHBOARD_PORT=8080
|
||||
TRAEFIK_DASHBOARD_BIND_ADDRESS=127.0.0.1
|
||||
TRAEFIK_API_INSECURE=true
|
||||
TRAEFIK_RESTART_POLICY=unless-stopped
|
||||
DOCKER_SOCKET_PATH=/var/run/docker.sock
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Build LinkLog Development Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
IMAGE_NAME: git.kolkman.org/olaf/link-log
|
||||
|
||||
jobs:
|
||||
development-image:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out main
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Log in to Gitea container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.kolkman.org
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
- name: Build and publish development image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ env.IMAGE_NAME }}:development
|
||||
labels: |
|
||||
org.opencontainers.image.source=https://git.kolkman.org/olaf/Link-Log
|
||||
org.opencontainers.image.revision=${{ gitea.sha }}
|
||||
org.opencontainers.image.version=development
|
||||
@@ -0,0 +1,151 @@
|
||||
name: Release LinkLog
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
IMAGE_NAME: git.kolkman.org/olaf/link-log
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out release tag
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Validate versions and signed XPI
|
||||
id: release
|
||||
run: |
|
||||
python3 scripts/release/validate_release.py --github-output "$GITHUB_OUTPUT"
|
||||
backend_version=$(python3 -c "import re; text=open('backend/app/core/config.py').read(); print(re.search(r\"version: str = os\\.getenv\\('LINKLOG_VERSION', '([^']+)'\\)\", text).group(1))")
|
||||
if [ "${GITHUB_REF_NAME#v}" != "$backend_version" ]; then
|
||||
echo "tag ${GITHUB_REF_NAME} does not match backend version $backend_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Log in to Gitea container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.kolkman.org
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
- name: Build and publish Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.IMAGE_NAME }}:${{ steps.release.outputs.backend_version }}
|
||||
${{ env.IMAGE_NAME }}:latest
|
||||
labels: |
|
||||
org.opencontainers.image.version=${{ steps.release.outputs.backend_version }}
|
||||
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
|
||||
id: gitea_release
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
VERSION: ${{ steps.release.outputs.backend_version }}
|
||||
run: |
|
||||
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 \
|
||||
-H "Authorization: token $RELEASE_TOKEN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data-binary "@$payload_file" \
|
||||
https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases)
|
||||
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" != 0
|
||||
upload_url="https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases/$release_id/assets"
|
||||
echo "upload_url=$upload_url" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload release README
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
UPLOAD_URL: ${{ steps.gitea_release.outputs.upload_url }}
|
||||
run: |
|
||||
response_status=$(curl --silent --show-error -o /tmp/linklog-readme-upload-response -w '%{http_code}' \
|
||||
-X POST -H "Authorization: token $RELEASE_TOKEN" \
|
||||
-H 'Content-Type: text/markdown' \
|
||||
--data-binary @release-readme.md \
|
||||
"$UPLOAD_URL?name=README.md")
|
||||
if [ "$response_status" -lt 200 ] || [ "$response_status" -ge 300 ]; then
|
||||
cat /tmp/linklog-readme-upload-response >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish release links
|
||||
env:
|
||||
BACKEND_VERSION: ${{ steps.release.outputs.backend_version }}
|
||||
PLUGIN_VERSION: ${{ steps.release.outputs.plugin_version }}
|
||||
SIGNED_XPI: ${{ steps.release.outputs.signed_xpi }}
|
||||
run: |
|
||||
echo "Docker image: $IMAGE_NAME:$BACKEND_VERSION"
|
||||
echo "Signed XPI: https://git.kolkman.org/olaf/Link-Log/raw/branch/main/$SIGNED_XPI (version $PLUGIN_VERSION)"
|
||||
echo "Release README: README.md"
|
||||
@@ -15,3 +15,5 @@ __pycache__/
|
||||
*.sqlite3
|
||||
*.log
|
||||
backend/data/avatars/
|
||||
LinkLog.afdesign~lock~
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Copyright © 2026 Olaf Kolkman
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
LinkLog is licensed under the GNU General Public License, version 3 or any later version (GPL-3.0-or-later).
|
||||
|
||||
Copyright (C) 2026 Olaf Kolkman
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
The complete license text is available at:
|
||||
https://www.gnu.org/licenses/gpl-3.0.html
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
|
||||
<g transform="matrix(1,0,0,1,-669.006,-255.89)">
|
||||
<g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)">
|
||||
<rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(24, 24, 37);"/>
|
||||
</g>
|
||||
<g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)">
|
||||
<path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/>
|
||||
</g>
|
||||
<g transform="matrix(0.135097,0,0,0.266653,668.366,1282.68)">
|
||||
<path d="M846.315,1802.1L846.315,1747.02C926.615,1744.29 989.248,1732.47 1034.22,1711.57C1079.18,1690.67 1110.8,1656.2 1129.07,1608.15C1147.34,1560.11 1156.47,1494.29 1156.47,1410.69C1156.47,1348.97 1150.95,1297.51 1139.91,1256.3C1128.87,1215.09 1110.5,1182.76 1084.81,1159.33C1067.94,1144.48 1048.07,1132.76 1025.18,1124.17C1002.3,1115.58 975.999,1109.52 946.288,1106.01C916.577,1102.49 883.253,1100.73 846.315,1100.73L846.315,1045.65L2092.36,1045.65L2092.36,1100.73C2037.36,1100.73 1990.18,1104.93 1950.83,1113.33C1911.49,1121.73 1879.47,1137.06 1854.78,1159.33C1830.08,1181.59 1811.92,1212.94 1800.27,1253.37C1788.63,1293.8 1782.81,1346.24 1782.81,1410.69L1782.81,1744.09C1860.7,1744.09 1935.18,1732.66 2006.24,1709.81C2077.31,1686.96 2140.34,1657.18 2195.35,1620.46C2250.35,1584.13 2294.21,1543.51 2326.94,1498.58C2359.66,1453.66 2377.83,1409.91 2381.44,1367.33L2444.68,1367.33C2444.68,1388.82 2444.07,1418.6 2442.87,1456.69C2441.66,1494.78 2439.86,1536.28 2437.45,1581.2C2434.64,1626.9 2431.33,1668.9 2427.51,1707.18C2423.7,1745.46 2419.18,1777.1 2413.96,1802.1L846.315,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M3043.37,1093.7C3001.22,1093.7 2961.37,1089.99 2923.83,1082.57C2886.29,1075.15 2853.66,1064.99 2825.96,1052.1C2797.86,1039.21 2775.67,1024.17 2759.41,1006.98C2743.15,989.794 2735.02,971.435 2735.02,951.904C2735.02,924.951 2748.97,900.732 2776.88,879.247C2804.78,857.763 2842.12,840.673 2888.9,827.978C2935.67,815.283 2987.16,808.935 3043.37,808.935C3101.59,808.935 3153.98,815.38 3200.56,828.271C3247.13,841.161 3284.07,858.447 3311.37,880.126C3338.67,901.806 3352.32,925.732 3352.32,951.904C3352.32,977.294 3338.67,1000.83 3311.37,1022.51C3284.07,1044.19 3247.13,1061.47 3200.56,1074.37C3153.98,1087.26 3101.59,1093.7 3043.37,1093.7ZM2498.94,1802.1L2498.94,1747.02C2608.95,1743.12 2686.24,1720.16 2730.81,1678.17C2775.37,1636.18 2797.66,1576.9 2797.66,1500.34C2797.66,1422.22 2776.08,1365.97 2732.91,1331.59C2689.75,1297.22 2618.39,1280.03 2518.82,1280.03L2518.82,1224.95L3327.03,1172.22L3327.03,1500.34C3327.03,1551.12 3333.76,1594.38 3347.2,1630.13C3360.66,1665.87 3386.05,1693.6 3423.39,1713.33C3460.73,1733.06 3515.53,1744.29 3587.8,1747.02L3587.8,1802.1L2498.94,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M3625.19,1802.1L3625.19,1747.02C3724.76,1743.12 3796.43,1721.83 3840.19,1683.15C3862.68,1663.62 3878.94,1639.6 3888.97,1611.08C3899.01,1582.57 3904.03,1549.17 3904.03,1510.89C3904.03,1447.22 3894.7,1399.37 3876.03,1367.33C3857.36,1335.3 3827.64,1313.72 3786.89,1302.59C3746.14,1291.45 3692.24,1285.89 3625.19,1285.89L3625.19,1230.81L4433.4,1178.08L4433.4,1274.76C4505.67,1243.51 4581.56,1216.94 4661.05,1195.07C4740.55,1173.19 4822.65,1162.26 4907.37,1162.26C4940.29,1162.26 4973.62,1164.31 5007.34,1168.41C5041.07,1172.51 5073.19,1183.93 5103.7,1202.68C5122.98,1214.79 5139.84,1231.2 5154.29,1251.9C5168.34,1273 5179.59,1299.17 5188.02,1330.42C5196.45,1361.67 5200.66,1399.37 5200.66,1443.51L5199.46,1488.62C5198.26,1504.25 5197.65,1521.24 5197.65,1539.6C5197.65,1573.97 5199.46,1604.15 5203.07,1630.13C5206.69,1656.1 5215.92,1677.68 5230.78,1694.87C5245.23,1712.06 5267.51,1725.05 5297.63,1733.84C5327.74,1742.63 5369.29,1747.02 5422.29,1747.02L5422.29,1802.1L4575.53,1802.1L4575.53,1757.57C4601.63,1741.16 4619.7,1713.62 4629.74,1674.95C4639.77,1636.28 4644.79,1583.35 4644.79,1516.16C4644.79,1457.96 4639.47,1415.09 4628.83,1387.55C4618.19,1360.01 4603.74,1342.14 4585.47,1333.93C4567.2,1325.73 4546.83,1321.63 4524.34,1321.63C4510.29,1321.63 4495.54,1323.1 4480.08,1326.03C4464.62,1328.95 4449.06,1332.96 4433.4,1338.04L4433.4,1526.71C4433.4,1595.07 4438.52,1646.53 4448.76,1681.1C4459,1715.67 4476.97,1741.16 4502.66,1757.57L4502.66,1802.1L3625.19,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M6760.3,1835.5C6693.65,1835.5 6638.55,1833.06 6594.99,1828.17C6551.42,1823.29 6518.2,1814.4 6495.32,1801.51C6481.26,1793.7 6469.62,1783.35 6460.39,1770.46C6451.55,1757.96 6444.73,1743.31 6439.91,1726.51C6435.09,1709.72 6430.67,1690.38 6426.66,1668.51C6422.64,1647.41 6416.92,1627.68 6409.49,1609.33C6402.07,1590.97 6387.21,1575.83 6364.93,1563.91C6342.65,1552 6306.81,1545.85 6257.43,1545.46C6258.23,1615.38 6265.66,1666.45 6279.71,1698.68C6293.76,1730.91 6320.86,1747.02 6361.01,1747.02L6361.01,1802.1L5449.21,1802.1L5449.21,1747.02C5485.35,1745.85 5517.27,1742.92 5544.97,1738.23C5600.78,1728.86 5642.33,1707.96 5669.64,1675.54C5683.69,1658.35 5695.13,1636.87 5703.96,1611.08C5712.4,1585.3 5718.52,1554.15 5722.33,1517.63C5726.15,1481.1 5728.05,1438.43 5728.05,1389.6C5728.05,1315.38 5722.84,1255.22 5712.4,1209.13C5701.96,1163.04 5685.49,1127.1 5663.01,1101.32C5640.53,1075.93 5611.72,1058.74 5576.59,1049.76C5541.46,1040.77 5499,1036.28 5449.21,1036.28L5449.21,981.786L6257.43,929.052L6257.43,1462.84C6286.74,1442.92 6314.84,1422.12 6341.74,1400.44C6368.64,1378.76 6392.33,1358.54 6412.81,1339.79C6457.78,1298.39 6480.26,1272.8 6480.26,1263.04C6480.26,1255.22 6471.63,1250.15 6454.36,1247.8C6437.1,1245.46 6413.61,1244.29 6383.9,1244.29L6383.9,1189.21L7053.6,1189.21L7053.6,1244.29C7005.82,1244.29 6953.42,1249.76 6896.41,1260.69C6839.4,1271.63 6778.97,1288.04 6715.14,1309.91C6650.9,1331.79 6583.85,1359.33 6513.99,1392.53C6444.12,1425.73 6372.46,1464.6 6298.98,1509.13C6373.66,1497.41 6449.04,1488.13 6525.13,1481.3C6601.21,1474.46 6668.36,1471.04 6726.58,1471.04C6810.89,1471.04 6875.33,1480.42 6919.9,1499.17C6965.67,1518.7 6994.58,1550.34 7006.62,1594.09C7013.85,1619.87 7023.18,1641.94 7034.63,1660.3C7046.07,1678.66 7058.21,1693.9 7071.06,1706.01C7083.91,1718.12 7096.86,1727.2 7109.91,1733.25C7122.96,1739.31 7134.3,1742.92 7143.93,1744.09L7143.93,1805.62C7133.49,1808.74 7116.23,1811.96 7092.14,1815.28C7068.05,1818.6 7039.14,1821.83 7005.42,1824.95C6971.29,1828.08 6933.35,1830.62 6891.59,1832.57C6849.84,1834.52 6806.07,1835.5 6760.3,1835.5Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M7746.18,1802.1L7746.18,1747.02C7826.48,1744.29 7889.11,1732.47 7934.08,1711.57C7979.05,1690.67 8010.67,1656.2 8028.93,1608.15C8047.2,1560.11 8056.34,1494.29 8056.34,1410.69C8056.34,1348.97 8050.82,1297.51 8039.77,1256.3C8028.73,1215.09 8010.36,1182.76 7984.67,1159.33C7967.81,1144.48 7947.93,1132.76 7925.05,1124.17C7902.16,1115.58 7875.86,1109.52 7846.15,1106.01C7816.44,1102.49 7783.12,1100.73 7746.18,1100.73L7746.18,1045.65L8992.23,1045.65L8992.23,1100.73C8937.22,1100.73 8890.05,1104.93 8850.7,1113.33C8811.35,1121.73 8779.33,1137.06 8754.64,1159.33C8729.95,1181.59 8711.78,1212.94 8700.14,1253.37C8688.49,1293.8 8682.67,1346.24 8682.67,1410.69L8682.67,1744.09C8760.56,1744.09 8835.04,1732.66 8906.1,1709.81C8977.17,1686.96 9040.2,1657.18 9095.21,1620.46C9150.22,1584.13 9194.08,1543.51 9226.8,1498.58C9259.52,1453.66 9277.69,1409.91 9281.3,1367.33L9344.54,1367.33C9344.54,1388.82 9343.94,1418.6 9342.73,1456.69C9341.53,1494.78 9339.72,1536.28 9337.31,1581.2C9334.5,1626.9 9331.19,1668.9 9327.38,1707.18C9323.56,1745.46 9319.05,1777.1 9313.83,1802.1L7746.18,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M10190.6,1828.47C10046.1,1828.47 9919.52,1816.36 9810.91,1792.14C9702.31,1767.92 9617.89,1731.2 9557.67,1681.98C9497.44,1632.76 9467.33,1570.65 9467.33,1495.65C9467.33,1439.01 9484.69,1389.6 9519.43,1347.41C9554.15,1305.22 9603.24,1270.46 9666.67,1243.12C9730.11,1215.38 9806.19,1194.87 9894.93,1181.59C9983.66,1168.31 10082.2,1161.67 10190.6,1161.67C10298.6,1161.67 10397.2,1168.31 10486.3,1181.59C10575.5,1194.87 10651.5,1215.38 10714.6,1243.12C10778,1270.46 10827,1305.22 10861.5,1347.41C10896.1,1389.6 10913.3,1439.01 10913.3,1495.65C10913.3,1551.9 10896.1,1600.83 10861.5,1642.43C10827,1684.03 10778,1718.7 10714.6,1746.43C10651.5,1773.78 10575.5,1794.29 10486.3,1807.96C10397.2,1821.63 10298.6,1828.47 10190.6,1828.47ZM10190.6,1766.94C10209.5,1766.94 10226.5,1759.62 10241.5,1744.97C10256.6,1730.32 10269.5,1710.5 10280.4,1685.5C10302,1634.72 10312.9,1571.43 10312.9,1495.65C10312.9,1419.09 10302,1355.22 10280.4,1304.05C10269.5,1279.05 10256.6,1259.13 10241.5,1244.29C10226.5,1229.44 10209.5,1222.02 10190.6,1222.02C10171.4,1222.02 10154.2,1229.44 10139.1,1244.29C10124.1,1259.13 10111.3,1279.05 10100.9,1304.05C10090.1,1329.05 10081.8,1358.06 10076.2,1391.06C10070.6,1424.07 10067.8,1458.93 10067.8,1495.65C10067.8,1531.98 10070.6,1566.55 10076.2,1599.37C10081.8,1632.18 10090.1,1660.89 10100.9,1685.5C10111.3,1710.5 10124.1,1730.32 10139.1,1744.97C10154.2,1759.62 10171.4,1766.94 10190.6,1766.94Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M11680.5,2098C11591.8,2098 11505.8,2096.73 11422.7,2094.19C11339.6,2091.65 11261.9,2085.5 11189.7,2075.73C11166.4,2072.61 11144.8,2069.09 11124.9,2065.18C11105,2061.28 11086.5,2056.79 11069.2,2051.71C11035.1,2041.55 11008.3,2029.35 10988.8,2015.09C10969.3,2000.83 10959.6,1983.54 10959.6,1963.23C10959.6,1947.22 10967.4,1932.86 10983.1,1920.16C10998.7,1907.47 11020,1896.43 11046.9,1887.06C11073.4,1877.68 11104.1,1869.58 11139.1,1862.74C11174,1855.91 11210.7,1850.34 11249.3,1846.04C11216.4,1832.37 11189.8,1815.87 11169.5,1796.53C11149.2,1777.2 11139.1,1755.22 11139.1,1730.62C11139.1,1713.43 11144.3,1697.51 11154.7,1682.86C11165.2,1668.21 11179.4,1654.83 11197.5,1642.72C11233.2,1618.51 11279.6,1600.34 11336.6,1588.23C11278.4,1578.86 11227.2,1565.77 11183,1548.97C11138.9,1532.18 11104.2,1511.18 11079.1,1485.99C11054.1,1460.79 11041.5,1431.01 11041.5,1396.63C11041.5,1355.62 11059.5,1319.97 11095.4,1289.7C11131.3,1259.42 11179,1235.11 11238.4,1216.75C11297.5,1198.39 11365.3,1184.72 11442,1175.73C11518.7,1166.75 11599.2,1162.26 11683.5,1162.26C11753.4,1162.26 11820.9,1165.28 11886.2,1171.34C11951.4,1177.39 12011.7,1187.06 12067.1,1200.34C12080.8,1169.48 12099,1145.46 12121.9,1128.27C12144.8,1111.08 12170.6,1098.68 12199.3,1091.06C12228,1083.45 12257.7,1078.76 12288.5,1077C12319.2,1075.24 12349.2,1074.37 12378.5,1074.37C12397.4,1074.37 12418.1,1074.56 12440.8,1074.95C12463.5,1075.34 12488.3,1076.32 12515.2,1077.88C12512.8,1088.82 12510.6,1103.86 12508.6,1123C12506.6,1142.14 12501.5,1159.13 12493.5,1173.97C12484.7,1190.38 12467.6,1201.71 12442.3,1207.96C12417,1214.21 12393.1,1217.33 12370.7,1217.33L12230.9,1217.33C12215.7,1217.33 12200.9,1217.63 12186.7,1218.21C12172.4,1218.8 12159.1,1220.46 12146.6,1223.19C12200.4,1241.55 12243.7,1265.09 12276.4,1293.8C12309.1,1322.51 12325.5,1356.79 12325.5,1396.63C12325.5,1438.04 12307.6,1472.7 12271.9,1500.63C12236.2,1528.56 12188.6,1550.54 12129.2,1566.55C12069.3,1582.57 12001.4,1594.09 11925.3,1601.12C11849.2,1608.15 11768.6,1611.67 11683.5,1611.67C11638.5,1611.67 11594.4,1610.79 11551,1609.03C11507.6,1607.28 11465.7,1604.25 11425.1,1599.95L11425.7,1602.88C11413.7,1602.88 11402.2,1606.4 11391.4,1613.43C11380.6,1620.46 11375.1,1629.25 11375.1,1639.79C11375.1,1649.17 11380.5,1657.18 11391.1,1663.82C11401.7,1670.46 11415.7,1675.73 11433,1679.64C11450.6,1683.54 11470.8,1686.38 11493.5,1688.13C11516.2,1689.89 11540,1690.77 11564.9,1690.77L11884,1690.77C11957.1,1690.77 12026.9,1691.06 12093.3,1691.65C12159.8,1692.24 12222.1,1697.61 12280.3,1707.76C12334.1,1716.75 12377.9,1733.25 12411.6,1757.28C12445.3,1781.3 12462.2,1815.58 12462.2,1860.11C12462.2,1897.61 12450.8,1929.44 12427.9,1955.62C12405,1981.79 12373.6,2003.56 12333.6,2020.95C12293.7,2038.33 12247.8,2052.29 12196,2062.84C12145,2073 12090.1,2080.62 12031.3,2085.69C11972.5,2090.77 11913.1,2094.09 11853,2095.65C11793,2097.22 11735.5,2098 11680.5,2098ZM11682.9,1547.22C11712.2,1547.22 11735.9,1539.79 11754,1524.95C11772,1510.11 11785.2,1490.58 11793.4,1466.36C11801.6,1442.14 11805.8,1415.77 11805.8,1387.26C11805.8,1341.94 11796.3,1303.76 11777.4,1272.7C11758.6,1241.65 11727.1,1226.12 11682.9,1226.12C11639.1,1226.12 11607.9,1241.65 11589.2,1272.7C11570.6,1303.76 11561.2,1341.94 11561.2,1387.26C11561.2,1415.38 11565.4,1441.65 11573.6,1466.06C11581.8,1490.48 11594.9,1510.11 11612.7,1524.95C11630.6,1539.79 11654,1547.22 11682.9,1547.22ZM11708.2,2035.3C11747.1,2035.3 11786.1,2034.62 11825,2033.25C11864,2031.88 11899.5,2028.66 11931.6,2023.58C11964.1,2018.9 11990.8,2011.87 12011.7,2002.49C12032.6,1993.12 12043,1980.62 12043,1964.99C12043,1947.02 12029.1,1933.25 12001.2,1923.68C11973.3,1914.11 11935.4,1906.98 11887.7,1902.29C11839.5,1897.61 11782.4,1894.78 11716.3,1893.8C11650.3,1892.82 11579.1,1892.33 11502.8,1892.33C11490.8,1892.33 11478.6,1891.94 11466.4,1891.16C11454.1,1890.38 11442,1889.4 11430,1888.23C11404.3,1905.81 11391.4,1929.44 11391.4,1959.13C11391.4,1974.76 11398.9,1987.55 11414,1997.51C11429,2007.47 11450.4,2015.18 11478.1,2020.65C11505.8,2026.12 11539.2,2029.93 11578.1,2032.08C11617.1,2034.23 11660.4,2035.3 11708.2,2035.3Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,67 @@
|
||||
# Copyright © 2026 Olaf Kolkman
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
SHELL := /bin/sh
|
||||
|
||||
SOURCE_LOGO := LinkLog.svg
|
||||
MAGICK ?= magick
|
||||
WEB_LOGO := frontend/static/logo.svg
|
||||
EXTENSION_LOGO := webextension/logo.svg
|
||||
ICON_FILES := webextension/icon-16.png webextension/icon-32.png webextension/icon-48.png webextension/icon-96.png
|
||||
GENERATED_LOGOS := $(WEB_LOGO) $(EXTENSION_LOGO) $(ICON_FILES)
|
||||
EXTENSION_VERSION := $(shell sed -n 's/^[[:space:]]*"version":[[:space:]]*"\([^"]*\)".*/\1/p' webextension/manifest.json | head -n 1)
|
||||
XPI_FILE := LinkLog-$(EXTENSION_VERSION).xpi
|
||||
XPI_UNSIGNED_DIR := XPI/unsigned
|
||||
XPI_SIGNED_DIR := XPI/signed
|
||||
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_SOURCES := $(addprefix webextension/,$(EXTENSION_FILES))
|
||||
XPI_VALIDATOR := scripts/release/validate_xpi.py
|
||||
|
||||
.PHONY: all logos xpi check-tools clean-generated
|
||||
|
||||
all: logos
|
||||
|
||||
|
||||
logos: check-tools $(GENERATED_LOGOS)
|
||||
|
||||
|
||||
xpi: $(XPI_OUTPUT)
|
||||
|
||||
$(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; }
|
||||
@mkdir -p $(XPI_UNSIGNED_DIR) $(XPI_SIGNED_DIR)
|
||||
@rm -f $(XPI_OUTPUT)
|
||||
@cd webextension && zip -q -9 "../$(XPI_OUTPUT)" $(EXTENSION_FILES)
|
||||
@python3 scripts/release/validate_xpi.py "$(XPI_OUTPUT)" webextension/manifest.json
|
||||
@echo "Created $(XPI_OUTPUT)"
|
||||
|
||||
check-tools:
|
||||
@command -v $(MAGICK) >/dev/null 2>&1 || { echo "Error: ImageMagick '$(MAGICK)' is required. Install ImageMagick and retry." >&2; exit 1; }
|
||||
|
||||
$(WEB_LOGO): $(SOURCE_LOGO)
|
||||
@mkdir -p $(@D)
|
||||
@cp $< $@
|
||||
|
||||
$(EXTENSION_LOGO): $(SOURCE_LOGO)
|
||||
@mkdir -p $(@D)
|
||||
@cp $< $@
|
||||
|
||||
webextension/icon-16.png: $(SOURCE_LOGO)
|
||||
@mkdir -p $(@D)
|
||||
@$(MAGICK) $< -resize 16x16 -gravity center -extent 16x16 $@
|
||||
|
||||
webextension/icon-32.png: $(SOURCE_LOGO)
|
||||
@mkdir -p $(@D)
|
||||
@$(MAGICK) $< -resize 32x32 -gravity center -extent 32x32 $@
|
||||
|
||||
webextension/icon-48.png: $(SOURCE_LOGO)
|
||||
@mkdir -p $(@D)
|
||||
@$(MAGICK) $< -resize 48x48 -gravity center -extent 48x48 $@
|
||||
|
||||
webextension/icon-96.png: $(SOURCE_LOGO)
|
||||
@mkdir -p $(@D)
|
||||
@$(MAGICK) $< -resize 96x96 -gravity center -extent 96x96 $@
|
||||
|
||||
clean-generated:
|
||||
@rm -f $(GENERATED_LOGOS)
|
||||
@@ -2,14 +2,18 @@
|
||||
|
||||
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.
|
||||
|
||||
For full transparency: The author used vibe coding to create this software.
|
||||
|
||||
## Project Layout
|
||||
|
||||
```text
|
||||
backend/ FastAPI application, services, database, and tests
|
||||
frontend/ Jinja templates and browser-side assets
|
||||
webextension/ Firefox Manifest V3 extension
|
||||
Logo.svg Source logo artwork used by the web and extension interfaces
|
||||
Dockerfile Backend container image
|
||||
docker-compose.yml App plus Traefik for local proxying
|
||||
docker-compose.yml Production app with Traefik reverse proxy hooks
|
||||
docker-compose.local.yml Local development app with direct port access
|
||||
REQUIREMENTS.md Product requirements
|
||||
VIBE/ Conversation and prompt logs
|
||||
```
|
||||
@@ -24,6 +28,8 @@ For local development:
|
||||
|
||||
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.
|
||||
The backend version is `0.1.0` and is exposed through the FastAPI/OpenAPI metadata. It can be overridden with `LINKLOG_VERSION`.
|
||||
LinkLog is licensed under the GNU General Public License, version 3 or any later version. See [LICENSE](LICENSE).
|
||||
|
||||
## Local Installation
|
||||
|
||||
@@ -42,17 +48,7 @@ On Windows PowerShell, activate the environment with:
|
||||
.venv\Scripts\Activate.ps1
|
||||
```
|
||||
|
||||
The SQLite database is created automatically at `backend/data/linklog.db` when the application starts or when the auth router is imported. The starter accounts are:
|
||||
|
||||
|
||||
|
||||
| Username | Password | Role |
|
||||
| --- | --- | --- |
|
||||
| `alice` | `secret123` | administrator |
|
||||
| `bob` | `secret123` | standard user |
|
||||
|
||||
|
||||
These credentials are for development only. Change the authentication and seeding design before deploying publicly.
|
||||
The 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.
|
||||
## Run The Backend
|
||||
@@ -70,20 +66,73 @@ Open these URLs:
|
||||
- User feed: <http://localhost:8000/alice>
|
||||
- Profile settings: <http://localhost:8000/profile>
|
||||
- Labels: <http://localhost:8000/labels>
|
||||
- About: <http://localhost:8000/about>
|
||||
- Admin page: <http://localhost:8000/admin>
|
||||
- Web login: <http://localhost:8000/login>
|
||||
- Token refresh: `POST http://localhost:8000/api/auth/refresh`
|
||||
- Health check: <http://localhost:8000/health>
|
||||
- OpenAPI documentation: <http://localhost:8000/docs>
|
||||
|
||||
The browser extension defaults to `http://localhost:8000`.
|
||||
The browser extension requires a backend URL to be entered during setup; it does not assume a default server.
|
||||
|
||||
The supplied `Logo.svg` is bundled as `frontend/static/logo.svg` for web pages and `webextension/logo.svg` for the Firefox popup and settings page.
|
||||
The visible LinkLog brand text uses the Google Foundry `Asset` font when available, with local fallbacks in the Firefox extension.
|
||||
|
||||
## Regenerate Logo Assets
|
||||
|
||||
`LinkLog.svg` is the source logo. Install ImageMagick, then regenerate the web logo, extension logo, and Firefox toolbar icons with:
|
||||
|
||||
```sh
|
||||
make logos
|
||||
```
|
||||
|
||||
The generated files are `frontend/static/logo.svg`, `webextension/logo.svg`, and `webextension/icon-16.png`, `icon-32.png`, `icon-48.png`, and `icon-96.png`. Override the ImageMagick executable with `make MAGICK=magick logos` when needed.
|
||||
|
||||
Create an installable Firefox XPI bundle with:
|
||||
|
||||
```sh
|
||||
make xpi
|
||||
```
|
||||
|
||||
This creates `XPI/unsigned/LinkLog-0.1.0.xpi` from the `webextension/` package and excludes macOS metadata and minified artifacts. The version is read from `webextension/manifest.json`. The `XPI/signed/` directory is reserved for signed release bundles.
|
||||
|
||||
## Docker Deployment
|
||||
|
||||
The main `docker-compose.yml` is the production deployment. It does not publish port 8000 on the host; the application is reachable through Traefik on the external `linklog_traefik` network. Set `LINKLOG_PUBLIC_URL` to the DNS hostname served by Traefik. The default is the documentation hostname `linklog.example.com`, which must be replaced for a real deployment.
|
||||
|
||||
For local development with direct access, use the separate file:
|
||||
|
||||
```sh
|
||||
docker compose -f docker-compose.local.yml up --build
|
||||
```
|
||||
|
||||
This publishes `${APP_PORT:-8000}` and defaults the application URL to `http://localhost:8000`. Do not use the local file for an Internet-facing deployment.
|
||||
|
||||
## Releases
|
||||
|
||||
Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `LINKLOG_VERSION`'s default in `backend/app/core/config.py`; the tag must match that backend version. The Firefox plugin version is independent and comes from the most recent signed `XPI/signed/LinkLog-<version>.xpi` checked into the repository.
|
||||
|
||||
The signed XPI is produced manually and should be checked into `XPI/signed/LinkLog-<version>.xpi`. The workflow validates the latest signed XPI's embedded manifest, publishes Docker images to `git.kolkman.org/olaf/link-log:<backend-version>` and `:latest`, and creates a release README that describes the project, the current backend/container version, and the raw signed XPI download URL with the plugin version.
|
||||
|
||||
The extension's `update_url` points at the stable raw repository URL `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json`. Update `webextension/updates.json` with each signed XPI version and commit it together with the XPI. 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.
|
||||
|
||||
Every push to `main` also runs `.gitea/workflows/development.yml` and publishes the current Docker image as `git.kolkman.org/olaf/link-log:development`. The workflow uses `REGISTRY_USERNAME` and the Gitea access token in `REGISTRY_TOKEN`, and can also be started manually from Gitea Actions.
|
||||
|
||||
Appending a username to the root URL, such as `/alice`, opens that user's public feed and profile information.
|
||||
|
||||
Configuration APIs require a bearer token returned by the login endpoint. User configuration uses the identity in that token. Plugin administration additionally requires an administrator account; the development `alice` account is seeded as an administrator, while `bob` is a standard user.
|
||||
Configuration APIs require a bearer token returned by the login endpoint. Send it in the `Authorization: Bearer ...` header; query-string tokens are not accepted. Users authenticate with their email address; the username remains the public presentation identity used in profiles and feed URLs. User configuration uses the identity in that token. Plugin administration additionally requires an administrator account.
|
||||
|
||||
Login failures are throttled per client IP and email. Five failures within 15 minutes trigger a two-minute lockout, including invalid OTP attempts; successful authentication clears the failure counter.
|
||||
|
||||
Users can change their password from the profile page. The current password is required, new passwords must contain at least 8 characters, and the endpoint is `PUT /api/user/password`.
|
||||
|
||||
On the profile page, the authenticated username is displayed as read-only. Users can upload a PNG, JPEG, GIF, or WebP avatar up to 2 MB; uploaded files are stored in the persistent data volume and served by the application. Bio and email fields remain empty until the user provides values. Mastodon settings default to the `mastodon.social` instance and the `From my #LinkLog: "` post prefix.
|
||||
Users can configure a time-based one-time password from the profile page using an authenticator app. The profile displays a provisioning secret and authenticator URI during setup, then requires a current six-digit code to enable or disable OTP. When OTP is enabled, both the web login and Firefox extension settings login require the code. The TOTP secret is never returned by the profile API after setup.
|
||||
|
||||
Users can add up to five additional email addresses from the profile page. Each additional address must be validated through a verification email before it can be used for authentication. A verified alternative can be promoted to primary; the previous primary remains as a verified alternative. The profile displays validation status and offers resend controls subject to the same 20-second interval, five-send limit, and two-minute cooldown used during initial setup.
|
||||
|
||||
On the profile page, the authenticated username is displayed as read-only. Users can upload a PNG, JPEG, GIF, or WebP avatar up to 2 MB; uploaded files are stored in the persistent data volume and served by the application. Bio and email fields remain empty until the user provides values. Mastodon settings default to the `mastodon.social` instance and the `From my #LinkLog: ` post prefix.
|
||||
|
||||
## Run Tests
|
||||
|
||||
@@ -101,21 +150,26 @@ PYTHONPATH=. PYTHONWARNINGS=error pytest backend/tests -q
|
||||
## Install The Firefox Extension For Development
|
||||
|
||||
The extension is an unpacked Firefox extension. No build step is required.
|
||||
The toolbar uses square PNG icons generated from the bundled dark-background logo; `logo.svg` remains available for the popup and settings branding.
|
||||
The manifest includes stable Firefox extension metadata and references the packaged PNG icons for toolbar and add-on installation.
|
||||
|
||||
1. Start the backend locally.
|
||||
2. Open Firefox and visit `about:debugging#/runtime/this-firefox`.
|
||||
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:
|
||||
- Backend URL: `http://localhost:8000`
|
||||
- Username: `alice`
|
||||
- Backend URL: the URL of your LinkLog server, such as `http://localhost:8000`
|
||||
- Email: `alice@example.com`
|
||||
- Password: `secret123`
|
||||
- One-time password: enter it when OTP is enabled
|
||||
6. Save the settings and login.
|
||||
7. Open a webpage, select the LinkLog toolbar button, review the title and URL, add a comment, and submit it.
|
||||
|
||||
When the extension settings page has a valid session, it shows `<username> logged in at <backend URL>` and a **Sign out** button instead of the login form. Access and refresh credentials are kept in Firefox session storage, so a browser restart requires login again. Signing out revokes the token family and returns the form.
|
||||
|
||||
Temporary extensions are removed when Firefox restarts. Reload the extension from `about:debugging` after changing its files.
|
||||
|
||||
## Docker And Traefik
|
||||
## Docker
|
||||
|
||||
Create the Docker environment file before starting the stack:
|
||||
|
||||
@@ -125,24 +179,40 @@ 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.
|
||||
|
||||
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:
|
||||
|
||||
| Variable | Purpose | Default |
|
||||
| --- | --- | --- |
|
||||
| `LINKLOG_SECRET_KEY` | token signing/security secret | required in Docker |
|
||||
| `LINKLOG_DATA_ENCRYPTION_KEY` | Fernet key for encrypting SMTP, Mastodon, and OTP secrets at rest | required in Docker |
|
||||
| `LINKLOG_DATABASE_PATH` | SQLite file path inside the container | `/app/backend/data/linklog.db` |
|
||||
| `LINKLOG_TOKEN_EXPIRY_DAYS` | access-token lifetime | `30` |
|
||||
| `LINKLOG_TRACKING_PARAMS` | comma-separated tracking parameters | built-in list |
|
||||
| `TRAEFIK_HOST` | hostname routed by Traefik | `localhost` |
|
||||
| `TRAEFIK_HTTP_PORT` | host port for the application proxy | `80` |
|
||||
| `TRAEFIK_DASHBOARD_PORT` | host port for the dashboard | `8080` |
|
||||
| `TRAEFIK_DASHBOARD_BIND_ADDRESS` | host address for the dashboard | `127.0.0.1` |
|
||||
| `TRAEFIK_API_INSECURE` | enable the local dashboard API | `true` |
|
||||
| `LINKLOG_TOKEN_EXPIRY_MINUTES` | access-token lifetime | `15` |
|
||||
| `LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS` | refresh-token lifetime | `30` |
|
||||
| `LINKLOG_PUBLIC_URL` | Public hostname used by Traefik and expanded to a callback URL by the backend | `linklog.example.com` |
|
||||
| `LINKLOG_SMTP_HOST` | SMTP server hostname; empty disables delivery in local development | empty |
|
||||
| `LINKLOG_SMTP_PORT` | SMTP server port | `587` |
|
||||
| `LINKLOG_SMTP_USERNAME` | SMTP login username | empty |
|
||||
| `LINKLOG_SMTP_PASSWORD` | SMTP login password | empty |
|
||||
| `LINKLOG_SMTP_FROM` | Sender address for verification mail | `LinkLog <no-reply@localhost>` |
|
||||
| `LINKLOG_SMTP_USE_TLS` | Use STARTTLS for SMTP | `true` |
|
||||
| `LINKLOG_EMAIL_VERIFICATION_EXPIRY_HOURS` | Verification-link lifetime | `24` |
|
||||
| `LINKLOG_PASSWORD_RESET_EXPIRY_HOURS` | Password-reset-link lifetime | `1` |
|
||||
| `LINKLOG_TRACKING_PARAMS` | comma-separated tracking parameters (stripped from logged URLs) | built-in list |
|
||||
| `APP_PORT` | direct host port for FastAPI | `8000` |
|
||||
|
||||
New users created by an administrator are email-unverified and cannot sign in until they follow the verification link sent to their address. The link is valid for `LINKLOG_EMAIL_VERIFICATION_EXPIRY_HOURS` hours and is handled by `/api/auth/verify-email`. Configure `LINKLOG_SMTP_HOST`, `LINKLOG_SMTP_FROM`, and the SMTP credentials for delivery; local development may leave the SMTP host empty, in which case accounts remain pending verification and no message is sent.
|
||||
|
||||
On a fresh installation, the setup form is prefilled from the `LINKLOG_SMTP_*` environment values when available. After saving, the values stored in the database are used for subsequent setup-page loads and mail delivery.
|
||||
|
||||
When a verified user enters the wrong password, LinkLog keeps the response generic and sends a password-reset link to that account's email address when SMTP is configured. Reset links expire after `LINKLOG_PASSWORD_RESET_EXPIRY_HOURS` hours, can be used once, and revoke existing sessions after the password is changed.
|
||||
|
||||
The full set of supported variables is listed in `.env.example`. Application variables are passed into the container by Compose; Docker and Traefik variables are used by Compose itself.
|
||||
|
||||
Build and start the application and local Traefik proxy:
|
||||
`LINKLOG_DATA_ENCRYPTION_KEY` must be a Fernet key kept outside the database. Generate one with a Python environment that has `cryptography` installed, for example `python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"`, then store it in `.env` or a protected deployment secret. Losing this key makes encrypted SMTP, Mastodon, and OTP values unrecoverable. Existing plaintext values from earlier versions should be rotated by saving them again after configuring the key.
|
||||
|
||||
Build and start the application:
|
||||
|
||||
```sh
|
||||
docker compose up --build
|
||||
@@ -150,12 +220,11 @@ docker compose up --build
|
||||
|
||||
The services are available at:
|
||||
|
||||
- LinkLog through Traefik: <http://example.com/>
|
||||
- Direct application port: <http://localhost:8000/>
|
||||
|
||||
|
||||
The Compose configuration routes the hostname `localhost` through Traefik. The SQLite database is stored in the named Docker volume `linklog_data`, mounted at `/app/backend/data`.
|
||||
The application runs as a non-root user and reports container health through `/health`; Traefik waits for the application health check before starting.
|
||||
The SQLite database is stored in the named Docker volume `linklog_data`, mounted at `/app/backend/data`.
|
||||
The application runs as a non-root user and reports container health through `/health`;
|
||||
|
||||
Stop the stack without deleting its database:
|
||||
|
||||
@@ -169,15 +238,20 @@ Stop the stack and delete the named database volume:
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
For a real deployment, replace the `localhost` router rule, configure TLS, protect the Traefik dashboard, avoid exposing the direct application port, and provide production secrets and authentication. The included Compose file is a local/prototype deployment scaffold, not a production security configuration.
|
||||
For a real deployment, start with the docker-compose-example.yaml file. replace the router rule, configure TLS, protect the Traefik dashboard, avoid exposing the direct application port, and provide production secrets and authentication. The included Compose file is a local/prototype deployment scaffold, not a production security configuration.
|
||||
|
||||
## Mastodon Configuration
|
||||
|
||||
After logging in, open <http://localhost:8000/profile> and save the Mastodon settings:
|
||||
After logging in, open <http://localhost:8000/profile>, enter the Mastodon instance, and select **Connect Mastodon**. LinkLog registers an OAuth application on that instance, opens Mastodon authorization, and stores the returned per-user access token after the callback. The requested scopes are `read:accounts` and `write:statuses`. Posts use the configured prefix followed directly by the title, an optional comment, a `from: URL` line when a title exists, and tags on the final line, with blank lines between sections.
|
||||
|
||||
- **Instance**: hostname or URL such as `mastodon.social` or `https://mastodon.social`
|
||||
- **Access token**: a Mastodon API token with permission to create statuses
|
||||
- **Post prefix**: text placed immediately before the link; defaults to `From my #LinkLog: "`
|
||||
- **Post prefix**: text placed immediately before the link; defaults to `From my #LinkLog: `
|
||||
|
||||
`LINKLOG_PUBLIC_URL` is the public hostname used by Traefik and the backend. Use `localhost` for local development or a hostname such as `linklog.kolkman.org` for a deployment. The backend adds `http://` for localhost and `https://` for other hostnames when constructing OAuth and email links. Existing manually entered access tokens remain compatible with the plugin configuration API.
|
||||
|
||||
LinkLog caches the OAuth application credentials per Mastodon server in the persistent SQLite `app_settings` table, so subsequent connections do not register a new application on every attempt. If the server rate-limits application registration, the profile page reports the upstream `429` response and the user can retry after the server's cooldown.
|
||||
|
||||
Mastodon instances must be HTTPS hostname-only URLs that resolve to public IP addresses. Loopback, private, link-local, multicast, unspecified, reserved, and IPv4-mapped IPv6 destinations are rejected, and outbound redirects are refused.
|
||||
|
||||
Enable the plugin from the admin API or the admin page. New links are saved first and then posted to the configured instance at `/api/v1/statuses`. A Mastodon network failure does not undo the saved link.
|
||||
|
||||
@@ -188,7 +262,26 @@ Login:
|
||||
```sh
|
||||
curl -X POST http://localhost:8000/api/auth/login \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{"username":"alice","password":"secret123"}'
|
||||
-d '{"email":"alice@example.com","password":"secret123"}'
|
||||
```
|
||||
|
||||
The login response contains a 15-minute access token, a device-bound refresh token, its expiry time, and a `device_id`. Each successful refresh rotates the refresh token.
|
||||
|
||||
Refresh an access token:
|
||||
|
||||
```sh
|
||||
curl -X POST http://localhost:8000/api/auth/refresh \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{"refresh_token":"YOUR_REFRESH_TOKEN","device_id":"YOUR_DEVICE_ID"}'
|
||||
```
|
||||
|
||||
Refresh-token reuse or a mismatched device ID returns `401` and revokes the token family. Signing out revokes the token family, while changing the password or completing a password reset revokes all sessions for the user.
|
||||
|
||||
Sign out with the access token in the bearer header:
|
||||
|
||||
```sh
|
||||
curl -X POST http://localhost:8000/api/auth/logout \\
|
||||
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
|
||||
```
|
||||
|
||||
Submit a link using the returned access token:
|
||||
@@ -214,6 +307,8 @@ The inline link editor also allows multiple existing tags to be selected and new
|
||||
The installation seeds these available tags: `#Internet`, `#Cybersecurity`, `#Fediverse`, `#Food`, `#Photography`, `#Music`, and `#AI`.
|
||||
Users can create, edit, and delete their own labels from `/labels`. Administrators can delete any label from `/admin`; system-seeded labels have no user owner.
|
||||
|
||||
Administrators can enable one or more backend themes from `/admin`: Plain Day, Plain Night, Catppuccin Latte, Catppuccin Frappe, Catppuccin Macchiato, Catppuccin Mocha, Dracula, Nord, and Solarized. Visitors can choose among enabled themes; their choice is stored locally in the browser. At least one theme must remain enabled.
|
||||
|
||||
Admin plugin requests must include the administrator's token:
|
||||
|
||||
```sh
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
# LinkLog Security Audit
|
||||
|
||||
**Assessment date:** 2026-08-26
|
||||
**Scope:** Current LinkLog backend, web frontend, Firefox extension, SQLite persistence, SMTP and Mastodon integrations, Docker/Traefik deployment files, and automated tests.
|
||||
**Assessment type:** Source-code review. This is not a penetration test, dependency scan, container scan, formal threat-model sign-off, or production configuration certification.
|
||||
|
||||
## Executive Summary
|
||||
|
||||
The current worktree contains strong security improvements: salted scrypt password hashing with legacy upgrade support, bearer-header authentication, hashed and expiring tokens, refresh-token rotation with device binding and family revocation, OTP recovery codes, encrypted newly written secrets, Mastodon SSRF controls, image decoding and re-encoding, reduced extension permissions, proxy-only production Compose, and append-only audit events.
|
||||
|
||||
The following issues remain before an Internet-facing production release:
|
||||
|
||||
1. Logout still accepts a bearer token in a JSON body rather than using the standard `Authorization` header.
|
||||
2. SMTP, Mastodon, setup, and some user-service errors return raw exception details to clients.
|
||||
3. First-run setup is intentionally unauthenticated and lacks a bootstrap secret and application-level request-size controls.
|
||||
4. Audit event details are serialized without defensive sanitization or size limits at the audit-service boundary.
|
||||
5. The development secret fallback is not rejected at application startup in production.
|
||||
6. Rate limiting is single-instance SQLite state, is not atomic under concurrency, and reset-mail issuance is not independently throttled.
|
||||
7. Runtime verification, security headers, centralized audit export, retention, alerting, and dependency/container/security scanning remain incomplete.
|
||||
|
||||
The application should remain behind the production reverse proxy, with real DNS/TLS, protected secrets, and restricted network access until these items are addressed.
|
||||
|
||||
## Verified Controls
|
||||
|
||||
- Passwords use salted scrypt hashes; valid legacy SHA-256 hashes are upgraded on login.
|
||||
- Bearer authentication is centralized through `get_current_user` and `require_admin`.
|
||||
- Query-string authentication is not accepted by protected session endpoints.
|
||||
- Access tokens are short-lived by default; refresh tokens are hashed, separately expiring, device-bound, rotated, and family-revoked on reuse.
|
||||
- Logout, password changes, and password resets revoke session material according to the token lifecycle.
|
||||
- OTP enrollment provides ten one-time recovery codes; only hashes are stored.
|
||||
- Users can recover OTP with password plus a recovery code, and administrators can disable OTP for another user.
|
||||
- Newly written SMTP, Mastodon, OAuth, and OTP secrets are encrypted with an external Fernet key.
|
||||
- Mastodon instances are restricted to HTTPS public hostnames, unsafe resolved addresses are rejected, and redirects are blocked.
|
||||
- Avatar uploads are size-limited, decoded with Pillow, pixel-limited, fully loaded, and re-encoded as server-generated PNG.
|
||||
- Production Compose does not publish the application port and uses the external Traefik network; local direct access is separate.
|
||||
- The Firefox extension uses `activeTab`, session-scoped credentials, exact configured backend permissions, and a self-only extension-page CSP.
|
||||
- SQLite queries are parameterized and foreign-key enforcement is enabled.
|
||||
- An append-only `security_audit_events` table records actor, action, target, outcome, and details for major administrative and destructive operations.
|
||||
- The current automated backend suite passes 49 tests.
|
||||
|
||||
## Findings
|
||||
|
||||
### SA-001: Logout uses non-standard token transport
|
||||
|
||||
**Severity:** High, remediated in current worktree
|
||||
**Evidence before remediation:** `POST /api/auth/logout` accepted `{"token": ...}` in the JSON request body, and the web frontend sent the access token this way.
|
||||
**Impact:** Request bodies may be captured by debugging middleware, application logs, or monitoring systems. The endpoint also diverges from the bearer-header contract used elsewhere, increasing the chance of inconsistent token handling.
|
||||
|
||||
**Current state:** Logout requires `Authorization: Bearer <access-token>`, rejects body-only tokens with `401`, and revokes the token family server-side. The web frontend and Firefox extension send the header; regression coverage verifies access and refresh tokens are invalid after logout.
|
||||
|
||||
**Recommendation:** Keep logout header-only, retain family revocation, avoid logging authorization headers, and rotate legacy sessions issued before this change.
|
||||
|
||||
**Priority:** Completed in code; legacy session rotation and log hygiene remain.
|
||||
|
||||
### SA-002: Raw infrastructure errors are returned to clients
|
||||
|
||||
**Severity:** High, remediated in current worktree
|
||||
**Evidence before remediation:** SMTP and Mastodon routes interpolated exception text into `503`/`502` responses. Setup and email-address routes also exposed mail-delivery exception text.
|
||||
**Impact:** Error responses can disclose SMTP hostnames, ports, TLS/library details, upstream response bodies, internal network information, or sensitive URL fragments.
|
||||
|
||||
**Current state:** The application assigns a request ID at middleware entry, returns it in `X-Request-ID`, logs technical exception summaries server-side after redacting authorization values, tokens, passwords, secrets, OTP/code values, and secret-bearing URL query values, and returns stable public messages with a reference ID. SMTP setup/admin/email errors and Mastodon registration/callback errors no longer expose raw exception text. Regression tests verify representative exception and secret text is absent from HTTP responses.
|
||||
|
||||
**Residual impact:** Logging currently uses the application logger rather than a centralized protected sink. Request-ID trust, log retention, access control, and structured redaction should be reviewed in deployment.
|
||||
|
||||
**Recommendation:** Keep public errors stable and reference-based, export redacted logs to a protected centralized system, define retention and access controls, and never log authorization headers or secret-bearing request data.
|
||||
|
||||
**Priority:** Completed in code; centralized logging and operational controls remain.
|
||||
|
||||
### SA-003: First-run setup is unauthenticated and lacks application-level body limits
|
||||
|
||||
**Severity:** Medium/High for exposed fresh deployments
|
||||
**Evidence:** `/api/setup/configuration`, `/api/setup/test-mail`, `/api/setup/complete`, and `/api/setup/status` are available before an administrator exists. No global request-size middleware or bootstrap secret is enforced in the application.
|
||||
|
||||
**Impact:** Anyone who can reach a fresh instance can overwrite pending setup values, attempt SMTP delivery, consume test-mail quota, and submit oversized request bodies. The setup design is necessary for provisioning but is unsafe when directly exposed.
|
||||
|
||||
**Recommendation:** Require a one-time bootstrap secret supplied through the environment or console, or restrict setup to localhost/private management networking. Add bounded request models and a global body-size limit. Keep strict setup/test-mail throttling, audit setup actions, expire pending setup data, and disable setup routes after provisioning.
|
||||
|
||||
**Priority:** High for Internet-facing fresh installations.
|
||||
|
||||
### SA-004: Audit details are not sanitized at the audit-service boundary
|
||||
|
||||
**Severity:** Medium
|
||||
**Evidence:** `record_audit_event()` serializes caller-supplied `details` directly to SQLite. Current callers generally avoid secrets, but the service does not enforce that contract or bound nested values and event size.
|
||||
|
||||
**Impact:** A future caller could persist passwords, tokens, OTP codes, SMTP credentials, sensitive URLs, or oversized data in the audit database. Audit records are durable and are not a suitable place for arbitrary request payloads.
|
||||
|
||||
**Recommendation:** Use an allow-list of permitted detail fields per action, or recursively redact sensitive key names and URL query values. Bound string lengths and serialized event size. Add direct service tests with nested `password`, `token`, `secret`, and URL values and assert that they are redacted or rejected.
|
||||
|
||||
**Priority:** Medium.
|
||||
|
||||
### SA-005: Production secret fallback is not fail-closed
|
||||
|
||||
**Severity:** Medium, remediated in current worktree
|
||||
**Evidence before remediation:** `Settings.secret_key` defaulted to `dev-secret-key-change-me`, and `LINKLOG_DATA_ENCRYPTION_KEY` was validated when encryption was used rather than fully validated during startup.
|
||||
|
||||
**Impact:** A deployment that omits required configuration can start with a known development secret or fail only when a protected feature is exercised. This creates dangerous configuration drift and complicates incident response.
|
||||
|
||||
**Current state:** `validate_configuration()` runs before FastAPI app construction. In production it rejects a missing or known development `LINKLOG_SECRET_KEY`, application secrets shorter than 32 characters or with insufficient character diversity, and missing `LINKLOG_DATA_ENCRYPTION_KEY`. Any supplied encryption key is checked as a valid Fernet key. Focused tests cover rejection and acceptance paths.
|
||||
|
||||
**Residual impact:** Secret strength checks are pragmatic length/diversity checks rather than a full entropy estimator. Secret provisioning, rotation, and protected storage remain operational requirements.
|
||||
|
||||
**Recommendation:** Keep production startup fail-closed, provision secrets through a protected secret manager, rotate them after suspected disclosure, and consider a stronger entropy policy if deployment requirements warrant it.
|
||||
|
||||
**Priority:** Completed in code; secret provisioning and rotation remain.
|
||||
|
||||
### SA-006: Login and reset-mail throttling are not distributed or atomic
|
||||
|
||||
**Severity:** Medium/High in multi-instance deployments
|
||||
**Evidence:** Login failure state is stored in SQLite and keyed by a client-IP/email hash. The check and increment occur as separate operations. Failed login handling can also issue a password-reset email for a known verified account without an independent reset-mail cooldown.
|
||||
|
||||
**Impact:** Concurrent attempts can overwrite counters, multiple application instances do not share reliable rate state, and reset-mail issuance can be abused to spam a user or consume SMTP resources.
|
||||
|
||||
**Recommendation:** Use an atomic shared limiter such as Redis for multi-instance deployments, with both account and IP buckets. Add an independent per-account/IP reset-mail cooldown and monitoring. Treat trusted proxy headers explicitly when deriving client IPs. Add concurrency, proxy, OTP-failure, and reset-mail abuse tests.
|
||||
|
||||
**Priority:** Medium/High for scaled or public deployments.
|
||||
|
||||
### SA-007: Security headers and global request policy are incomplete
|
||||
|
||||
**Severity:** Medium
|
||||
**Evidence:** The application does not consistently install or test CSP, HSTS, `X-Content-Type-Options`, frame protections, `Referrer-Policy`, trusted hosts, or a global request-size limit. The extension CSP does not cover the web application.
|
||||
|
||||
**Impact:** Browser defense-in-depth and resource exhaustion protections depend on external proxy configuration. A proxy configuration mistake can leave HTML, API, or media responses weaker than intended.
|
||||
|
||||
**Recommendation:** Add a documented application or guaranteed-proxy policy and test headers on HTML, API, and media responses. Use `TrustedHostMiddleware` with explicit production hosts, `nosniff`, restrictive framing/referrer rules, HSTS only on HTTPS, and bounded request bodies.
|
||||
|
||||
**Priority:** Medium.
|
||||
|
||||
### SA-008: Audit operations lack request correlation, retention, export, and alerting
|
||||
|
||||
**Severity:** Medium
|
||||
**Evidence:** Audit events contain actor/action/target/outcome/details/time but no request ID, source context, retention policy, protected export, or alerting pipeline.
|
||||
|
||||
**Impact:** Operators can inspect database events but cannot reliably correlate them with request logs, detect attacks promptly, or guarantee retention and tamper-resistant access controls.
|
||||
|
||||
**Recommendation:** Add request IDs at middleware entry, export redacted events to protected logs or a security monitoring system, define retention and access controls, and alert on privilege changes, OTP resets, password resets, credential changes, refresh-token reuse, and destructive actions.
|
||||
|
||||
**Priority:** Medium.
|
||||
|
||||
### SA-009: Dependency, container, secret, and runtime security verification is incomplete
|
||||
|
||||
**Severity:** Medium
|
||||
**Evidence:** The repository runs functional tests and static syntax checks, but no dependency vulnerability scan, container scan, secret scan, authenticated dynamic test, or live Firefox extension workflow is part of the verified release path.
|
||||
|
||||
**Impact:** Known vulnerable dependencies, image issues, accidental secret commits, proxy misconfiguration, and browser-runtime permission failures can reach release despite passing unit tests.
|
||||
|
||||
**Recommendation:** Add CI jobs for Python dependency and license policy, container scanning, secret scanning, Compose rendering, authenticated dynamic API checks, and a Firefox smoke test covering permission grant, login, refresh, logout, and active-tab capture.
|
||||
|
||||
**Priority:** Medium before public release.
|
||||
|
||||
## Residual Operational Requirements
|
||||
|
||||
- Replace documentation hostnames with real DNS names and enforce HTTPS/TLS.
|
||||
- Keep production Compose proxy-only and verify the actual Traefik network and middleware in deployment.
|
||||
- Rotate legacy plaintext secrets and previously issued sessions after upgrades.
|
||||
- Protect and encrypt database/avatar backups; test restoration and token/session revocation.
|
||||
- Monitor failed logins, reset-mail volume, refresh-token reuse, OTP recovery, privilege changes, and destructive actions.
|
||||
- Review the Firefox extension against Mozilla Add-ons policy before signing.
|
||||
|
||||
## Verification Performed
|
||||
|
||||
- `PYTHONPATH=. pytest -q`: **49 passed** at the start of this audit.
|
||||
- Static source review of backend APIs/services, frontend assets, extension manifest/scripts, Compose files, configuration, and tests.
|
||||
- Targeted searches for authentication, token, secret, upload, outbound-request, error, and audit-log paths.
|
||||
|
||||
Functional tests demonstrate regression coverage only; they do not certify production security.
|
||||
@@ -1,5 +1,167 @@
|
||||
# Chat Log
|
||||
|
||||
### User
|
||||
The release server fails because its curl does not support `--fail-with-body`.
|
||||
|
||||
### Assistant outcome
|
||||
Replaced all three `--fail-with-body` uses in the release workflow with portable curl response capture and explicit HTTP status checks. Failed API and asset-upload responses now print their response body before exiting, while older curl versions remain supported.
|
||||
|
||||
### User
|
||||
When posting to Mastodon change the formatting so there is an empty line between “From my #LinkLog:” and the title.
|
||||
|
||||
### Assistant outcome
|
||||
Updated the Mastodon formatter so the prefix and title are separate paragraphs: `From my #LinkLog:` followed by a blank line and then the title. Existing comment, source URL, and tag paragraph formatting remains unchanged.
|
||||
|
||||
### User
|
||||
Check the modified pages for the correct link because a version number was added to the signed XPI.
|
||||
|
||||
### Assistant outcome
|
||||
Verified that the signed artifact is `XPI/signed/LinkLog-0.1.0.xpi` and that the About page, Profile page, `webextension/updates.json`, README, and related regression test all reference the matching versioned filename. No changes were required.
|
||||
|
||||
### User
|
||||
In the Profile page below the Save profile button add “If you have not downloaded the plugin yet find it here” with a link to the signed plugin.
|
||||
|
||||
### Assistant outcome
|
||||
Added the plugin download prompt immediately below the Save profile button, linking “find it here” to the signed `LinkLog-0.1.0.xpi` artifact. Added profile-page regression assertions and recorded the change in VIBE.
|
||||
|
||||
### User
|
||||
Add a Plugin section to the About page with a download link to the signed XPI file.
|
||||
|
||||
### Assistant outcome
|
||||
Added a Plugin section to the About page with a download link for the signed `LinkLog-0.1.0.xpi` artifact hosted on the repository's raw main branch. Added a page-rendering regression assertion.
|
||||
|
||||
### User
|
||||
The Firefox plugin tests report that `strict_min_version` 112 is too low for `data_collection_permissions`, `storage.session`, and `permissions.request`.
|
||||
|
||||
### Assistant outcome
|
||||
Raised the extension minimum Firefox version to 142.0, covering the reported desktop and Android manifest/API compatibility warnings. Updated the README to require Firefox 142 or newer.
|
||||
|
||||
### User
|
||||
Implement SA-005: during startup reject missing or known development `LINKLOG_SECRET_KEY` in production, validate minimum length and entropy, require and validate the encryption key, and add fail-closed configuration tests.
|
||||
|
||||
### Assistant outcome
|
||||
Added startup configuration validation before FastAPI app construction. Production now rejects missing/default/weak application secrets and missing or invalid Fernet encryption keys, while development defaults remain available. Added configuration tests for rejection and valid production settings, and updated SA-005 documentation.
|
||||
|
||||
### User
|
||||
For SA-002, log technical details server-side with a request/correlation ID, return a stable public message with a short reference ID, redact secrets, and test that exception text is absent from responses.
|
||||
|
||||
### Assistant outcome
|
||||
Added request-ID middleware and stable public error references. SMTP, setup, email-verification, and Mastodon exception paths now log redacted technical summaries server-side without exposing raw exception text, credentials, authorization values, reset tokens, OTP data, or secret-bearing URL values. Added regression coverage and updated SA-002 documentation.
|
||||
|
||||
### User
|
||||
Remedy SA-001: Logout uses non-standard token transport.
|
||||
|
||||
### Assistant outcome
|
||||
Migrated logout to require `Authorization: Bearer <access-token>`, updated the web frontend and Firefox extension, and added regression coverage proving body-only logout is rejected while header logout revokes the access token and refresh-token family. Updated SA-001, the checklist, and README examples.
|
||||
|
||||
### User
|
||||
Perform a new security audit overwriting Security-audit.md with new and remaining issues.
|
||||
|
||||
### Assistant outcome
|
||||
Replaced the historical audit with a fresh current-state review dated 2026-08-26. The new report records verified controls and nine remaining findings: logout token transport, raw infrastructure errors, unauthenticated setup exposure, audit-detail sanitization, production secret fallback, non-distributed rate limiting, incomplete security headers/request policy, missing audit operations, and incomplete dependency/container/secret/runtime verification. The baseline backend suite passed 49 tests.
|
||||
|
||||
### User
|
||||
Update SA-012 to reflect the actual implementation, document device binding, rotation, reuse detection, family revocation, logout and password-reset revocation, update the checklist and README API examples, and add the refresh endpoint to the documented API surface.
|
||||
|
||||
### Assistant outcome
|
||||
Reconciled SA-012 and the authentication documentation with the implemented 15-minute access tokens and 30-day device-bound refresh tokens. Documented hashing, rotation, reuse-triggered family revocation, logout and password-reset revocation, added the refresh endpoint and curl example to the README, corrected extension login instructions, and checked off the refresh-token implementation item.
|
||||
|
||||
### User
|
||||
Replace `LINKLOG_TOKEN_EXPIRY_DAYS` with `LINKLOG_TOKEN_EXPIRY_MINUTES`, add `LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS` to the production Compose environment, and add a CI test comparing Compose variables with Settings.
|
||||
|
||||
### Assistant outcome
|
||||
Updated production Compose to pass the configured 15-minute access-token and 30-day refresh-token settings. Added a repository test that compares `LINKLOG_*` Compose keys with the environment keys declared by `Settings` and rejects the obsolete days-based access-token variable.
|
||||
|
||||
### User
|
||||
Reduce the size of the font of the greeting somewhat.
|
||||
|
||||
### Assistant outcome
|
||||
Reduced the email greeting from 22px to 18px while preserving the Asset font, top alignment, and placement to the right of the 50×50 logo.
|
||||
|
||||
### User
|
||||
Put the greeting to the right of the logo in the header, and align at the top.
|
||||
|
||||
### Assistant outcome
|
||||
Changed the email header to use separate table cells for the logo and greeting. The greeting cell is explicitly top-aligned and padded to the right of the fixed 50×50 logo, avoiding email-client baseline alignment differences.
|
||||
|
||||
### User
|
||||
Put the header text to the right of the logo and align it on the top. Also add a comma after Hello.
|
||||
|
||||
### Assistant outcome
|
||||
Aligned the email logo and header text at the top of the header row, kept the text to the right of the 50×50 logo, and changed the greeting to “Hello, a message from <public hostname>”.
|
||||
|
||||
### User
|
||||
Instead of “Hello” print “Hello a message from <public hostname>”, with the public hostname linking to the LinkLog server.
|
||||
|
||||
### Assistant outcome
|
||||
Updated the branded email header to show “Hello a message from <public hostname>”. The visible hostname is extracted from the configured public URL and links to that server; the existing 50×50 top-left logo and Asset font styling remain in place.
|
||||
|
||||
### User
|
||||
The logo is still full width. Make it 50px by 50px, put it in the top left, and put “Hello” to the right in the Asset font.
|
||||
|
||||
### Assistant outcome
|
||||
Reworked the email header to use a fixed 50×50 logo at the top-left, with “Hello” immediately to its right in the Asset font with email-safe fallbacks. Added regression assertions for the dimensions, placement styling, and greeting.
|
||||
|
||||
### User
|
||||
The Logo in the emails should be 120px wide and centered on the top.
|
||||
|
||||
### Assistant outcome
|
||||
Updated the shared branded email template so the embedded LinkLog logo is explicitly 120px wide and remains centered in the top header. Added a regression assertion for the rendered width.
|
||||
|
||||
### User
|
||||
Mails sent should be formatted nicely in the style of the website and include the logo.
|
||||
|
||||
### Assistant outcome
|
||||
Added branded multipart emails with a LinkLog-styled HTML layout, an embedded logo, and preserved plain-text fallbacks for verification, password-reset, and SMTP test messages. Dynamic usernames and URLs are HTML-escaped, and email tests cover the HTML body, CID logo reference, and escaping.
|
||||
|
||||
### User
|
||||
Fix SA-015: Some destructive and administrative operations lack audit logging.
|
||||
|
||||
### Assistant outcome
|
||||
Added an append-only `security_audit_events` table and audit service. Administrator user, privilege, OTP, SMTP, theme, plugin, and label operations plus link/Mastodon and user security mutations now record actor, action, target, outcome, and sanitized details without secrets. Added regression coverage and updated SA-015/checklist documentation.
|
||||
|
||||
### User
|
||||
Solve SA-010: Avatar validation trusts the client MIME type.
|
||||
|
||||
### Assistant outcome
|
||||
Completed avatar hardening with Pillow: uploads are size-limited, decoded and verified rather than trusted by MIME type, bounded to 25 megapixels, fully loaded, normalized to PNG, and served under a fixed `.png` path. Tests now verify PNG normalization and rejection of fake image bytes. SA-010 is marked remediated with `nosniff` and media-origin isolation retained as deployment hardening.
|
||||
|
||||
### User
|
||||
Run full backend and frontend test suites.
|
||||
|
||||
### Assistant outcome
|
||||
The normal backend suite passed with 46 tests. Frontend and extension validation passed for all JavaScript syntax checks, JSON files, XPI rebuild, and unsigned XPI validation. The warnings-as-errors backend variant failed on unclosed SQLite connection `ResourceWarning` instances under Python 3.13; no functional tests failed.
|
||||
|
||||
### User
|
||||
Address SA-007 and use linklog.example.com as default LINKLOG_PUBLIC_URL.
|
||||
|
||||
### Assistant outcome
|
||||
Hardened the production Compose deployment by removing direct host port publication, keeping the app on the external Traefik network, and using `linklog.example.com` as the default public hostname. Added `docker-compose.local.yml` for explicit local direct-port development, updated `.env.example`, backend defaults, README deployment instructions, and SA-007 status.
|
||||
|
||||
### User
|
||||
Fix SA-009: TOTP enrollment has no recovery codes or reset workflow.
|
||||
|
||||
### Assistant outcome
|
||||
Implemented ten one-time hashed TOTP recovery codes, a password-protected `/api/user/otp/recover` workflow, password reauthentication for normal OTP disablement, one-time code consumption, and profile-page controls for saving and using recovery codes. Updated SA-009 and the deployment checklist.
|
||||
|
||||
### User
|
||||
Continue SA-06: Store session credentials in the narrowest available extension storage, minimize token lifetime, support refresh-token rotation, and clear all session material on logout or token invalidation.
|
||||
|
||||
### Assistant outcome
|
||||
Implemented SA-006 session hardening: access tokens now default to 15 minutes, refresh tokens are hashed and persisted separately with device and family binding, rotation revokes prior family state and detects reuse, and password reset revokes sessions. The extension uses Firefox session storage for credentials, refreshes on 401, clears session and legacy local token keys on invalidation/logout, requests only the configured backend origin, and uses a self-only extension-page CSP.
|
||||
|
||||
### User
|
||||
Also allow an admin to reset (disable) OTP for any user.
|
||||
|
||||
### Assistant outcome
|
||||
Added an administrator-only OTP reset endpoint and admin UI action. Resetting a user clears the OTP seed, disables OTP, and deletes all recovery codes. The operation never returns OTP secrets or recovery material and is covered by authorization, missing-user, state, and recovery-code invalidation tests.
|
||||
|
||||
### User
|
||||
Implement SA-006 permission changes: remove `<all_urls>` and unnecessary `tabs`, request exact access to the configured self-hosted backend, and keep page capture behind `activeTab`.
|
||||
|
||||
### Assistant outcome
|
||||
Updated the Firefox extension manifest to use `activeTab` and `storage` only, with Firefox-compatible optional HTTP/HTTPS host permissions. The options login page now normalizes the backend to an origin and requests only that origin during the user-initiated login. The popup checks that exact grant before session validation or link submission, so it does not perform backend calls without permission.
|
||||
|
||||
## 2026-08-24
|
||||
|
||||
### User
|
||||
@@ -218,6 +380,134 @@ Show the avatar with all posts
|
||||
### Assistant outcome
|
||||
Updated feed rendering to display each user's uploaded avatar beside every post, with an initial fallback when no avatar exists or the image fails to load. Filtered profile headers now render uploaded avatars as well. Added avatar data coverage and verified the strict backend suite with 10 passing tests.
|
||||
|
||||
## 2026-08-26
|
||||
|
||||
### User
|
||||
Continue to log interactions to the VIBE directory.
|
||||
|
||||
### Assistant outcome
|
||||
Continued the append-only interaction logging convention by recording this prompt and outcome in both VIBE log files.
|
||||
|
||||
### User
|
||||
On the home page, when clicking on the avatar or the user, show the profile information.
|
||||
|
||||
### Assistant outcome
|
||||
Made each home-feed avatar and username link to the corresponding `/<username>/` profile page, added matching link layout styling, and added a regression assertion for the generated profile URL.
|
||||
|
||||
## 2026-08-26
|
||||
|
||||
### User
|
||||
Localize the firefox plugin.
|
||||
|
||||
### Assistant outcome
|
||||
Added Firefox `browser.i18n` support with an `en-US` message catalog, localized popup and settings page labels and runtime messages, localized manifest metadata, and included the localization resources in XPI packaging and validation.
|
||||
|
||||
### User
|
||||
Create a Spanish, German, French and Dutch locale.
|
||||
|
||||
### Assistant outcome
|
||||
Added complete Spanish (`es`), German (`de`), French (`fr`), and Dutch (`nl`) Firefox locale catalogs and updated XPI packaging and validation to include all four locales.
|
||||
|
||||
## 2026-08-26
|
||||
|
||||
### User
|
||||
On the admin page add the SMTP settings (with the validation button).
|
||||
|
||||
### Assistant outcome
|
||||
Added administrator-only SMTP settings APIs and an admin-page form for loading, saving, and validating SMTP delivery. SMTP passwords are never returned and blank password updates preserve the existing credential. The validation email is sent to the signed-in administrator.
|
||||
|
||||
### User
|
||||
Populate the SMTP fields with current values except the password. Send test mail to the authenticated administrator, use unsaved fields for testing, and apply the configuration page's testing limits.
|
||||
|
||||
### Assistant outcome
|
||||
The admin form now loads effective SMTP settings without exposing the password. Validation sends the current form values directly to the authenticated administrator, without saving them first, while enforcing the same five-send limit, 20-second interval, two-minute cooldown, and countdown behavior used by initial setup.
|
||||
|
||||
### User
|
||||
Report any errors that may occur from the SMTP module to the user.
|
||||
|
||||
### Assistant outcome
|
||||
Updated admin SMTP, user-creation, and validation error handling to display backend SMTP error details and network failures in the UI. Added regression coverage confirming SMTP delivery errors are returned as actionable `503` details.
|
||||
|
||||
### User
|
||||
In the admin screen allow selecting multiple themes for the backend. Create at least one plain day and one night theme, and add all Catppuccin themes.
|
||||
|
||||
### Assistant outcome
|
||||
Added persisted multi-theme administration with Plain Day, Plain Night, Catppuccin Latte, Frappe, Macchiato, and Mocha themes. Administrators can enable any non-empty combination, while visitors can select from the enabled themes using a local preference.
|
||||
|
||||
### User
|
||||
For the day and Latte themes, the contrast on the link items is too low.
|
||||
|
||||
### Assistant outcome
|
||||
Repaired the light-theme contrast by using theme surfaces for link items and toolbars instead of a fixed dark overlay, and strengthened day/Latte text and accent colors for readable titles, metadata, and secondary content.
|
||||
|
||||
### User
|
||||
Add three other popular themes.
|
||||
|
||||
### Assistant outcome
|
||||
Added Dracula, Nord, and Solarized themes to the administrator’s multi-theme selector and the visitor theme picker, with matching backend registry entries, CSS palettes, test coverage, and documentation.
|
||||
|
||||
### User
|
||||
Show tags in the LinkLog on the bottom left, move the date to the bottom right, and horizontally align the tags with the date.
|
||||
|
||||
### Assistant outcome
|
||||
Grouped tags and dates into a shared bottom metadata row, placing tags on the left and the date on the right with responsive wrapping for narrow screens.
|
||||
|
||||
## 2026-08-26
|
||||
|
||||
### User
|
||||
Continue todos.
|
||||
|
||||
### Assistant outcome
|
||||
Reviewed the requirements and source for unfinished TODO markers. No implementation TODOs remain; corrected the README’s stale default-account instructions to match the current first-run administrator setup flow, then validated the project.
|
||||
|
||||
### User
|
||||
Do not show `no comment provided`; leave the comment empty when no comment has been provided.
|
||||
|
||||
### Assistant outcome
|
||||
Changed feed rendering to leave the comment area empty when a link has no comment, removing the `No comment provided` placeholder. Added a regression assertion and validated the change.
|
||||
|
||||
### User
|
||||
Decrease the space between LinkLog items.
|
||||
|
||||
### Assistant outcome
|
||||
Reduced the feed grid gap from 14px to 8px so link-log items sit closer together while preserving the existing item padding and responsive layout.
|
||||
|
||||
### User
|
||||
Move the sort and filter toolbar underneath the theme and menu, in the header, on the home page and user pages.
|
||||
|
||||
### Assistant outcome
|
||||
Moved the feed sort, user filter, and tag filter toolbar into the header beneath the theme picker and hamburger menu. The same header toolbar is used on both the home feed and `/<user>/` pages, with responsive styling preserved.
|
||||
|
||||
### User
|
||||
Run frontend and style checks.
|
||||
|
||||
### Assistant outcome
|
||||
Ran syntax checks for all frontend JavaScript files, editor diagnostics for the stylesheet and key frontend scripts, HTML parsing for all templates, and frontend whitespace validation. All checks passed.
|
||||
|
||||
### User
|
||||
Keep the sort and filter bar left of the logo and pack it snug against the menu and theme selector.
|
||||
|
||||
### Assistant outcome
|
||||
Reworked the feed header into a compact row with the sort and filter bar on the left, the LinkLog branding beside it, and the theme/menu controls on the right. The toolbar stacks cleanly on mobile.
|
||||
|
||||
### User
|
||||
Correction: the feed header should have the sort and filter bar to the right of the LinkLog logo, compact and underneath the theme selector and menu.
|
||||
|
||||
### Assistant outcome
|
||||
Corrected the feed header so the logo remains on the left and the theme selector/menu sit above the sort and filter bar in a right-side control column. The control column remains responsive on mobile.
|
||||
|
||||
### User
|
||||
When a log entry is deleted, delete all Mastodon posts too.
|
||||
|
||||
### Assistant outcome
|
||||
Added migration-backed tracking for all Mastodon post IDs, including reposts. Deleting a link now removes every associated remote Mastodon status before deleting the local entry, and preserves the local link with an actionable error if remote cleanup fails.
|
||||
|
||||
### User
|
||||
Perform the next items on the todo list.
|
||||
|
||||
### Assistant outcome
|
||||
No TODO markers remained, so addressed the next concrete requirements gap found during validation: user profile summaries now render on `/<user>/` pages even when that user has no links, by loading profile data independently from the feed.
|
||||
|
||||
### User
|
||||
Show the avatar with each entry on the home page. On the specific /<user>/ page don't show the avatar and user name with each entry
|
||||
|
||||
@@ -373,3 +663,542 @@ Create a page where users can add, delete, or edit labels - Labels can be edited
|
||||
|
||||
### Assistant outcome
|
||||
Added schema migration 4 with label ownership, authenticated user label CRUD endpoints and a `/labels` management page. Label creators can edit/delete their own labels, non-owners are denied, and administrators can delete any label including another user's labels. Added administrator label listing/deletion controls and regression coverage. The strict backend suite passed with 15 tests.
|
||||
|
||||
### User
|
||||
The profile page shows in red: "can't access property \"classList\", document.querySelector(...) is null"
|
||||
|
||||
### Assistant outcome
|
||||
Found that `profile.js` still queried the removed standalone `#admin-link`, while the current hamburger menu uses `#auth-admin-link`. Updated the selector with an optional null guard, bumped the live asset to `profile.js?v=3`, rebuilt/verified the Docker service, and confirmed the profile route and full strict backend suite with 15 passing tests.
|
||||
|
||||
### User
|
||||
The post prefix is now 'From my #LinkLog: "' make that 'From my #LinkLog: '
|
||||
|
||||
### Assistant outcome
|
||||
Removed the trailing double quote from the default Mastodon post prefix in the publisher, profile UI, fallback, tests, and documentation. Removed the stale minified profile artifact and verified Mastodon/profile tests plus the full strict backend suite with 15 passing tests.
|
||||
|
||||
### User
|
||||
Use the logo.svg in both the plugin as well as on the web page
|
||||
|
||||
### Assistant outcome
|
||||
Bundled the supplied logo into the web static assets and Firefox extension, replaced text-only headers with accessible logo images, added responsive sizing, and verified all web pages, extension references, scripts, and the strict backend suite.
|
||||
|
||||
### User
|
||||
use the logo as the logo on the dropdown for firefox extensions but put it on a dark background
|
||||
|
||||
### Assistant outcome
|
||||
Updated the Firefox popup/dropdown with a dark Catppuccin-style background and matching dark form controls, tags fieldset, status states, and buttons. The existing bundled logo remains the popup brand mark and is readable against the dark surface. Firefox scripts and the strict backend suite passed.
|
||||
|
||||
### User
|
||||
Make sure that the logo is used in the toolbar
|
||||
|
||||
### Assistant outcome
|
||||
Configured the Firefox Manifest V3 action and extension icon declarations to use the bundled `logo.svg` at 16, 32, 48, and 96 pixel entries. Manifest validation, logo asset verification, extension syntax checks, and the strict backend suite passed.
|
||||
|
||||
### User
|
||||
For the logo in the toolbar make the background dark
|
||||
|
||||
### Assistant outcome
|
||||
Added a Catppuccin Mocha `#1e1e2e` background rectangle directly behind the Firefox toolbar logo artwork, preserving the foreground logo and source asset. SVG, manifest, extension scripts, and strict backend validation passed.
|
||||
|
||||
### User
|
||||
Make sure the addon conforms to Firefox guidelines
|
||||
|
||||
### Assistant outcome
|
||||
Reviewed the Firefox WebExtension package, retained permissions required by the active-tab capture flow, added stable Firefox-specific extension identity metadata, and generated exact square 16/32/48/96 PNG icons for toolbar and add-on metadata from the dark logo. Popup and settings branding continue to use `logo.svg`. Manifest paths, icon dimensions, extension scripts, and backend tests were validated successfully.
|
||||
|
||||
### User
|
||||
Create a make file that will regenerate the logo and icon files from LinkLog.svg
|
||||
|
||||
### Assistant outcome
|
||||
Added a root `Makefile` using `LinkLog.svg` as the source. `make logos` regenerates the web SVG, extension SVG, and square 16/32/48/96 PNG icons with ImageMagick. Added tool validation, generated-file cleanup, README instructions, and VIBE logging.
|
||||
|
||||
### User
|
||||
Make sure the addon conforms to Firefox guidelines
|
||||
|
||||
### Assistant outcome
|
||||
Validated the Firefox package and corrected its manifest structure. The toolbar and add-on metadata use exact square PNG icons, popup/settings use the SVG logo, stable Firefox-specific identity metadata is present, all referenced files exist, and extension scripts pass syntax validation. The backend suite remains green.
|
||||
|
||||
### User
|
||||
How come when te container starts after docker compose down -v the database is still populated with old links
|
||||
|
||||
### Assistant outcome
|
||||
Inspected the active container and confirmed it uses `/app/backend/data/linklog.db` from the Compose volume `linklog_linklog_data`, containing 230 links. The current Compose project maps logical `linklog_data` to that prefixed volume. `docker compose down` preserves it; only `docker compose down -v` from the same project removes it. A different directory/project, an external volume, or stopping without `-v` can therefore preserve the data.
|
||||
|
||||
### User
|
||||
Refine the Plugins Settings page. When the user is logged in it shows all "<user> logged in at <url>" and a sign-out button. If the user is not logged in it shows the form as is now.
|
||||
|
||||
### Assistant outcome
|
||||
Updated the Firefox extension settings page to restore valid stored sessions, show `<username> logged in at <backend URL>` with a sign-out button, and show the original login form when signed out or when token validation fails. Sign-out revokes the token when possible, clears stored credentials, and returns to the form. Extension and backend validation passed.
|
||||
|
||||
### User
|
||||
On the plugin, next to the logo, create a link of the form: [LinkLog](https://<host>/<user>)
|
||||
|
||||
### Assistant outcome
|
||||
Added a `LinkLog` link next to the Firefox popup logo. It uses the configured backend origin and authenticated username to target `/<user>/`, preserving HTTP or HTTPS from the configured backend. Popup HTML, scripts, manifest, and backend regression validation passed.
|
||||
|
||||
### User
|
||||
Use the Asset Font from google foundry as font for the LinkLog text
|
||||
|
||||
### Assistant outcome
|
||||
Applied the Google Foundry `Asset` font to visible LinkLog branding on the web and Firefox popup, retaining graceful local fallbacks for restricted or offline extension contexts. Font declarations, branding references, extension scripts, whitespace checks, and the strict backend suite passed.
|
||||
|
||||
### User
|
||||
Create an about page and add an entry in the hamburger menu. The about page explains what the linklog does
|
||||
|
||||
### Assistant outcome
|
||||
Added an `/about` page explaining LinkLog's link capture, cleanup, tagging, filtering, ownership, and Mastodon publishing workflow. Added an always-visible About item to every shared hamburger menu, documented the route, and verified all web routes, scripts, and the strict backend suite with 15 passing tests.
|
||||
|
||||
### User
|
||||
On the bottom of all files add a copyright statement (Olaf Kolkman) and a link to the git.kolkman.org/LinkLog repository in small print
|
||||
|
||||
### Assistant outcome
|
||||
Added small-print attribution footers to all seven web templates and both Firefox extension pages. Each footer contains `Copyright Olaf Kolkman` and a link to `https://git.kolkman.org/olaf/Link-Log`, with matching web and extension styling. All web routes, extension footer references, strict backend tests, and whitespace checks passed.
|
||||
|
||||
### User
|
||||
the link in the site footer must be underlined and in the same color as the other text
|
||||
|
||||
### Assistant outcome
|
||||
Updated the web footer repository link to remain the same muted color as the surrounding footer text and always display an underline. Added a footer rendering assertion and validated the site.
|
||||
|
||||
### User
|
||||
Add copyright sign and 2026 to the copyright notices
|
||||
|
||||
### Assistant outcome
|
||||
Updated all web and Firefox extension footer notices to `© 2026 Olaf Kolkman`, preserving the repository links and small-print styling. Verified all eight user-facing pages, whitespace, and the strict backend suite with 15 passing tests.
|
||||
|
||||
### User
|
||||
in the footer make the link the same color as the mother text, when clicked use a tint from the Catpuccin theme
|
||||
|
||||
### Assistant outcome
|
||||
Updated web and extension footer links to inherit the surrounding footer text color, remain underlined, and use Catppuccin lavender/mauve interaction tints for hover, focus, and active click states. Preserved the current repository URL edits and verified the strict backend suite with 15 passing tests.
|
||||
|
||||
### User
|
||||
Add a GNU License file
|
||||
|
||||
### Assistant outcome
|
||||
Added a root `LICENSE` file declaring GNU General Public License version 3 or any later version (GPL-3.0-or-later), with Olaf Kolkman copyright attribution and the official GNU license reference. Documented the license in `README.md`.
|
||||
|
||||
### User
|
||||
Add a copyright statement to source files refer to GNU license
|
||||
|
||||
### Assistant outcome
|
||||
Added `Copyright © 2026 Olaf Kolkman` and `SPDX-License-Identifier: GPL-3.0-or-later` headers to all 47 non-minified application, test, frontend, extension, build, deployment, and source-logo files. Generated/runtime assets were left untouched. Python and JavaScript compilation, Compose validation, whitespace checks, and the strict backend suite passed with 15 tests.
|
||||
|
||||
### User
|
||||
Add the version to the name of the resulting xpi
|
||||
|
||||
### Assistant outcome
|
||||
Updated the Makefile to read the extension version from `webextension/manifest.json` and produce a versioned archive such as `LinkLog-0.1.0.xpi`. Updated `.gitignore` and README documentation. The generated XPI contains 12 expected extension files and passes `unzip -tq` integrity validation.
|
||||
|
||||
### User
|
||||
Set the version number of the backend to 0.1.0
|
||||
|
||||
### Assistant outcome
|
||||
Added backend setting `version = 0.1.0`, wired it into FastAPI and OpenAPI metadata, and exposed `LINKLOG_VERSION` as an environment override. Added regression coverage and documented the setting. Compose validation and the strict backend suite passed with 15 tests.
|
||||
|
||||
### User
|
||||
Add the creation of an xpi bundle for the webextention to the Makefile
|
||||
|
||||
### Assistant outcome
|
||||
Added a portable `xpi` Makefile target that regenerates logo assets and packages the Firefox extension into `LinkLog.xpi`, excluding metadata and minified artifacts. Added README instructions, ignored the generated XPI, and verified the archive contents and integrity with `unzip -tq`.
|
||||
|
||||
### User
|
||||
Correct: A signed XPI will be generated manually and checked into the repository under XPI/signed
|
||||
|
||||
### Assistant outcome
|
||||
Defined the release workflow around a manually checked-in signed XPI and added version/update-manifest validation, Docker image publishing, and Gitea release asset handling.
|
||||
|
||||
### User
|
||||
The "data_collection_permissions" property is missing from the plugin
|
||||
|
||||
### Assistant outcome
|
||||
Added Firefox `data_collection_permissions` requiring `websiteActivity`, with no optional categories, and enforced the declaration in release validation.
|
||||
|
||||
### User
|
||||
Validate the XPI during the make process of the unsigned xpi
|
||||
|
||||
### Assistant outcome
|
||||
Added unsigned-XPI validation to the Makefile. The validator checks ZIP integrity, required files, macOS metadata, and exact manifest parity.
|
||||
|
||||
### User
|
||||
pressing remove still does not remove a user.
|
||||
|
||||
### Assistant outcome
|
||||
Fixed admin user removal behavior, added server-side self-protection, improved browser error reporting, and updated the admin cache-busting version.
|
||||
|
||||
### User
|
||||
Trying to remove user alice: Could not remove alice: Internal Server Error
|
||||
|
||||
### Assistant outcome
|
||||
Found the SQLite foreign-key failure caused by Alice-owned tokens, links, and plugin configuration. User deletion now removes dependent records transactionally before deleting the user. Full validation passed.
|
||||
|
||||
### User
|
||||
Create a Gitea Action for every update to main that creates a Docker image tagged development
|
||||
|
||||
### Assistant outcome
|
||||
Added `.gitea/workflows/development.yml`, publishing `git.kolkman.org/olaf/link-log:development` on every push to `main`, with manual dispatch support.
|
||||
|
||||
### User
|
||||
Use an access token to publish to registry, not username and password
|
||||
|
||||
### Assistant outcome
|
||||
Changed release and development workflows to use `REGISTRY_TOKEN` as the Docker registry credential while retaining `REGISTRY_USERNAME` as the login identity.
|
||||
|
||||
### User
|
||||
Add SMTP capabilities and email validation links
|
||||
|
||||
### Assistant outcome
|
||||
Added SMTP delivery, email verification tokens, verification-link handling, and environment configuration for SMTP.
|
||||
|
||||
### User
|
||||
Do not configure default users at bootstrap. Present a configuration page when no administrator exists.
|
||||
|
||||
### Assistant outcome
|
||||
Removed default-user bootstrap, added a first-run setup page, persisted SMTP settings, created the first administrator through setup, and added an SMTP test-mail step.
|
||||
|
||||
### User
|
||||
Separate saving configuration from sending test mail, allow five sends with 20-second intervals, then hold for two minutes with a visual timer.
|
||||
|
||||
### Assistant outcome
|
||||
Split setup into Save configuration, Send test mail, and Complete setup actions. Added persistent server-side throttling, reload-safe countdown state, a five-send limit, and a two-minute cooldown.
|
||||
|
||||
### User
|
||||
Use `.env` defaults during initial configuration.
|
||||
|
||||
### Assistant outcome
|
||||
The setup status endpoint now exposes effective environment SMTP defaults, and the setup form populates blank fields from them. Persisted setup values take precedence after saving.
|
||||
|
||||
### User
|
||||
Use OAuth to register with the Mastodon account and obtain access to post.
|
||||
|
||||
### Assistant outcome
|
||||
Added Mastodon OAuth app registration, authorization and callback endpoints, one-time OAuth state storage, and per-user access-token persistence.
|
||||
|
||||
### User
|
||||
Allow the user to enter the Mastodon server to authenticate to.
|
||||
|
||||
### Assistant outcome
|
||||
The profile now requires an explicit Mastodon server, saves that server before OAuth, and authenticates against the selected instance.
|
||||
|
||||
### User
|
||||
Clicking authenticate with this server for social.secret-wg.org generates a 502 error.
|
||||
|
||||
### Assistant outcome
|
||||
Confirmed the Mastodon instance was returning HTTP 429 during app registration. OAuth app credentials are now cached per instance, and upstream rate-limit responses are passed through with retry information instead of being reported as generic 502 errors.
|
||||
|
||||
### User
|
||||
When a password is mistyped, send a password reset link.
|
||||
|
||||
### Assistant outcome
|
||||
Added hashed, expiring, single-use password-reset tokens, SMTP reset mail, a reset-password page, generic login errors, and session revocation after reset.
|
||||
|
||||
### User
|
||||
Log the unlogged chat and prompt in the VIBE directory.
|
||||
|
||||
### Assistant outcome
|
||||
Appended the previously unlogged feature work and this request to `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`.
|
||||
|
||||
### User
|
||||
Continue to log prompts and chats in VIBE
|
||||
|
||||
### User
|
||||
Use the VIBE directory in the current workspace.
|
||||
|
||||
### Assistant outcome
|
||||
Confirmed the current workspace is `/home/olaf/LinkLog_Dev` and appended both requests and this outcome to the VIBE logs located at `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`.
|
||||
|
||||
### User
|
||||
Posting to Mastodon seems to fail, try to fix, add debug logging.
|
||||
|
||||
### Assistant outcome
|
||||
Changed Mastodon status publishing to form-encoded API requests, added safe configurable logging for skipped, successful, and failed posts, included upstream HTTP response details without logging access tokens, and wired `LINKLOG_LOG_LEVEL` through the environment and Compose configuration. Updated the posting regression test. The focused test and complete Dockerized backend suite passed with 22 tests.
|
||||
|
||||
### User
|
||||
`LINKLOG_PUBLIC_URL` and `TRAEFIK_HOST` are the same and can be merged. Use `LINKLOG_PUBLIC_URL` in Docker Compose.
|
||||
|
||||
### Assistant outcome
|
||||
Removed the duplicate `TRAEFIK_HOST` configuration, changed both Traefik router rules to use `LINKLOG_PUBLIC_URL`, standardized the value as a host name, and normalized scheme-less values to valid HTTP/HTTPS backend callback URLs. Compose validation, URL normalization, and the complete Dockerized backend suite passed with 22 tests.
|
||||
|
||||
### User
|
||||
Format Mastodon posts as `From my #LinkLog:`, the web page title, an optional comment, and `from: URL`.
|
||||
|
||||
### Assistant outcome
|
||||
Updated the Mastodon formatter to emit the configured prefix, title, optional comment, and source URL as blank-line-separated blocks. Tags remain on the source URL line. The focused posting test and complete Dockerized backend suite passed with 22 tests, and the running container is healthy on port 5469.
|
||||
|
||||
### User
|
||||
Only print the `from` line if there is no title. Put the title directly behind the colon, and put all tags on the last line.
|
||||
|
||||
### Assistant outcome
|
||||
Updated Mastodon formatting to place the title directly after `From my #LinkLog:`, omit the `from:` line when no title is available, and place tags on a separate final line. Added no-title regression coverage. The focused tests passed and the complete Dockerized backend suite passed with 23 tests.
|
||||
|
||||
### User
|
||||
Do not show edit buttons on the home page. On `/<user>/`, show the edit button on the right and add a delete button.
|
||||
|
||||
### Assistant outcome
|
||||
Added an owner-scoped `DELETE /api/links/{link_id}` endpoint. Feed edit/delete controls now render only on user-specific pages, never on the home feed, and are right-aligned in an entry action group. Added owner-only deletion regression coverage and updated the feed cache key. The complete Dockerized backend suite passed with 23 tests, and the running container is healthy.
|
||||
|
||||
### User
|
||||
Put the buttons on the right-hand side of the link item, make them smaller, and keep the same color scheme.
|
||||
|
||||
### Assistant outcome
|
||||
Changed the entry action group to float at the right edge of user-specific link items, allowing content to wrap around it. Reduced Edit and Delete button padding, radius, and font size while preserving Catppuccin surface and danger colors.
|
||||
|
||||
### User
|
||||
Put the Mastodon button on the lower-right corner of the log entry.
|
||||
|
||||
### Assistant outcome
|
||||
Split the Mastodon control from the Edit/Delete action group and positioned it at the lower-right corner of user-specific link entries. Reserved bottom space in each entry to prevent overlap.
|
||||
|
||||
### User
|
||||
Make sure that the Makefile also rebuilds the XPI if any of its source files are changed.
|
||||
|
||||
### Assistant outcome
|
||||
Changed the unsigned XPI into a dependency-aware Make target with explicit dependencies on all packaged extension sources and the XPI validator. Confirmed a forced build succeeds and the real archive target reports up to date when unchanged.
|
||||
|
||||
### User
|
||||
Change the Mastodon button location to immediately below the Edit and Delete buttons.
|
||||
|
||||
### Assistant outcome
|
||||
Changed the Mastodon button from absolute lower-right positioning to normal right-floated flow with `clear: right`, placing it directly beneath the Edit/Delete row while preserving the existing logo and posted-state styling.
|
||||
|
||||
### User
|
||||
When an authorized user is on their `/<user>/` page, show a button to post on Mastodon. After a message has been posted, keep the button functional but change its color and use the Mastodon logo inside it.
|
||||
|
||||
### Assistant outcome
|
||||
Added persisted Mastodon post state, an owner-scoped repost endpoint, and an owner-only Mastodon button on user-specific pages. The button includes a bundled Mastodon logo, says `Post to Mastodon` before posting, changes to the posted teal state and `Post again` afterward, and remains functional for reposting. Home-page entries remain free of controls. The complete Dockerized backend suite passed with 23 tests and the running container is healthy.
|
||||
|
||||
## 2026-08-26
|
||||
|
||||
### User
|
||||
Don't forget to update the plugin to work with OTP.
|
||||
|
||||
### Assistant outcome
|
||||
Updated the Firefox extension settings login to accept and submit a six-digit one-time password. The backend supports TOTP setup, enable/disable confirmation, and OTP-enforced login, with the stored secret protected from profile responses.
|
||||
|
||||
### User
|
||||
When the user is not logged in, the plugin should display no form fields and warn them that they must log in, with a link to settings.
|
||||
|
||||
### Assistant outcome
|
||||
The Firefox popup now hides capture fields by default for signed-out users, shows a localized sign-in warning, and provides an Open settings action. The form appears only after backend credentials and a valid session are available; expired sessions return to the warning state.
|
||||
|
||||
### User
|
||||
Remove `DEFAULT_BACKEND` setting in the plugin.
|
||||
|
||||
### Assistant outcome
|
||||
Removed the hard-coded backend URL fallback from the Firefox extension. The backend URL is now empty until the user enters it, and the README setup instructions reflect that no default server is assumed.
|
||||
|
||||
### User
|
||||
Change authentication to use email addresses rather than usernames while keeping usernames for presentation.
|
||||
|
||||
### Assistant outcome
|
||||
Switched backend, web login, and Firefox extension login to use trimmed email addresses as credentials. Returned usernames remain available for display, profiles, feed URLs, and authenticated session presentation. Updated login callers, documentation, and tests.
|
||||
|
||||
### User
|
||||
Make sure the web plugin follows the same logic.
|
||||
|
||||
### Assistant outcome
|
||||
Aligned the web and Firefox plugin flows with email-based authentication, including email-form fields, trimmed email/OTP submission, and retention of the returned username for display.
|
||||
|
||||
### User
|
||||
In the plugin, `<span data-i18n="emailLabel">emailLabel</span>` should read `<span data-i18n="emailLabel">Email</span>`.
|
||||
|
||||
### Assistant outcome
|
||||
Changed the Firefox plugin settings email field fallback text to `Email` while retaining the existing `emailLabel` localization key.
|
||||
|
||||
### User
|
||||
Change the title of the field “One-time password” to “One-time password (when configured)”.
|
||||
|
||||
### Assistant outcome
|
||||
Updated the OTP field label in the English, Spanish, German, French, and Dutch extension locale catalogs to clarify that the code is needed only when OTP is configured.
|
||||
|
||||
### User
|
||||
When a URL with the same title is already in the database, warn the user, allow comment and hashtag changes, and retrigger plugins such as Mastodon reposting.
|
||||
|
||||
### Assistant outcome
|
||||
Added authenticated duplicate detection for matching title and normalized URL. The existing link is updated with the submitted comment and tags, plugins are redispatched, and the popup displays a localized duplicate warning.
|
||||
|
||||
### User
|
||||
When the plugin is activated and the link already exists, show “This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered.”
|
||||
|
||||
### Assistant outcome
|
||||
Added an authenticated duplicate-check request when the popup opens after loading the active page. Existing links now show the requested warning before submission; comment and tag editing plus plugin retriggering remain available.
|
||||
|
||||
### User
|
||||
Display any errors that occur during posting.
|
||||
|
||||
### Assistant outcome
|
||||
Save responses now include sanitized plugin failure details, and the popup displays publishing errors alongside the save confirmation, including Mastodon HTTP or connection failures.
|
||||
|
||||
### User
|
||||
When pressing Save link, display “Link saved to <LinkLog server URL>” and hide all other information. Refresh only when the plugin is opened again.
|
||||
|
||||
### Assistant outcome
|
||||
Added a terminal save state to the popup. After a successful save it displays the localized LinkLog server URL, hides the form, session, warnings, and header information, and performs no refresh until the popup is opened again.
|
||||
|
||||
### User
|
||||
The plugin settings still show `emailLabel`; make that `email` as the title for the email field.
|
||||
|
||||
### Assistant outcome
|
||||
Added the missing `emailLabel` and `emailPlaceholder` messages to every extension locale. The English field now resolves to `Email` instead of displaying the localization key.
|
||||
|
||||
### User
|
||||
For the new password in the user setting add a validation field to make sure they are the same before submitting.
|
||||
|
||||
### Assistant outcome
|
||||
Added a confirm-new-password field to the profile password form. The browser now compares both new-password values and blocks submission with an error message when they differ.
|
||||
|
||||
### User
|
||||
Remove any leading and trailing spaces when entering fields in the plugin settings page.
|
||||
|
||||
### Assistant outcome
|
||||
The extension now trims leading and trailing whitespace from the backend URL, username, and OTP before validation, login, and storage. Password input is preserved exactly so intentional password characters are not changed.
|
||||
|
||||
### User
|
||||
Do a full security audit document in detail in `Security-audit.md`.
|
||||
|
||||
### Assistant outcome
|
||||
Created [Security-audit.md](../Security-audit.md), documenting the assessed architecture, existing controls, 15 prioritized security findings, authentication and authorization review, data protection, frontend and extension risks, deployment checklist, remediation order, and verification limits.
|
||||
|
||||
### User
|
||||
Address issue 1 and improve password storage.
|
||||
|
||||
### Assistant outcome
|
||||
Replaced unsalted SHA-256 password storage with salted scrypt hashes using standard-library `hashlib.scrypt`. Existing legacy SHA-256 hashes remain verifiable and are transparently upgraded after successful login. Password change and reset flows use the stronger hashing path, regression coverage was added, and `Security-audit.md` was updated to mark SA-001 as remediated in the current worktree.
|
||||
|
||||
### User
|
||||
The login page should ask for OTP password.
|
||||
|
||||
### Assistant outcome
|
||||
Added an optional “One-time password (when configured)” field to the web login page. The form sends a trimmed OTP value to the existing OTP-aware login endpoint and displays the backend’s OTP error when required or invalid.
|
||||
|
||||
### User
|
||||
Allow secondary or tertiary email addresses, validate them before authentication, show their status in the profile, allow resending validation mail, and retain a holdback period.
|
||||
|
||||
### Assistant outcome
|
||||
Added independently tracked secondary and tertiary addresses with verification tokens, email-based authentication only for validated addresses, profile status/add/resend/remove controls, a maximum of two additional addresses, and persistent resend throttling with 20-second intervals, five sends, and a two-minute cooldown.
|
||||
|
||||
### User
|
||||
Enable users to change the primary email address and remove the original one while maintaining access and rights.
|
||||
|
||||
### Assistant outcome
|
||||
Added a pending primary-email replacement workflow. The original address remains active until the new address is validated, preserving the same account, privileges, and sessions; after validation the new address replaces the original. Added profile controls, verification/resend handling, migration 13, tests, documentation, and security-audit notes.
|
||||
|
||||
### User
|
||||
Choose the primary email from already verified alternative addresses and increase the allowed alternatives to five.
|
||||
|
||||
### Assistant outcome
|
||||
Verified alternative addresses can now be promoted to primary from the profile page. The previous primary is retained as a verified alternative, preserving the account identity and access. The maximum number of additional addresses was increased from two to five, with test and documentation updates.
|
||||
|
||||
### User
|
||||
Make sure an email can only be selected when it has been validated.
|
||||
|
||||
### Assistant outcome
|
||||
Made validated status explicit in the email-address API and profile UI. Only verified alternatives expose and render the primary-selection action, while the backend rejects any unverified promotion attempt.
|
||||
|
||||
### User
|
||||
Remove the entire “New primary email address” block; keep only selecting an existing alternative as primary.
|
||||
|
||||
### Assistant outcome
|
||||
Removed the pending primary-email replacement form, client handlers, API routes, service, and obsolete test. The profile now retains only verified alternative promotion, with unverified addresses unable to become primary.
|
||||
|
||||
### User
|
||||
Remove the “New primary email address” functionality and keep only selecting an existing alternative as primary.
|
||||
|
||||
### Assistant outcome
|
||||
Removed the replacement-email workflow entirely. Added cleanup migration 14 for its unused table; verified alternatives remain the only addresses eligible for primary selection.
|
||||
|
||||
### User
|
||||
Address SA-003 by supplying a dedicated protected encryption key and encrypting sensitive values before SQLite storage.
|
||||
|
||||
### Assistant outcome
|
||||
Added Fernet encryption with required `LINKLOG_DATA_ENCRYPTION_KEY` handling for SMTP, Mastodon OAuth/client and access-token values, TOTP seeds, and recognized administrator plugin secrets. Updated Docker/Compose configuration, tests, README guidance, and the security audit. Legacy plaintext values require rotation after key configuration.
|
||||
|
||||
### User
|
||||
Address SA-004 by validating Mastodon instances as HTTPS public hostnames, rejecting unsafe DNS/IP ranges including mapped IPv6, and blocking redirects.
|
||||
|
||||
### Assistant outcome
|
||||
Implemented and validated SA-004 with centralized Mastodon URL checks, DNS resolution and blocked-range detection, IPv4-mapped IPv6 handling, and no-redirect outbound requests for OAuth, posting, and deletion. The rebuilt container suite passed with 42 tests.
|
||||
|
||||
### User
|
||||
Implement SA-005: login endpoint lacks rate limiting and lockout.
|
||||
|
||||
### Assistant outcome
|
||||
Added persistent IP/email login throttling with a five-failure limit in a 15-minute window, two-minute lockout, `Retry-After` responses, OTP failure coverage, and counter reset after successful authentication. Updated documentation and audit status.
|
||||
|
||||
### User
|
||||
Address SA-004 by validating Mastodon instances as HTTPS public hostnames, rejecting unsafe DNS/IP ranges including mapped IPv6, and blocking redirects.
|
||||
|
||||
### Assistant outcome
|
||||
Added centralized Mastodon SSRF protection for OAuth, posting, and deletion. Validation requires HTTPS hostname-only instances, resolves and rejects private or reserved destinations, and all outbound requests use a no-redirect opener. Added security tests, documentation, and audit status updates.
|
||||
|
||||
### User
|
||||
When the user is logged in, the web plugin should not display “Please sign in to use LinkLog.”
|
||||
|
||||
### Assistant outcome
|
||||
Removed the authenticated-state warning flash by hiding the popup sign-in warning in the initial markup. The popup reveals it only after the session check confirms that no valid bearer session is available.
|
||||
|
||||
### User
|
||||
When the user is signed in, the plugin should not display “Please sign in to use LinkLog.” or the settings link.
|
||||
|
||||
### Assistant outcome
|
||||
Updated popup session detection to validate the stored bearer token through `/api/auth/me` before hiding the sign-in warning and revealing capture fields. Expired or invalid sessions now keep the warning and settings action visible.
|
||||
|
||||
### User
|
||||
The plugin still does not behave as expected and still shows that the user should sign in.
|
||||
|
||||
### Assistant outcome
|
||||
Centralized popup session validation, ensured valid bearer sessions hide the sign-in warning, and cleared stale credentials when the backend rejects a session. The capture form is shown only after successful validation.
|
||||
|
||||
### User
|
||||
In the popup show that the user has logged in.
|
||||
|
||||
### Assistant outcome
|
||||
Added a localized authenticated-session indicator to the Firefox popup, showing the returned username and backend URL after successful session validation. It remains hidden for signed-out or invalid sessions.
|
||||
|
||||
### User
|
||||
Address SA-003 by using a dedicated secret key supplied through a protected environment or secret file, and encrypt sensitive values before SQLite storage.
|
||||
|
||||
### Assistant outcome
|
||||
Added Fernet encryption using the required `LINKLOG_DATA_ENCRYPTION_KEY` for newly stored SMTP passwords, Mastodon OAuth secrets and access tokens, and TOTP seeds. Protected API responses from returning Mastodon tokens, required the key in Docker, documented generation and rotation, and updated the security audit.
|
||||
|
||||
### User
|
||||
The popup still shows the sign-in block even though the authenticated session text is displayed; show the block only when signed out.
|
||||
|
||||
### Assistant outcome
|
||||
Made popup authentication states mutually exclusive using the DOM `hidden` property. Authenticated sessions now always hide the sign-in block, while signed-out sessions hide the session text and show only the warning block.
|
||||
|
||||
### User
|
||||
The authenticated session text and sign-in block are still shown together.
|
||||
|
||||
### User
|
||||
Use the VIBE directory to log interactions
|
||||
|
||||
### Assistant outcome
|
||||
Appended this visible interaction to the project VIBE chat and prompt logs in the repo’s append-only format.
|
||||
|
||||
### Assistant outcome
|
||||
Made popup state transitions defensive by synchronizing both `hidden` attributes and CSS classes. Non-authentication tag-loading errors no longer switch the popup to signed-out state; only a rejected session does. Added `display: none !important` guards for both authentication blocks.
|
||||
|
||||
### User
|
||||
Continue to document every prompt and chat in the VIBE directory.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -65,6 +65,153 @@
|
||||
61. Make the tags filtering case incensitive (but maintain case of tags)
|
||||
62. Display the date as "2026 June 18 - 20:22"
|
||||
63. Create a page where users can add, delete, or edit labels - Labels can be edited and deleted by the same user that created them. The administrator can delete any label.
|
||||
64. The profile page shows in red: "can't access property \"classList\", document.querySelector(...) is null"
|
||||
65. The post prefix is now 'From my #LinkLog: "' make that 'From my #LinkLog: '
|
||||
66. Use the logo.svg in both the plugin as well as on the web page
|
||||
67. use the logo as the logo on the dropdown for firefox extensions but put it on a dark background
|
||||
68. Make sure that the logo is used in the toolbar
|
||||
69. For the logo in the toolbar make the background dark
|
||||
70. Make sure the addon conforms to Firefox guidelines
|
||||
71. Create a make file that will regenerate the logo and icon files from LinkLog.svg
|
||||
72. Make sure the addon conforms to Firefox guidelines
|
||||
73. How come when te container starts after docker compose down -v the database is still populated with old links
|
||||
74. Refine the Plugins Settings page. When the user is logged in it shows all "<user> logged in at <url>" and a sign-out button. If the user is not logged in it shows the form as is now.
|
||||
75. On the plugin, next to the logo, create a link of the form: [LinkLog](https://<host>/<user>)
|
||||
76. Use the Asset Font from google foundry as font for the LinkLog text
|
||||
77. Create an about page and add an entry in the hamburger menu. The about page explains what the linklog does
|
||||
78. On the bottom of all files add a copyright statement (Olaf Kolkman) and a link to the git.kolkman.org/LinkLog repository in small print
|
||||
79. the link in the site footer must be underlined and in the same color as the other text
|
||||
80. Add copyright sign and 2026 to the copyright notices
|
||||
81. in the footer make the link the same color as the mother text, when clicked use a tint from the Catpuccin theme
|
||||
82. Add a GNU License file
|
||||
83. Add a copyright statement to source files refer to GNU license
|
||||
84. Add the version to the name of the resulting xpi
|
||||
85. Set the version number of the backend to 0.1.0
|
||||
86. Add the creation of an xpi bundle for the webextention to the Makefile
|
||||
87. Correct: A signed XPI will be generated manually and checked into the repository under XPI/signed
|
||||
88. The "data_collection_permissions" property is missing from the plugin
|
||||
89. Validate the XPI during the make process of the unsigned xpi
|
||||
90. pressing remove still does not remove a user.
|
||||
91. Trying to remove user alice: Could not remove alice: Internal Server Error
|
||||
92. create a gitea action that is ran every time main is updated and that creates a docker image tagged development
|
||||
93. Use an access token to publish to registry, not username and password
|
||||
94. Add SMTP capabilities to the backend. Use it to validate the email addresses using a validation link in mail
|
||||
95. Do not configure default users at bootstrap. Instead present a configuration page (only present if no administrator is configured). The configuration page asks for the admin users credetials and allows to configure the SMTP settings and sends a test mail after configuration
|
||||
96. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent."
|
||||
97. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down.
|
||||
98. when running the initial config use the defaults from the .env file when available
|
||||
99. Use oauth to register with the mastodon account and obtain access to post
|
||||
100. Allow user to enter the mastodon server to authenticate to
|
||||
101. Clicking authenticate with this server (social.secret-wg.org) generates 502 error
|
||||
102. Log the unlogged chat and promt in the VIBE directory
|
||||
103. when password is mistyped send a password reset link
|
||||
104. when running the initial config use the defaults from the .env file when available
|
||||
105. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent."
|
||||
106. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down.
|
||||
107. Use oauth to register with the mastodon account and obtain access to post
|
||||
108. Allow user to enter the mastodon server to authenticate to
|
||||
109. Log the unlogged chat and promt in the VIBE directory
|
||||
110. Continue to log prompts and chats in VIBE
|
||||
111. use VIVE that is in the current directory
|
||||
112. Posting to mastodon seems to fail, try to fix, add debug logging
|
||||
113. LINKLOG_PUBLIC_URL and TRAEFIK_HOST are the same and can be merged. (use LINKLOG_PUBLIC_URL), fix docker-compose to use said variable
|
||||
114. Format mastodon posts like From my #LinkLog: Title, optional comment, and from: URL
|
||||
115. Only print the 'from' line if there is no title. Put the title directly behind the colon, and put all tags on the last line.
|
||||
116. In the frontend do not show edit buttons on the home page even when a user is logged in. On the /<user>/ page show the edit button on the right of the entry. Also add a delete button.
|
||||
117. Put the buttons on the right hand side of the link item, make the buttons smaller and same color scheme
|
||||
118. Put the mastodon button on the lower right corner of the log entry
|
||||
119. Make sure that the makefile also rebuilds XPI if any of its source files are changed
|
||||
120. Change that location to be immediately below the edit and delete button
|
||||
121. When the user is authorized and on its /<user>/ page show a Mastodon post button with logo; after posting keep it functional but change its color.
|
||||
122. Continue to log interactions to the VIBE directory.
|
||||
123. On the home page, when clicking on the avatar or the user, show the profile information.
|
||||
124. Localize the firefox plugin.
|
||||
125. Create a spanish, german, french and dutch locale.
|
||||
126. On the admin page add the SMTP settings (with the validation button).
|
||||
127. Populate the SMTP fields with the current values except for the password. Send the testmail to the currently authenticated admin user. Only use updated fields when testing. Use the same logic as in the configuration page to restrict endless testing.
|
||||
128. Report any errors that may occur from the SMTP module to the user.
|
||||
129. In the admin screen allow to select multiple themes for the backend. Create at least one plain day and one night theme, and add in all catpuccin themes for good measure.
|
||||
130. For the day and latte themes the contrast on the link items is too low.
|
||||
131. Add 3 other of the most popular themes.
|
||||
132. Show the tags in the linklog on the bottom left, move the date to the bottom right - horizontally align the tags with the date.
|
||||
133. Continue todos.
|
||||
134. Do not show 'no comment provided' but leave empty when no comment has been provided.
|
||||
135. Decrease the space between link-log items.
|
||||
136. Perform the next items on the todo list.
|
||||
137. Correct: move the sort and filter toolbar underneath the theme and menu, in the header, on the home page and on the <user> pages.
|
||||
138. Run frontend and style checks.
|
||||
139. Keep the sort and filter bar left of the logo and pack it snug against the menu and theme selector.
|
||||
140. Correction: the feed header should have the sort and filter bar to the right of the LinkLog logo, compact and underneath the theme selector and menu.
|
||||
141. When a log entry is deleted then all mastodon posts are deleted too.
|
||||
142. Don't forget to update the plugin to work with OTP.
|
||||
143. When the user is not logged in then the plugin should just display no form fields but warn the user that they have to log in with a link to settings.
|
||||
144. Remove DEFAULT_BACKEND setting in the plugin.
|
||||
145. Change the title of the field "One-time password" to "One-time password (when configured)".
|
||||
146. The plugin settings still show 'emailLabel'; make that 'email' as title for the email field.
|
||||
147. When a URL with the same title is already in the database, warn the user, allow comment and hashtag changes, and retrigger plugins such as Mastodon reposting.
|
||||
148. Display any errors that occur during posting.
|
||||
149. When the plugin is activated and the link already exists, show "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered."
|
||||
150. When pressing save link the plugin should display "Link saved to <url of linklog server>" and hide all other information. It should only refresh when the plugin is opened again
|
||||
151. Remove any leading and trailing spaces when entering fields in the settings page of the plugin.
|
||||
152. Do a full security audit document in what you have done in detail in Security-audit.md
|
||||
153. Address issue 1. and improve password storage
|
||||
154. The login page should ask for OTP password
|
||||
155. For the new password in the user setting add a validation field to make sure they are the same before submitting
|
||||
156. Change so that authentication is based on email address rather than username - maintain the username for presentation purposes
|
||||
157. Make sure the web plugin follows same logic
|
||||
158. Implement the recommendation for ### SA-002: Bearer tokens accepted in query strings
|
||||
159. Change so that authentication is based on email address rather than username - maintain the username for presentation purposes
|
||||
160. Make sure the web plugin follows same logic
|
||||
161. In the plugin <span data-i18n="emailLabel">emailLabel</span> should read: <span data-i18n="emailLabel">Email</span>
|
||||
162. Allow addition of secondary or tertiary email addresses; validate them before authentication and support profile status/resend controls with holdback.
|
||||
163. Enable the user to change primary email address and remove the original one while maintaining access and rights.
|
||||
164. Choose primary email from already verified alternative email addresses and increase the number of alternative email addresses allowed to 5.
|
||||
165. Make sure an email can only be selected when it has been validated.
|
||||
166. Remove the entire "New primary email address" block; keep only selecting an existing alternative as primary.
|
||||
167. Remove the “New primary email address” functionality and keep only selecting an existing alternative as primary.
|
||||
168. Address SA-003 by using a dedicated secret key supplied through a protected environment/secret file, encrypt sensitive values before SQLite storage
|
||||
169. Address SA-004 by validating Mastodon instances as HTTPS public hostnames, rejecting unsafe DNS/IP ranges including mapped IPv6, and blocking redirects
|
||||
170. Implement SA-005: login endpoint lacks rate limiting and lockout
|
||||
171. Address SA-004 by validating Mastodon instances as HTTPS public hostnames, rejecting unsafe DNS/IP ranges including mapped IPv6, and blocking redirects.
|
||||
172. When the user is logged in the webplugin should not display "Please sign in to use LinkLog."
|
||||
173. When the user is signed in the plugin should not display "Please sign in to use LinkLog." and the link to the settings
|
||||
174. The plugin still does not behave as expected. It still shows that the user should sign in.
|
||||
175. In the popup show that the user has logged in.
|
||||
176. Address SA-003 by using a dedicated secret key supplied through a protected environment/secret file, encrypt sensitive values before SQLite storage
|
||||
177. The popup still shows the sign-in block even though the authenticated session text is displayed; show the block only when signed out.
|
||||
178. The authenticated session text and sign-in block are still shown together.
|
||||
179. Use the VIBE directory to log interactions.
|
||||
180. Implement SA-006: remove broad Firefox extension host access and unnecessary tabs permission, request exact configured backend origin access, and keep page capture behind activeTab.
|
||||
181. Continue to document every prompt and chat in the VIBE directory.
|
||||
182. Continue SA-006: store session credentials in the narrowest available extension storage, minimize token lifetime, support refresh-token rotation, and clear all session material on logout or token invalidation.
|
||||
183. Also allow an admin to reset (disable) OTP for any user.
|
||||
183. Fix SA-009: TOTP enrollment has no recovery codes or reset workflow.
|
||||
183. Address SA-007 and use linklog.example.com as the default LINKLOG_PUBLIC_URL.
|
||||
184. Run full backend and frontend test suites.
|
||||
185. Solve SA-010: Avatar validation trusts the client MIME type.
|
||||
186. Fix SA-015: Some destructive and administrative operations lack audit logging.
|
||||
187. Format sent mail in the website style and include the logo.
|
||||
188. Set the email logo to 120px wide and center it at the top.
|
||||
189. Make the email logo 50px by 50px, place it top-left, and put "Hello" to its right in the Asset font.
|
||||
190. Replace the email greeting with "Hello a message from <public hostname>", linking the hostname to the LinkLog server.
|
||||
191. Put the email header text to the right of the logo, align it at the top, and add a comma after Hello.
|
||||
192. Put the email greeting in a separate top-aligned cell to the right of the logo.
|
||||
193. Reduce the email greeting font size somewhat.
|
||||
194. Replace LINKLOG_TOKEN_EXPIRY_DAYS with LINKLOG_TOKEN_EXPIRY_MINUTES, add LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS to production Compose, and add a CI configuration consistency test.
|
||||
195. Perform a new security audit overwriting Security-audit.md with new and remaining issues.
|
||||
195. Update SA-012 and README for the implemented refresh-token lifecycle, revocation behavior, and refresh endpoint.
|
||||
196. Remedy SA-001: migrate logout from JSON token transport to the Authorization bearer header.
|
||||
197. Implement SA-002: replace raw infrastructure errors with redacted server-side logging, request IDs, and stable public reference messages.
|
||||
198. Implement SA-005: reject missing/default/weak production secrets at startup and validate the Fernet encryption key, with configuration tests.
|
||||
199. Fix Firefox manifest compatibility warnings by aligning the minimum version with data collection permissions and session storage support.
|
||||
200. Add a Plugin section to the About page with a download link to the signed XPI file.
|
||||
201. Below the Save profile button, add a link to download the signed plugin if it has not been downloaded yet.
|
||||
202. Check the modified pages for the correct versioned signed XPI link.
|
||||
203. When posting to Mastodon, add an empty line between "From my #LinkLog:" and the title.
|
||||
204. Fix the release workflow because the runner's curl does not support `--fail-with-body`.
|
||||
205. The release action should work differently. Rather than publishing the signed XPI and `updates.json`, it should produce a README describing the project, the latest Docker container version, and the latest signed XPI download URL with version number.
|
||||
206. The tagged version will be the version of the backend. However, the version of the plugin is set manually, just use the most recent signed plugin version that lives in the signed repo.
|
||||
207. Update the VIBE directory with what you have done.
|
||||
|
||||
## Future entries
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
# VIBE
|
||||
|
||||
This code has mostly been vibe coded. For full transparency we maintain a log of prompts and results.
|
||||
|
||||
This folder contains an append-only record of the visible Link Log development conversation.
|
||||
|
||||
- `CHAT_LOG.md` records user requests and assistant responses or outcomes in chronological order.
|
||||
- `PROMPTS.md` records user prompts separately for quick reference.
|
||||
- [`CHAT_LOG.md`](./CHAT_LOG.md) records user requests and assistant responses or outcomes in chronological order.
|
||||
- [`PROMPTS.md`](PROMPTS.md) records user prompts separately for quick reference.
|
||||
|
||||
Only the user-visible conversation is recorded. System, developer, environment, and private tool instructions are intentionally excluded.
|
||||
|
||||
|
||||
@@ -1 +1,4 @@
|
||||
"""LinkLog backend package."""
|
||||
|
||||
# Copyright © 2026 Olaf Kolkman
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
"""Legacy admin page wiring."""
|
||||
|
||||
# Copyright © 2026 Olaf Kolkman
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
|
||||
@@ -1,14 +1,33 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.app.api.dependencies import require_admin
|
||||
from backend.app.database import get_connection, hash_password
|
||||
from backend.app.services.link_service import delete_label
|
||||
from backend.app.services.email_service import (
|
||||
get_smtp_settings,
|
||||
save_smtp_settings,
|
||||
send_test_email,
|
||||
send_verification_email,
|
||||
smtp_configured,
|
||||
)
|
||||
from backend.app.services.email_verification import create_verification_token
|
||||
from backend.app.services.theme_service import THEMES, get_enabled_themes, save_enabled_themes
|
||||
from backend.app.services.secret_store import encrypt_secret
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.services.audit_service import record_audit_event
|
||||
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||
import logging
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AdminPluginUpdate(BaseModel):
|
||||
@@ -27,6 +46,36 @@ class AdminUserUpdate(BaseModel):
|
||||
is_admin: bool
|
||||
|
||||
|
||||
class AdminSmtpUpdate(BaseModel):
|
||||
smtp_host: str
|
||||
smtp_port: int = 587
|
||||
smtp_username: str = ''
|
||||
smtp_password: str = ''
|
||||
smtp_from: str
|
||||
smtp_use_tls: bool = True
|
||||
|
||||
|
||||
class AdminThemesUpdate(BaseModel):
|
||||
themes: list[str]
|
||||
|
||||
|
||||
def validate_smtp_values(payload: AdminSmtpUpdate, current: dict | None = None) -> dict:
|
||||
smtp_host = payload.smtp_host.strip()
|
||||
smtp_from = payload.smtp_from.strip()
|
||||
if not smtp_host or not smtp_from:
|
||||
raise HTTPException(status_code=422, detail='SMTP host and sender address are required')
|
||||
if not 1 <= payload.smtp_port <= 65535:
|
||||
raise HTTPException(status_code=422, detail='SMTP port must be between 1 and 65535')
|
||||
return {
|
||||
'smtp_host': smtp_host,
|
||||
'smtp_port': payload.smtp_port,
|
||||
'smtp_username': payload.smtp_username.strip(),
|
||||
'smtp_password': payload.smtp_password or (current or {}).get('smtp_password', ''),
|
||||
'smtp_from': smtp_from,
|
||||
'smtp_use_tls': payload.smtp_use_tls,
|
||||
}
|
||||
|
||||
|
||||
def public_user(row):
|
||||
return {
|
||||
'id': row['id'],
|
||||
@@ -36,6 +85,7 @@ def public_user(row):
|
||||
'avatar_url': row['avatar_url'],
|
||||
'bio': row['bio'],
|
||||
'created_at': row['created_at'],
|
||||
'email_verified': bool(row['email_verified']),
|
||||
}
|
||||
|
||||
|
||||
@@ -43,13 +93,29 @@ def public_user(row):
|
||||
def list_users(_: dict = Depends(require_admin)):
|
||||
with get_connection() as conn:
|
||||
rows = conn.execute(
|
||||
'SELECT id, username, email, is_admin, avatar_url, bio, created_at FROM users ORDER BY username'
|
||||
'SELECT id, username, email, is_admin, avatar_url, bio, created_at, email_verified FROM users ORDER BY username'
|
||||
).fetchall()
|
||||
return [public_user(row) for row in rows]
|
||||
|
||||
|
||||
@router.post('/users/{user_id}/otp/reset')
|
||||
def reset_user_otp(user_id: str, current_user: dict = Depends(require_admin)):
|
||||
with get_connection() as conn:
|
||||
target = conn.execute('SELECT id FROM users WHERE id = ?', (user_id,)).fetchone()
|
||||
if target is None:
|
||||
raise HTTPException(status_code=404, detail='User not found')
|
||||
conn.execute(
|
||||
'UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
(user_id,),
|
||||
)
|
||||
conn.execute('DELETE FROM otp_recovery_codes WHERE user_id = ?', (user_id,))
|
||||
conn.commit()
|
||||
record_audit_event(current_user['id'], 'otp_reset', 'user', user_id)
|
||||
return {'status': 'otp_reset', 'enabled': False, 'user_id': user_id}
|
||||
|
||||
|
||||
@router.post('/users', status_code=201)
|
||||
def create_user(payload: AdminUserCreate, _: dict = Depends(require_admin)):
|
||||
def create_user(payload: AdminUserCreate, request: Request, current_user: dict = Depends(require_admin)):
|
||||
username = payload.username.strip()
|
||||
email = payload.email.strip()
|
||||
if not username or not email or len(payload.password) < 8:
|
||||
@@ -59,8 +125,8 @@ def create_user(payload: AdminUserCreate, _: dict = Depends(require_admin)):
|
||||
try:
|
||||
cursor = conn.execute(
|
||||
'''
|
||||
INSERT INTO users (id, username, email, password_hash, is_admin)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
INSERT INTO users (id, username, email, password_hash, is_admin, email_verified)
|
||||
VALUES (?, ?, ?, ?, ?, 0)
|
||||
''',
|
||||
(str(uuid4()), username, email, hash_password(payload.password), int(payload.is_admin)),
|
||||
)
|
||||
@@ -71,17 +137,114 @@ def create_user(payload: AdminUserCreate, _: dict = Depends(require_admin)):
|
||||
raise
|
||||
|
||||
row = conn.execute(
|
||||
'SELECT id, username, email, is_admin, avatar_url, bio, created_at FROM users WHERE rowid = last_insert_rowid()'
|
||||
'SELECT id, username, email, is_admin, avatar_url, bio, created_at, email_verified FROM users WHERE rowid = last_insert_rowid()'
|
||||
).fetchone()
|
||||
token = create_verification_token(row['id'])
|
||||
verification_url = f'{settings.public_url}/api/auth/verify-email?token={token}'
|
||||
if smtp_configured():
|
||||
try:
|
||||
send_verification_email(row['email'], row['username'], verification_url)
|
||||
except Exception as error:
|
||||
logger.error('User verification email failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||
raise HTTPException(status_code=503, detail=public_error(request, 'User created but verification email could not be sent.')) from error
|
||||
record_audit_event(current_user['id'], 'user_created', 'user', row['id'], details={'is_admin': bool(payload.is_admin)})
|
||||
return public_user(row)
|
||||
|
||||
|
||||
def public_smtp_settings(values: dict) -> dict:
|
||||
return {
|
||||
'smtp_host': values['smtp_host'],
|
||||
'smtp_port': values['smtp_port'],
|
||||
'smtp_username': values['smtp_username'],
|
||||
'smtp_from': values['smtp_from'],
|
||||
'smtp_use_tls': values['smtp_use_tls'],
|
||||
'password_configured': bool(values['smtp_password']),
|
||||
}
|
||||
|
||||
|
||||
@router.get('/smtp')
|
||||
def get_admin_smtp_settings(_: dict = Depends(require_admin)):
|
||||
return public_smtp_settings(get_smtp_settings())
|
||||
|
||||
|
||||
@router.get('/themes')
|
||||
def get_admin_themes(_: dict = Depends(require_admin)):
|
||||
return {'themes': THEMES, 'enabled': get_enabled_themes()}
|
||||
|
||||
|
||||
@router.put('/themes')
|
||||
def update_admin_themes(payload: AdminThemesUpdate, current_user: dict = Depends(require_admin)):
|
||||
try:
|
||||
enabled = save_enabled_themes(payload.themes)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=422, detail=str(error)) from error
|
||||
record_audit_event(current_user['id'], 'themes_updated', 'application', details={'themes': enabled})
|
||||
return {'themes': THEMES, 'enabled': enabled}
|
||||
|
||||
|
||||
@router.put('/smtp')
|
||||
def update_admin_smtp_settings(payload: AdminSmtpUpdate, current_user: dict = Depends(require_admin)):
|
||||
current = get_smtp_settings()
|
||||
values = validate_smtp_values(payload, current)
|
||||
save_smtp_settings(values)
|
||||
record_audit_event(current_user['id'], 'smtp_settings_updated', 'application', details={'host': values['smtp_host'], 'port': values['smtp_port'], 'username': values['smtp_username'], 'tls': values['smtp_use_tls']})
|
||||
return public_smtp_settings(values)
|
||||
|
||||
|
||||
@router.post('/smtp/test')
|
||||
def validate_admin_smtp(payload: AdminSmtpUpdate, request: Request, current_user: dict = Depends(require_admin)):
|
||||
values = validate_smtp_values(payload, get_smtp_settings())
|
||||
now = datetime.now(timezone.utc)
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',)).fetchone()
|
||||
rate = json.loads(row['value']) if row else {}
|
||||
last_sent = datetime.fromisoformat(rate['last_sent']) if rate.get('last_sent') else None
|
||||
cooldown_until = datetime.fromisoformat(rate['cooldown_until']) if rate.get('cooldown_until') else None
|
||||
if cooldown_until and now >= cooldown_until:
|
||||
rate = {}
|
||||
last_sent = None
|
||||
cooldown_until = None
|
||||
if cooldown_until and now < cooldown_until:
|
||||
retry_after = int((cooldown_until - now).total_seconds()) + 1
|
||||
raise HTTPException(status_code=429, detail=f'SMTP validation limit reached. Try again in {retry_after} seconds.', headers={'Retry-After': str(retry_after)})
|
||||
if last_sent and now - last_sent < timedelta(seconds=20):
|
||||
retry_after = int((timedelta(seconds=20) - (now - last_sent)).total_seconds()) + 1
|
||||
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before sending another validation email.', headers={'Retry-After': str(retry_after)})
|
||||
try:
|
||||
send_test_email(current_user['email'], values)
|
||||
except Exception as error:
|
||||
logger.error('SMTP validation failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||
raise HTTPException(status_code=503, detail=public_error(request, 'SMTP validation failed.')) from error
|
||||
sends = int(rate.get('sends', 0)) + 1
|
||||
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
|
||||
if sends >= 5:
|
||||
updated_rate['cooldown_until'] = (now + timedelta(minutes=2)).isoformat()
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||
('admin_smtp_mail_rate', json.dumps(updated_rate)),
|
||||
)
|
||||
conn.commit()
|
||||
next_allowed = datetime.fromisoformat(updated_rate.get('cooldown_until')) if sends >= 5 else now + timedelta(seconds=20)
|
||||
return {
|
||||
'status': 'sent',
|
||||
'message': f'SMTP validation email sent to {current_user["email"]}.',
|
||||
'sends_remaining': max(0, 5 - sends),
|
||||
'cooldown_seconds': 120 if sends >= 5 else 0,
|
||||
'next_allowed_at': next_allowed.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.put('/users/{user_id}')
|
||||
def update_user_privileges(
|
||||
user_id: str,
|
||||
payload: AdminUserUpdate,
|
||||
_: dict = Depends(require_admin),
|
||||
current_user: dict = Depends(require_admin),
|
||||
):
|
||||
if user_id == current_user['id']:
|
||||
raise HTTPException(status_code=400, detail='You cannot change your own administrator status')
|
||||
|
||||
with get_connection() as conn:
|
||||
target = conn.execute(
|
||||
'SELECT id, is_admin FROM users WHERE id = ?',
|
||||
@@ -103,9 +266,10 @@ def update_user_privileges(
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute(
|
||||
'SELECT id, username, email, is_admin, avatar_url, bio, created_at FROM users WHERE id = ?',
|
||||
'SELECT id, username, email, is_admin, avatar_url, bio, created_at, email_verified FROM users WHERE id = ?',
|
||||
(user_id,),
|
||||
).fetchone()
|
||||
record_audit_event(current_user['id'], 'user_privileges_updated', 'user', user_id, details={'is_admin': bool(payload.is_admin)})
|
||||
return public_user(row)
|
||||
|
||||
|
||||
@@ -123,15 +287,20 @@ def delete_user(user_id: str, current_user: dict = Depends(require_admin)):
|
||||
if admins <= 1:
|
||||
raise HTTPException(status_code=400, detail='Cannot delete the last administrator')
|
||||
|
||||
conn.execute('DELETE FROM tokens WHERE user_id = ?', (user_id,))
|
||||
conn.execute('DELETE FROM user_plugin_config WHERE user_id = ?', (user_id,))
|
||||
conn.execute('DELETE FROM links WHERE user_id = ?', (user_id,))
|
||||
conn.execute('DELETE FROM users WHERE id = ?', (user_id,))
|
||||
conn.commit()
|
||||
record_audit_event(current_user['id'], 'user_deleted', 'user', user_id)
|
||||
return {'status': 'deleted', 'id': user_id}
|
||||
|
||||
|
||||
@router.delete('/labels/{label_id}')
|
||||
def admin_delete_label(label_id: str, _: dict = Depends(require_admin)):
|
||||
def admin_delete_label(label_id: str, current_user: dict = Depends(require_admin)):
|
||||
if not delete_label(label_id, is_admin=True):
|
||||
raise HTTPException(status_code=404, detail='Label not found')
|
||||
record_audit_event(current_user['id'], 'label_deleted', 'label', label_id)
|
||||
return {'status': 'deleted', 'id': label_id}
|
||||
|
||||
|
||||
@@ -190,7 +359,7 @@ def get_plugin(plugin_name: str, _: dict = Depends(require_admin)):
|
||||
def update_plugin(
|
||||
plugin_name: str,
|
||||
payload: AdminPluginUpdate,
|
||||
_: dict = Depends(require_admin),
|
||||
current_user: dict = Depends(require_admin),
|
||||
):
|
||||
with get_connection() as conn:
|
||||
current = conn.execute(
|
||||
@@ -205,6 +374,9 @@ def update_plugin(
|
||||
config = json.loads(current['config']) if current['config'] else {}
|
||||
if payload.config is not None:
|
||||
config.update(payload.config)
|
||||
for secret_name in ('access_token', 'client_secret', 'smtp_password'):
|
||||
if config.get(secret_name):
|
||||
config[secret_name] = encrypt_secret(config[secret_name])
|
||||
|
||||
conn.execute(
|
||||
'''
|
||||
@@ -216,6 +388,7 @@ def update_plugin(
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
record_audit_event(current_user['id'], 'plugin_updated', 'plugin', plugin_name, details={'enabled': enabled})
|
||||
return {
|
||||
'name': plugin_name,
|
||||
'enabled': enabled,
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.app.api.dependencies import get_current_user
|
||||
from backend.app.database import get_connection, init_db
|
||||
from backend.app.services.auth_service import authenticate_user
|
||||
from backend.app.services.token_service import issue_token, revoke_token, validate_token
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.services.auth_service import authenticate_user, find_user
|
||||
from backend.app.services.email_service import send_password_reset_email, smtp_configured
|
||||
from backend.app.services.email_verification import verify_email
|
||||
from backend.app.services.password_reset import create_reset_token, reset_password
|
||||
from backend.app.services.token_service import issue_token, revoke_token, rotate_refresh_token, validate_token
|
||||
from backend.app.services.otp_service import verify_code
|
||||
from backend.app.services.secret_store import decrypt_secret
|
||||
from backend.app.services.email_addresses import verify_user_email_address
|
||||
from backend.app.services.login_throttle import check_login_allowed, clear_login_failures, record_login_failure
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -13,31 +25,106 @@ init_db()
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
email: str
|
||||
password: str
|
||||
otp: str | None = None
|
||||
device_id: str | None = None
|
||||
|
||||
|
||||
class RefreshTokenRequest(BaseModel):
|
||||
refresh_token: str
|
||||
device_id: str | None = None
|
||||
|
||||
|
||||
class PasswordResetRequest(BaseModel):
|
||||
token: str
|
||||
password: str
|
||||
|
||||
|
||||
@router.post('/login')
|
||||
def login(payload: LoginRequest):
|
||||
user = authenticate_user(payload.username, payload.password)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail='Invalid username or password')
|
||||
def login(payload: LoginRequest, request: Request):
|
||||
email = payload.email.strip()
|
||||
ip_address = request.client.host if request.client else 'unknown'
|
||||
retry_after = check_login_allowed(ip_address, email)
|
||||
if retry_after is not None:
|
||||
raise HTTPException(status_code=429, detail='Too many failed login attempts. Try again later.', headers={'Retry-After': str(retry_after)})
|
||||
|
||||
token_data = issue_token(user['id'], user['username'])
|
||||
user = authenticate_user(email, payload.password)
|
||||
if user is None:
|
||||
record_login_failure(ip_address, email)
|
||||
reset_user = find_user(email)
|
||||
if reset_user and reset_user['email_verified'] and smtp_configured():
|
||||
try:
|
||||
token = create_reset_token(reset_user['id'])
|
||||
reset_url = f'{settings.public_url}/reset-password?token={token}'
|
||||
send_password_reset_email(reset_user['email'], reset_user['username'], reset_url)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(status_code=401, detail='Invalid username or password')
|
||||
if not user['email_verified']:
|
||||
raise HTTPException(status_code=403, detail='Email address is not verified')
|
||||
if user['otp_enabled'] and not verify_code(decrypt_secret(user['otp_secret']), payload.otp):
|
||||
record_login_failure(ip_address, email)
|
||||
raise HTTPException(status_code=401, detail='One-time password required or invalid')
|
||||
|
||||
clear_login_failures(ip_address, email)
|
||||
token_data = issue_token(user['id'], user['username'], payload.device_id)
|
||||
return {
|
||||
'access_token': token_data['access_token'],
|
||||
'token_type': 'bearer',
|
||||
'expires_at': token_data['expires_at'],
|
||||
'refresh_token': token_data['refresh_token'],
|
||||
'user': {'id': user['id'], 'username': user['username'], 'email': user['email']}
|
||||
'device_id': token_data['device_id'],
|
||||
'user': {'id': user['id'], 'username': user['username'], 'email': user['email'], 'otp_enabled': bool(user['otp_enabled'])}
|
||||
}
|
||||
|
||||
|
||||
@router.post('/refresh')
|
||||
def refresh_token_endpoint(payload: RefreshTokenRequest):
|
||||
rotated = rotate_refresh_token(payload.refresh_token, payload.device_id)
|
||||
if rotated is None:
|
||||
raise HTTPException(status_code=401, detail='Refresh token is invalid, expired, or bound to another device')
|
||||
return {
|
||||
'access_token': rotated['access_token'],
|
||||
'token_type': 'bearer',
|
||||
'expires_at': rotated['expires_at'],
|
||||
'refresh_token': rotated['refresh_token'],
|
||||
'device_id': rotated['device_id'],
|
||||
'user': {'id': rotated['user_id'], 'username': rotated['username']},
|
||||
}
|
||||
|
||||
|
||||
@router.get('/verify-email')
|
||||
def verify_email_address(token: str):
|
||||
if not verify_email(token):
|
||||
raise HTTPException(status_code=400, detail='Verification link is invalid or expired')
|
||||
return {'status': 'verified', 'message': 'Email address verified. You can now sign in.'}
|
||||
|
||||
|
||||
@router.get('/verify-additional-email')
|
||||
def verify_additional_email_address(token: str):
|
||||
if not verify_user_email_address(token):
|
||||
raise HTTPException(status_code=400, detail='Email verification link is invalid or expired')
|
||||
return {'status': 'verified', 'message': 'Email address verified. You can now sign in.'}
|
||||
|
||||
|
||||
|
||||
@router.post('/reset-password')
|
||||
def reset_password_endpoint(payload: PasswordResetRequest):
|
||||
if len(payload.password) < 8:
|
||||
raise HTTPException(status_code=422, detail='Password must contain at least 8 characters')
|
||||
if not reset_password(payload.token, payload.password):
|
||||
raise HTTPException(status_code=400, detail='Password reset link is invalid or expired')
|
||||
return {'status': 'password_reset', 'message': 'Password reset. You can now sign in.'}
|
||||
|
||||
|
||||
@router.post('/logout')
|
||||
def logout(payload: dict):
|
||||
token = payload.get('token')
|
||||
def logout(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')
|
||||
token = authorization.replace('Bearer ', '', 1).strip()
|
||||
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)
|
||||
if not revoked:
|
||||
raise HTTPException(status_code=404, detail='Token not found or already revoked')
|
||||
@@ -45,14 +132,7 @@ def logout(payload: dict):
|
||||
|
||||
|
||||
@router.get('/me')
|
||||
def current_user(token: str):
|
||||
info = validate_token(token)
|
||||
if info is None:
|
||||
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
||||
with get_connection() as conn:
|
||||
user = conn.execute('SELECT * FROM users WHERE id = ?', (info['user_id'],)).fetchone()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=404, detail='User not found')
|
||||
def current_user(user: dict = Depends(get_current_user)):
|
||||
return {
|
||||
'id': user['id'],
|
||||
'username': user['username'],
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
from fastapi import APIRouter, Header, HTTPException, status
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import json
|
||||
from fastapi import APIRouter, Header, HTTPException, Response, status
|
||||
import logging
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.app.services.link_service import create_link, list_public_links, list_tags, update_link
|
||||
from backend.app.services.link_service import create_link, delete_link, find_owned_link_by_title_url, get_link_tags, get_owned_link, list_public_links, list_tags, mark_mastodon_posted, update_link
|
||||
from backend.app.database import get_connection
|
||||
from backend.app.services.plugin_manager import plugin_manager
|
||||
from backend.app.services.token_service import validate_token
|
||||
from backend.app.services.audit_service import record_audit_event
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LinkCreate(BaseModel):
|
||||
@@ -28,8 +36,23 @@ def available_tags():
|
||||
return list_tags()
|
||||
|
||||
|
||||
@router.get('/links/check')
|
||||
def check_existing_link(
|
||||
title: str,
|
||||
url: str,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
if not authorization or not authorization.startswith('Bearer '):
|
||||
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||
info = validate_token(authorization.replace('Bearer ', '', 1))
|
||||
if info is None:
|
||||
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
||||
record = find_owned_link_by_title_url(info['user_id'], title, url)
|
||||
return {'exists': record is not None}
|
||||
|
||||
|
||||
@router.post('/links', status_code=status.HTTP_201_CREATED)
|
||||
def create_link_endpoint(payload: LinkCreate, authorization: str | None = Header(default=None)):
|
||||
def create_link_endpoint(payload: LinkCreate, response: Response, authorization: str | None = Header(default=None)):
|
||||
if not authorization or not authorization.startswith('Bearer '):
|
||||
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||
token = authorization.replace('Bearer ', '', 1)
|
||||
@@ -38,11 +61,28 @@ def create_link_endpoint(payload: LinkCreate, authorization: str | None = Header
|
||||
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
||||
|
||||
try:
|
||||
record = create_link(info['user_id'], payload.title, payload.url, payload.comment, payload.timestamp, payload.tags)
|
||||
record = find_owned_link_by_title_url(info['user_id'], payload.title, payload.url)
|
||||
duplicate = record is not None
|
||||
if duplicate:
|
||||
record = update_link(record['id'], info['user_id'], payload.title, payload.url, payload.comment, payload.tags)
|
||||
else:
|
||||
record = create_link(info['user_id'], payload.title, payload.url, payload.comment, payload.timestamp, payload.tags)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=422, detail=str(error)) from error
|
||||
plugin_manager.dispatch({'type': 'link_created', **record})
|
||||
return record
|
||||
if duplicate:
|
||||
response.status_code = status.HTTP_200_OK
|
||||
plugin_results = plugin_manager.dispatch({'type': 'link_created', **record})
|
||||
mastodon_result = next((result for result in plugin_results if result.get('plugin') == 'mastodon'), None)
|
||||
if mastodon_result and mastodon_result.get('status') == 'posted':
|
||||
mark_mastodon_posted(record['id'], info['user_id'], mastodon_result.get('post_id'))
|
||||
if any(result.get('status') == 'failed' for result in plugin_results):
|
||||
logger.warning('One or more plugins failed for link_id=%s results=%s', record['id'], plugin_results)
|
||||
plugin_errors = [
|
||||
{'plugin': result.get('plugin', 'unknown'), 'reason': result.get('reason', 'Plugin failed')}
|
||||
for result in plugin_results
|
||||
if result.get('status') == 'failed'
|
||||
]
|
||||
return {**record, 'duplicate': duplicate, 'plugin_errors': plugin_errors}
|
||||
|
||||
|
||||
@router.put('/links/{link_id}')
|
||||
@@ -66,6 +106,59 @@ def update_link_endpoint(
|
||||
return record
|
||||
|
||||
|
||||
@router.delete('/links/{link_id}')
|
||||
def delete_link_endpoint(
|
||||
link_id: str,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
if not authorization or not authorization.startswith('Bearer '):
|
||||
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||
info = validate_token(authorization.replace('Bearer ', '', 1))
|
||||
if info is None:
|
||||
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
||||
link = get_owned_link(link_id, info['user_id'])
|
||||
if link is None:
|
||||
raise HTTPException(status_code=404, detail='Link not found or not owned by user')
|
||||
post_ids = json.loads(link['mastodon_post_ids']) if link.get('mastodon_post_ids') else []
|
||||
if not post_ids and link.get('mastodon_post_id'):
|
||||
post_ids = [link['mastodon_post_id']]
|
||||
if post_ids:
|
||||
result = plugin_manager.delete_mastodon_posts({**link, 'mastodon_post_ids': post_ids})
|
||||
if result.get('status') != 'deleted':
|
||||
raise HTTPException(status_code=502, detail=result.get('reason', 'Could not delete Mastodon posts'))
|
||||
if not delete_link(link_id, info['user_id']):
|
||||
raise HTTPException(status_code=404, detail='Link not found or not owned by user')
|
||||
record_audit_event(info['user_id'], 'link_deleted', 'link', link_id)
|
||||
return {'status': 'deleted', 'id': link_id}
|
||||
|
||||
|
||||
@router.post('/links/{link_id}/mastodon')
|
||||
def post_link_to_mastodon(
|
||||
link_id: str,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
if not authorization or not authorization.startswith('Bearer '):
|
||||
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||
info = validate_token(authorization.replace('Bearer ', '', 1))
|
||||
if info is None:
|
||||
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT * FROM links WHERE id = ? AND user_id = ?', (link_id, info['user_id'])).fetchone()
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail='Link not found or not owned by user')
|
||||
event = dict(row)
|
||||
with get_connection() as conn:
|
||||
event['tags'] = get_link_tags(conn, link_id)
|
||||
result = plugin_manager.post_to_mastodon({'type': 'link_created', **event})
|
||||
if result.get('status') == 'posted':
|
||||
mark_mastodon_posted(link_id, info['user_id'], result.get('post_id'))
|
||||
record_audit_event(info['user_id'], 'mastodon_posted', 'link', link_id)
|
||||
return {'status': 'posted', 'post_id': result.get('post_id')}
|
||||
if result.get('status') == 'skipped':
|
||||
raise HTTPException(status_code=409, detail='Mastodon is not enabled or configured')
|
||||
raise HTTPException(status_code=502, detail=result.get('reason', 'Mastodon post failed'))
|
||||
|
||||
|
||||
@router.get('/links')
|
||||
def list_links():
|
||||
return list_public_links()
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from urllib.parse import quote
|
||||
from urllib.error import HTTPError
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import RedirectResponse
|
||||
from starlette.requests import Request
|
||||
|
||||
from backend.app.api.dependencies import get_current_user
|
||||
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()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get('/oauth/start')
|
||||
def oauth_start(request: Request, instance: str = 'mastodon.social', user: dict = Depends(get_current_user)):
|
||||
try:
|
||||
authorization_url = start_authorization(user['id'], instance)
|
||||
except HTTPError as error:
|
||||
retry_after = error.headers.get('Retry-After') if error.headers else None
|
||||
headers = {'Retry-After': retry_after} if retry_after else None
|
||||
raise HTTPException(
|
||||
status_code=error.code,
|
||||
detail=f'Mastodon returned HTTP {error.code} while registering LinkLog. Try again later.',
|
||||
headers=headers,
|
||||
) from error
|
||||
except Exception as 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}
|
||||
|
||||
|
||||
@router.get('/oauth/callback')
|
||||
def oauth_callback(request: Request, code: str | None = None, state: str | None = None, error: str | None = None):
|
||||
if error or not code or not state:
|
||||
return RedirectResponse(f'/profile?mastodon_error={quote(error or "Authorization was cancelled")}')
|
||||
try:
|
||||
finish_authorization(code, state)
|
||||
except Exception as 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')
|
||||
@@ -1,8 +1,12 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
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.theme_service import THEMES, get_enabled_themes
|
||||
|
||||
router = APIRouter()
|
||||
optional_bearer = HTTPBearer(auto_error=False)
|
||||
@@ -13,6 +17,12 @@ def public_users():
|
||||
return list_public_users()
|
||||
|
||||
|
||||
@router.get('/themes')
|
||||
def public_themes():
|
||||
enabled = get_enabled_themes()
|
||||
return [{'id': theme, **THEMES[theme]} for theme in enabled]
|
||||
|
||||
|
||||
@router.get('/feed')
|
||||
@router.get('/feed/{username}')
|
||||
def public_feed(
|
||||
@@ -40,6 +50,7 @@ def public_feed(
|
||||
'is_owner': item['user_id'] == current_user_id,
|
||||
'can_edit': item['user_id'] == current_user_id,
|
||||
'created_at': item['created_at'],
|
||||
'mastodon_posted': bool(item['mastodon_posted']),
|
||||
}
|
||||
for item in items
|
||||
]
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
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, save_smtp_settings, send_test_email
|
||||
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||
import logging
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SetupRequest(BaseModel):
|
||||
username: str
|
||||
email: str
|
||||
password: str
|
||||
smtp_host: str
|
||||
smtp_port: int = 587
|
||||
smtp_username: str = ''
|
||||
smtp_password: str = ''
|
||||
smtp_from: str
|
||||
smtp_use_tls: bool = True
|
||||
|
||||
|
||||
class TestMailRequest(BaseModel):
|
||||
email: str | None = None
|
||||
|
||||
|
||||
def has_administrator() -> bool:
|
||||
with get_connection() as conn:
|
||||
return conn.execute('SELECT 1 FROM users WHERE is_admin = 1 LIMIT 1').fetchone() is not None
|
||||
|
||||
|
||||
def get_pending_setup() -> dict | None:
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('setup_pending',)).fetchone()
|
||||
return json.loads(row['value']) if row else None
|
||||
|
||||
|
||||
def save_pending_setup(values: dict) -> None:
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||
('setup_pending', json.dumps(values)),
|
||||
)
|
||||
conn.execute('DELETE FROM app_settings WHERE name = ?', ('setup_mail_rate',))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def delete_pending_setup() -> None:
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM app_settings WHERE name = ?', ('setup_pending',))
|
||||
conn.execute('DELETE FROM app_settings WHERE name = ?', ('setup_mail_rate',))
|
||||
conn.commit()
|
||||
|
||||
|
||||
@router.post('/configuration', status_code=200)
|
||||
def save_configuration(payload: SetupRequest):
|
||||
if has_administrator():
|
||||
raise HTTPException(status_code=409, detail='LinkLog is already configured')
|
||||
username = payload.username.strip()
|
||||
email = payload.email.strip()
|
||||
smtp_host = payload.smtp_host.strip()
|
||||
smtp_from = payload.smtp_from.strip()
|
||||
if not username or not email or not smtp_host or not smtp_from or len(payload.password) < 8:
|
||||
raise HTTPException(status_code=422, detail='Admin credentials and SMTP settings are required')
|
||||
if not 1 <= payload.smtp_port <= 65535:
|
||||
raise HTTPException(status_code=422, detail='SMTP port must be between 1 and 65535')
|
||||
|
||||
smtp_values = {
|
||||
'smtp_host': smtp_host,
|
||||
'smtp_port': payload.smtp_port,
|
||||
'smtp_username': payload.smtp_username.strip(),
|
||||
'smtp_password': payload.smtp_password,
|
||||
'smtp_from': smtp_from,
|
||||
'smtp_use_tls': payload.smtp_use_tls,
|
||||
}
|
||||
pending = {
|
||||
'username': username,
|
||||
'email': email,
|
||||
'password_hash': hash_password(payload.password),
|
||||
}
|
||||
save_pending_setup(pending)
|
||||
save_smtp_settings(smtp_values)
|
||||
return {'status': 'saved', 'message': 'Configuration saved. Send a test mail to verify SMTP delivery.'}
|
||||
|
||||
|
||||
@router.post('/test-mail')
|
||||
def test_mail(request: Request, payload: TestMailRequest | None = None):
|
||||
if has_administrator():
|
||||
raise HTTPException(status_code=409, detail='LinkLog is already configured')
|
||||
pending = get_pending_setup()
|
||||
if pending is None:
|
||||
raise HTTPException(status_code=400, detail='Save the configuration before sending test mail')
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('setup_mail_rate',)).fetchone()
|
||||
rate = json.loads(row['value']) if row else {}
|
||||
last_sent = datetime.fromisoformat(rate['last_sent']) if rate.get('last_sent') else None
|
||||
cooldown_until = datetime.fromisoformat(rate['cooldown_until']) if rate.get('cooldown_until') else None
|
||||
if cooldown_until and now >= cooldown_until:
|
||||
rate = {}
|
||||
last_sent = None
|
||||
cooldown_until = None
|
||||
if cooldown_until and now < cooldown_until:
|
||||
retry_after = int((cooldown_until - now).total_seconds()) + 1
|
||||
raise HTTPException(status_code=429, detail=f'Test mail limit reached. Try again in {retry_after} seconds.', headers={'Retry-After': str(retry_after)})
|
||||
if last_sent and now - last_sent < timedelta(seconds=20):
|
||||
retry_after = int((timedelta(seconds=20) - (now - last_sent)).total_seconds()) + 1
|
||||
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before sending another test mail.', headers={'Retry-After': str(retry_after)})
|
||||
|
||||
try:
|
||||
send_test_email(payload.email if payload and payload.email else pending['email'])
|
||||
except Exception as 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
|
||||
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
|
||||
if sends >= 5:
|
||||
updated_rate['cooldown_until'] = (now + timedelta(minutes=2)).isoformat()
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||
('setup_mail_rate', json.dumps(updated_rate)),
|
||||
)
|
||||
conn.commit()
|
||||
next_allowed = datetime.fromisoformat(updated_rate.get('cooldown_until')) if sends >= 5 else now + timedelta(seconds=20)
|
||||
return {
|
||||
'status': 'sent',
|
||||
'message': 'SMTP test mail sent.',
|
||||
'sends_remaining': max(0, 5 - sends),
|
||||
'cooldown_seconds': 120 if sends >= 5 else 0,
|
||||
'next_allowed_at': next_allowed.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.post('/complete', status_code=201)
|
||||
def complete_setup():
|
||||
if has_administrator():
|
||||
raise HTTPException(status_code=409, detail='LinkLog is already configured')
|
||||
pending = get_pending_setup()
|
||||
if pending is None:
|
||||
raise HTTPException(status_code=400, detail='Save the configuration before completing setup')
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('setup_mail_rate',)).fetchone()
|
||||
if row is None or int(json.loads(row['value']).get('sends', 0)) < 1:
|
||||
raise HTTPException(status_code=400, detail='Send a successful test mail before completing setup')
|
||||
user_id = str(uuid4())
|
||||
with get_connection() as conn:
|
||||
try:
|
||||
conn.execute(
|
||||
'''INSERT INTO users
|
||||
(id, username, email, password_hash, is_admin, email_verified)
|
||||
VALUES (?, ?, ?, ?, 1, 1)''',
|
||||
(user_id, pending['username'], pending['email'], pending['password_hash']),
|
||||
)
|
||||
conn.commit()
|
||||
except Exception as error:
|
||||
raise HTTPException(status_code=409, detail='Username or email already exists') from error
|
||||
delete_pending_setup()
|
||||
return {'status': 'configured', 'message': 'LinkLog is configured.'}
|
||||
|
||||
|
||||
@router.get('/status')
|
||||
def setup_status():
|
||||
rate = {}
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('setup_mail_rate',)).fetchone()
|
||||
if row:
|
||||
rate = json.loads(row['value'])
|
||||
now = datetime.now(timezone.utc)
|
||||
cooldown_until = datetime.fromisoformat(rate['cooldown_until']) if rate.get('cooldown_until') else None
|
||||
last_sent = datetime.fromisoformat(rate['last_sent']) if rate.get('last_sent') else None
|
||||
next_allowed = cooldown_until if cooldown_until and cooldown_until > now else (
|
||||
last_sent + timedelta(seconds=20) if last_sent else None
|
||||
)
|
||||
return {
|
||||
'configured': has_administrator(),
|
||||
'pending': get_pending_setup() is not None,
|
||||
'smtp_defaults': get_smtp_settings(),
|
||||
'sends_remaining': max(0, 5 - int(rate.get('sends', 0))),
|
||||
'next_allowed_at': next_allowed.isoformat() if next_allowed and next_allowed > now else None,
|
||||
}
|
||||
@@ -1,18 +1,36 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import json
|
||||
import warnings
|
||||
from io import BytesIO
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.app.api.dependencies import get_current_user
|
||||
from backend.app.database import AVATARS_DIR, get_connection, hash_password
|
||||
from backend.app.database import AVATARS_DIR, get_connection, hash_password, verify_password
|
||||
from backend.app.services.link_service import create_label, delete_label, list_user_labels, update_label
|
||||
from backend.app.services.otp_service import consume_recovery_code, create_recovery_codes, create_secret, provisioning_uri, verify_code
|
||||
from backend.app.services.email_addresses import add_user_email_address, create_email_verification, list_user_email_addresses
|
||||
from backend.app.services.email_service import send_verification_email, smtp_configured
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
|
||||
from backend.app.services.audit_service import record_audit_event
|
||||
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||
import logging
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_AVATAR_BYTES = 2 * 1024 * 1024
|
||||
MAX_AVATAR_PIXELS = 25_000_000
|
||||
|
||||
|
||||
class UserConfigUpdate(BaseModel):
|
||||
email: str | None = None
|
||||
bio: str | None = None
|
||||
|
||||
|
||||
@@ -21,6 +39,23 @@ class PasswordUpdate(BaseModel):
|
||||
new_password: str
|
||||
|
||||
|
||||
class OtpUpdate(BaseModel):
|
||||
action: str
|
||||
code: str | None = None
|
||||
current_password: str | None = None
|
||||
recovery_code: str | None = None
|
||||
|
||||
|
||||
class AdditionalEmail(BaseModel):
|
||||
email: str
|
||||
|
||||
|
||||
class OtpRecovery(BaseModel):
|
||||
current_password: str
|
||||
recovery_code: str
|
||||
|
||||
|
||||
|
||||
class UserPluginConfigUpdate(BaseModel):
|
||||
instance: str | None = None
|
||||
access_token: str | None = None
|
||||
@@ -41,7 +76,10 @@ def get_current_user_profile(user: dict = Depends(get_current_user)):
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail='User not found')
|
||||
return dict(row)
|
||||
profile = dict(row)
|
||||
profile.pop('otp_secret', None)
|
||||
profile.pop('password_hash', None)
|
||||
return profile
|
||||
|
||||
|
||||
@router.put('/me')
|
||||
@@ -54,7 +92,6 @@ def update_current_user_profile(
|
||||
if current is None:
|
||||
raise HTTPException(status_code=404, detail='User not found')
|
||||
|
||||
email = payload.email or current['email']
|
||||
bio = payload.bio if payload.bio is not None else current['bio']
|
||||
|
||||
conn.execute(
|
||||
@@ -63,7 +100,7 @@ def update_current_user_profile(
|
||||
SET email = ?, bio = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
''',
|
||||
(email, bio, user['id']),
|
||||
(current['email'], bio, user['id']),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
@@ -74,7 +111,7 @@ def update_current_user_profile(
|
||||
def update_password(payload: PasswordUpdate, user: dict = Depends(get_current_user)):
|
||||
if len(payload.new_password) < 8:
|
||||
raise HTTPException(status_code=422, detail='New password must be at least 8 characters')
|
||||
if hash_password(payload.current_password) != user['password_hash']:
|
||||
if not verify_password(payload.current_password, user['password_hash']):
|
||||
raise HTTPException(status_code=400, detail='Current password is incorrect')
|
||||
|
||||
with get_connection() as conn:
|
||||
@@ -83,9 +120,188 @@ def update_password(payload: PasswordUpdate, user: dict = Depends(get_current_us
|
||||
(hash_password(payload.new_password), user['id']),
|
||||
)
|
||||
conn.commit()
|
||||
record_audit_event(user['id'], 'password_changed', 'user', user['id'])
|
||||
return {'status': 'password_updated'}
|
||||
|
||||
|
||||
@router.get('/otp')
|
||||
def get_otp(user: dict = Depends(get_current_user)):
|
||||
return {'enabled': bool(user['otp_enabled'])}
|
||||
|
||||
|
||||
@router.post('/otp/setup')
|
||||
def setup_otp(user: dict = Depends(get_current_user)):
|
||||
if user['otp_enabled']:
|
||||
raise HTTPException(status_code=409, detail='One-time password is already enabled')
|
||||
secret = create_secret()
|
||||
with get_connection() as conn:
|
||||
conn.execute('UPDATE users SET otp_secret = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (encrypt_secret(secret), user['id']))
|
||||
conn.commit()
|
||||
record_audit_event(user['id'], 'otp_enrolled', 'user', user['id'])
|
||||
return {
|
||||
'secret': secret,
|
||||
'otpauth_url': provisioning_uri(secret, user['username']),
|
||||
'recovery_codes': create_recovery_codes(user['id']),
|
||||
}
|
||||
|
||||
|
||||
@router.post('/otp')
|
||||
def update_otp(payload: OtpUpdate, user: dict = Depends(get_current_user)):
|
||||
if payload.action not in {'enable', 'disable'}:
|
||||
raise HTTPException(status_code=422, detail='OTP action must be enable or disable')
|
||||
if payload.action == 'disable' and not payload.current_password:
|
||||
raise HTTPException(status_code=400, detail='Current password is required to disable one-time password')
|
||||
if payload.action == 'disable' and not verify_password(payload.current_password, user['password_hash']):
|
||||
raise HTTPException(status_code=400, detail='Current password is incorrect')
|
||||
valid_code = verify_code(decrypt_secret(user['otp_secret']), payload.code)
|
||||
valid_recovery_code = payload.action == 'disable' and payload.recovery_code and consume_recovery_code(user['id'], payload.recovery_code)
|
||||
if not valid_code and not valid_recovery_code:
|
||||
raise HTTPException(status_code=400, detail='Invalid one-time password')
|
||||
with get_connection() as conn:
|
||||
if payload.action == 'enable':
|
||||
conn.execute('UPDATE users SET otp_enabled = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
|
||||
else:
|
||||
conn.execute('UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
|
||||
conn.commit()
|
||||
record_audit_event(user['id'], f'otp_{payload.action}d', 'user', user['id'])
|
||||
return {'status': 'updated', 'enabled': payload.action == 'enable'}
|
||||
|
||||
|
||||
@router.post('/otp/recover')
|
||||
def recover_otp(payload: OtpRecovery, user: dict = Depends(get_current_user)):
|
||||
if not verify_password(payload.current_password, user['password_hash']):
|
||||
raise HTTPException(status_code=400, detail='Current password is incorrect')
|
||||
if not consume_recovery_code(user['id'], payload.recovery_code):
|
||||
raise HTTPException(status_code=400, detail='Recovery code is invalid or already used')
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
(user['id'],),
|
||||
)
|
||||
conn.commit()
|
||||
record_audit_event(user['id'], 'otp_recovered', 'user', user['id'])
|
||||
return {'status': 'otp_recovered', 'enabled': False}
|
||||
|
||||
|
||||
@router.get('/emails')
|
||||
def get_additional_emails(user: dict = Depends(get_current_user)):
|
||||
return [{'email': user['email'], 'verified': bool(user['email_verified']), 'primary': True}] + list_user_email_addresses(user['id'])
|
||||
|
||||
|
||||
@router.post('/emails', status_code=201)
|
||||
def add_additional_email(payload: AdditionalEmail, request: Request, user: dict = Depends(get_current_user)):
|
||||
email = payload.email.strip().lower()
|
||||
if email == user['email'].lower():
|
||||
raise HTTPException(status_code=409, detail='This is already the primary email address')
|
||||
with get_connection() as conn:
|
||||
if conn.execute('SELECT 1 FROM users WHERE lower(email) = ?', (email,)).fetchone():
|
||||
raise HTTPException(status_code=409, detail='Email address already exists')
|
||||
additional_count = conn.execute(
|
||||
'SELECT COUNT(*) AS count FROM user_email_addresses WHERE user_id = ?',
|
||||
(user['id'],),
|
||||
).fetchone()['count']
|
||||
if additional_count >= 5:
|
||||
raise HTTPException(status_code=422, detail='You can add at most five additional email addresses')
|
||||
try:
|
||||
address = add_user_email_address(user['id'], email)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=409, detail=str(error)) from error
|
||||
if smtp_configured():
|
||||
email_address, token = create_email_verification(user['id'], address['id'])
|
||||
verification_url = f'{settings.public_url}/api/auth/verify-additional-email?token={token}'
|
||||
try:
|
||||
send_verification_email(email_address, user['username'], verification_url)
|
||||
except Exception as error:
|
||||
logger.error('Additional email verification failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||
raise HTTPException(status_code=503, detail=public_error(request, 'Email address added but verification email could not be sent.')) from error
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||
(f'email_verify_rate:{address["id"]}', json.dumps({'sends': 1, 'last_sent': datetime.now(timezone.utc).isoformat()})),
|
||||
)
|
||||
conn.commit()
|
||||
return address
|
||||
|
||||
|
||||
@router.post('/emails/{address_id}/resend')
|
||||
def resend_additional_email(address_id: str, request: Request, user: dict = Depends(get_current_user)):
|
||||
now = datetime.now(timezone.utc)
|
||||
setting_name = f'email_verify_rate:{address_id}'
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
|
||||
address = conn.execute('SELECT email, verified FROM user_email_addresses WHERE id = ? AND user_id = ?', (address_id, user['id'])).fetchone()
|
||||
if address is None:
|
||||
raise HTTPException(status_code=404, detail='Email address not found')
|
||||
if address['verified']:
|
||||
raise HTTPException(status_code=409, detail='Email address is already verified')
|
||||
rate = json.loads(row['value']) if row else {}
|
||||
last_sent = datetime.fromisoformat(rate['last_sent']) if rate.get('last_sent') else None
|
||||
cooldown_until = datetime.fromisoformat(rate['cooldown_until']) if rate.get('cooldown_until') else None
|
||||
if cooldown_until and now < cooldown_until:
|
||||
retry_after = int((cooldown_until - now).total_seconds()) + 1
|
||||
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before resending verification email.', headers={'Retry-After': str(retry_after)})
|
||||
if last_sent and now - last_sent < timedelta(seconds=20):
|
||||
retry_after = int((timedelta(seconds=20) - (now - last_sent)).total_seconds()) + 1
|
||||
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before resending verification email.', headers={'Retry-After': str(retry_after)})
|
||||
email, token = create_email_verification(user['id'], address_id)
|
||||
verification_url = f'{settings.public_url}/api/auth/verify-additional-email?token={token}'
|
||||
try:
|
||||
send_verification_email(email, user['username'], verification_url)
|
||||
except Exception as error:
|
||||
logger.error('Verification email resend failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||
raise HTTPException(status_code=503, detail=public_error(request, 'Verification email could not be sent.')) from error
|
||||
sends = int(rate.get('sends', 0)) + 1
|
||||
updated = {'sends': sends, 'last_sent': now.isoformat()}
|
||||
if sends >= 5:
|
||||
updated['cooldown_until'] = (now + timedelta(minutes=2)).isoformat()
|
||||
with get_connection() as conn:
|
||||
conn.execute('''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''', (setting_name, json.dumps(updated)))
|
||||
conn.commit()
|
||||
return {'status': 'sent', 'message': f'Verification email sent to {email}.', 'next_allowed_at': (now + timedelta(seconds=20)).isoformat()}
|
||||
|
||||
|
||||
@router.delete('/emails/{address_id}')
|
||||
def remove_additional_email(address_id: str, user: dict = Depends(get_current_user)):
|
||||
with get_connection() as conn:
|
||||
cursor = conn.execute('DELETE FROM user_email_addresses WHERE id = ? AND user_id = ?', (address_id, user['id']))
|
||||
conn.commit()
|
||||
if cursor.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail='Email address not found')
|
||||
record_audit_event(user['id'], 'email_address_deleted', 'email_address', address_id)
|
||||
return {'status': 'deleted', 'id': address_id}
|
||||
|
||||
|
||||
@router.post('/emails/{address_id}/make-primary')
|
||||
def make_email_primary(address_id: str, user: dict = Depends(get_current_user)):
|
||||
with get_connection() as conn:
|
||||
address = conn.execute(
|
||||
'SELECT email, verified FROM user_email_addresses WHERE id = ? AND user_id = ?',
|
||||
(address_id, user['id']),
|
||||
).fetchone()
|
||||
if address is None:
|
||||
raise HTTPException(status_code=404, detail='Email address not found')
|
||||
if not address['verified']:
|
||||
raise HTTPException(status_code=400, detail='Email address must be validated before it can become primary')
|
||||
old_email = user['email']
|
||||
conn.execute(
|
||||
'DELETE FROM user_email_addresses WHERE id = ? AND user_id = ?',
|
||||
(address_id, user['id']),
|
||||
)
|
||||
conn.execute(
|
||||
'INSERT INTO user_email_addresses (id, user_id, email, verified) VALUES (?, ?, ?, 1)',
|
||||
(str(uuid4()), user['id'], old_email),
|
||||
)
|
||||
conn.execute(
|
||||
'UPDATE users SET email = ?, email_verified = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
(address['email'], user['id']),
|
||||
)
|
||||
conn.commit()
|
||||
record_audit_event(user['id'], 'primary_email_changed', 'user', user['id'])
|
||||
return {'status': 'updated', 'email': address['email']}
|
||||
|
||||
|
||||
@router.get('/labels')
|
||||
def get_labels(user: dict = Depends(get_current_user)):
|
||||
return list_user_labels(user['id'])
|
||||
@@ -114,6 +330,7 @@ def edit_label(label_id: str, payload: LabelUpdate, user: dict = Depends(get_cur
|
||||
def remove_label(label_id: str, user: dict = Depends(get_current_user)):
|
||||
if not delete_label(label_id, user['id']):
|
||||
raise HTTPException(status_code=404, detail='Label not found or not owned by user')
|
||||
record_audit_event(user['id'], 'label_deleted', 'label', label_id)
|
||||
return {'status': 'deleted', 'id': label_id}
|
||||
|
||||
|
||||
@@ -122,25 +339,33 @@ async def upload_avatar(
|
||||
avatar: UploadFile = File(...),
|
||||
user: dict = Depends(get_current_user),
|
||||
):
|
||||
allowed_types = {
|
||||
'image/gif': '.gif',
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
'image/webp': '.webp',
|
||||
}
|
||||
suffix = allowed_types.get(avatar.content_type or '')
|
||||
if suffix is None:
|
||||
if avatar.content_type not in {'image/gif', 'image/jpeg', 'image/png', 'image/webp'}:
|
||||
raise HTTPException(status_code=415, detail='Avatar must be a PNG, JPEG, GIF, or WebP image')
|
||||
|
||||
contents = await avatar.read(2 * 1024 * 1024 + 1)
|
||||
if len(contents) > 2 * 1024 * 1024:
|
||||
contents = await avatar.read(MAX_AVATAR_BYTES + 1)
|
||||
if len(contents) > MAX_AVATAR_BYTES:
|
||||
raise HTTPException(status_code=413, detail='Avatar must be 2 MB or smaller')
|
||||
|
||||
avatar_path = AVATARS_DIR / f'{user["id"]}{suffix}'
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
with Image.open(BytesIO(contents)) as image:
|
||||
if image.width * image.height > MAX_AVATAR_PIXELS:
|
||||
raise HTTPException(status_code=413, detail='Avatar dimensions are too large')
|
||||
image.verify()
|
||||
with Image.open(BytesIO(contents)) as image:
|
||||
image.load()
|
||||
normalized = image.convert('RGBA')
|
||||
except HTTPException:
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning, UnidentifiedImageError, OSError, ValueError) as error:
|
||||
raise HTTPException(status_code=415, detail='Avatar content is not a valid image') from error
|
||||
|
||||
avatar_path = AVATARS_DIR / f'{user["id"]}.png'
|
||||
normalized.save(avatar_path, format='PNG', optimize=True)
|
||||
for existing_path in AVATARS_DIR.glob(f'{user["id"]}.*'):
|
||||
if existing_path != avatar_path:
|
||||
existing_path.unlink(missing_ok=True)
|
||||
avatar_path.write_bytes(contents)
|
||||
avatar_url = f'/media/{avatar_path.name}'
|
||||
|
||||
with get_connection() as conn:
|
||||
@@ -149,6 +374,7 @@ async def upload_avatar(
|
||||
(avatar_url, user['id']),
|
||||
)
|
||||
conn.commit()
|
||||
record_audit_event(user['id'], 'avatar_updated', 'user', user['id'])
|
||||
return {'avatar_url': avatar_url}
|
||||
|
||||
|
||||
@@ -164,6 +390,8 @@ def get_user_plugin_config(plugin_name: str, user: dict = Depends(get_current_us
|
||||
return {}
|
||||
|
||||
config = json.loads(row['config']) if row['config'] else {}
|
||||
if config.get('access_token'):
|
||||
config.pop('access_token')
|
||||
return config
|
||||
|
||||
|
||||
@@ -181,6 +409,8 @@ def update_user_plugin_config(
|
||||
|
||||
current_config = json.loads(current['config']) if current and current['config'] else {}
|
||||
updates = payload.model_dump(exclude_none=True)
|
||||
if updates.get('access_token'):
|
||||
updates['access_token'] = encrypt_secret(updates['access_token'])
|
||||
merged = {**current_config, **updates}
|
||||
|
||||
if current is None:
|
||||
@@ -203,4 +433,6 @@ def update_user_plugin_config(
|
||||
|
||||
conn.commit()
|
||||
|
||||
return merged
|
||||
public_config = dict(merged)
|
||||
public_config.pop('access_token', None)
|
||||
return public_config
|
||||
|
||||
@@ -1,18 +1,47 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
||||
DB_PATH = BASE_DIR / 'data' / 'linklog.db'
|
||||
|
||||
|
||||
def normalize_public_url(value: str) -> str:
|
||||
value = value.strip().rstrip('/')
|
||||
if '://' in value:
|
||||
return value
|
||||
scheme = 'http' if value.startswith(('localhost', '127.0.0.1')) else 'https'
|
||||
return f'{scheme}://{value}'
|
||||
|
||||
|
||||
@dataclass
|
||||
class Settings:
|
||||
app_env: str = os.getenv('APP_ENV', 'development').lower()
|
||||
app_name: str = os.getenv('LINKLOG_APP_NAME', 'LinkLog')
|
||||
version: str = os.getenv('LINKLOG_VERSION', '0.1.0')
|
||||
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')
|
||||
token_expiry_days: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_DAYS', '30'))
|
||||
data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
|
||||
token_expiry_minutes: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_MINUTES', '15'))
|
||||
refresh_token_expiry_days: int = int(os.getenv('LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS', '30'))
|
||||
public_url: str = normalize_public_url(os.getenv('LINKLOG_PUBLIC_URL', 'linklog.example.com'))
|
||||
smtp_host: str = os.getenv('LINKLOG_SMTP_HOST', '')
|
||||
smtp_port: int = int(os.getenv('LINKLOG_SMTP_PORT', '587'))
|
||||
smtp_username: str = os.getenv('LINKLOG_SMTP_USERNAME', '')
|
||||
smtp_password: str = os.getenv('LINKLOG_SMTP_PASSWORD', '')
|
||||
smtp_from: str = os.getenv('LINKLOG_SMTP_FROM', 'LinkLog <no-reply@localhost>')
|
||||
smtp_use_tls: bool = os.getenv('LINKLOG_SMTP_USE_TLS', 'true').lower() in {'1', 'true', 'yes'}
|
||||
email_verification_expiry_hours: int = int(os.getenv('LINKLOG_EMAIL_VERIFICATION_EXPIRY_HOURS', '24'))
|
||||
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_oauth_expiry_minutes: int = int(os.getenv('LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES', '10'))
|
||||
log_level: str = os.getenv('LINKLOG_LOG_LEVEL', 'INFO').upper()
|
||||
tracking_params: list[str] = None
|
||||
|
||||
def __post_init__(self):
|
||||
@@ -33,3 +62,19 @@ class 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)}'
|
||||
@@ -1,3 +1,6 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import sha256
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import sqlite3
|
||||
import os
|
||||
from hashlib import sha256
|
||||
from hashlib import scrypt, sha256
|
||||
import hmac
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -12,7 +16,28 @@ AVATARS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return sha256(password.encode('utf-8')).hexdigest()
|
||||
salt = os.urandom(16)
|
||||
digest = scrypt(password.encode('utf-8'), salt=salt, n=16_384, r=8, p=1, dklen=32)
|
||||
return f'scrypt$16384$8$1${salt.hex()}${digest.hex()}'
|
||||
|
||||
|
||||
def verify_password(password: str, stored_hash: str) -> bool:
|
||||
if stored_hash.startswith('scrypt$'):
|
||||
try:
|
||||
algorithm, cost, block_size, parallelism, salt_hex, digest_hex = stored_hash.split('$')
|
||||
if algorithm != 'scrypt':
|
||||
return False
|
||||
digest = scrypt(
|
||||
password.encode('utf-8'), salt=bytes.fromhex(salt_hex),
|
||||
n=int(cost), r=int(block_size), p=int(parallelism), dklen=32,
|
||||
)
|
||||
return hmac.compare_digest(digest.hex(), digest_hex)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
if len(stored_hash) == 64:
|
||||
legacy_digest = sha256(password.encode('utf-8')).hexdigest()
|
||||
return hmac.compare_digest(legacy_digest, stored_hash)
|
||||
return False
|
||||
|
||||
DEFAULT_TAGS = ('#Internet', '#Cybersecurity', '#Fediverse', '#Food', '#Photography', '#Music', '#AI')
|
||||
|
||||
@@ -99,6 +124,142 @@ UPDATE tags SET name = '#' || name WHERE name NOT LIKE '#%';
|
||||
ALTER TABLE tags ADD COLUMN created_by TEXT REFERENCES users(id) ON DELETE SET NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_tags_created_by ON tags(created_by);
|
||||
'''),
|
||||
(5, '''
|
||||
ALTER TABLE users ADD COLUMN email_verified INTEGER NOT NULL DEFAULT 0;
|
||||
UPDATE users SET email_verified = 1;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS email_verification_tokens (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_user_id
|
||||
ON email_verification_tokens(user_id);
|
||||
'''),
|
||||
(6, '''
|
||||
CREATE TABLE IF NOT EXISTS app_settings (
|
||||
name TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
'''),
|
||||
(7, '''
|
||||
CREATE TABLE IF NOT EXISTS password_reset_tokens (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_user_id
|
||||
ON password_reset_tokens(user_id);
|
||||
'''),
|
||||
(8, '''
|
||||
CREATE TABLE IF NOT EXISTS mastodon_oauth_states (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
state_hash TEXT NOT NULL UNIQUE,
|
||||
instance TEXT NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
client_secret TEXT NOT NULL,
|
||||
redirect_uri TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_mastodon_oauth_states_state_hash
|
||||
ON mastodon_oauth_states(state_hash);
|
||||
'''),
|
||||
(9, '''
|
||||
ALTER TABLE links ADD COLUMN mastodon_posted INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE links ADD COLUMN mastodon_post_id TEXT;
|
||||
ALTER TABLE links ADD COLUMN mastodon_posted_at TEXT;
|
||||
'''),
|
||||
(10, '''
|
||||
ALTER TABLE links ADD COLUMN mastodon_post_ids TEXT;
|
||||
UPDATE links
|
||||
SET mastodon_post_ids = CASE
|
||||
WHEN mastodon_post_id IS NOT NULL THEN json_array(mastodon_post_id)
|
||||
ELSE '[]'
|
||||
END
|
||||
WHERE mastodon_post_ids IS NULL;
|
||||
'''),
|
||||
(11, '''
|
||||
ALTER TABLE users ADD COLUMN otp_secret TEXT;
|
||||
ALTER TABLE users ADD COLUMN otp_enabled INTEGER NOT NULL DEFAULT 0;
|
||||
'''),
|
||||
(12, '''
|
||||
CREATE TABLE IF NOT EXISTS user_email_addresses (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
verified INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS email_address_verification_tokens (
|
||||
id TEXT PRIMARY KEY,
|
||||
email_address_id TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(email_address_id) REFERENCES user_email_addresses(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_email_addresses_user_id ON user_email_addresses(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_address_verification_tokens_address_id ON email_address_verification_tokens(email_address_id);
|
||||
'''),
|
||||
(13, '''
|
||||
CREATE TABLE IF NOT EXISTS pending_primary_email_changes (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
'''),
|
||||
(14, '''
|
||||
DROP TABLE IF EXISTS pending_primary_email_changes;
|
||||
'''),
|
||||
(15, '''
|
||||
ALTER TABLE tokens ADD COLUMN device_id TEXT;
|
||||
ALTER TABLE tokens ADD COLUMN token_family_id TEXT;
|
||||
CREATE INDEX IF NOT EXISTS idx_tokens_device_id ON tokens(device_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tokens_family_id ON tokens(token_family_id);
|
||||
'''),
|
||||
(16, '''
|
||||
CREATE TABLE IF NOT EXISTS otp_recovery_codes (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
code_hash TEXT NOT NULL UNIQUE,
|
||||
used INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
used_at TEXT,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_otp_recovery_codes_user_id ON otp_recovery_codes(user_id);
|
||||
'''),
|
||||
(17, '''
|
||||
CREATE TABLE IF NOT EXISTS security_audit_events (
|
||||
id TEXT PRIMARY KEY,
|
||||
actor_id TEXT,
|
||||
action TEXT NOT NULL,
|
||||
target_type TEXT NOT NULL,
|
||||
target_id TEXT,
|
||||
outcome TEXT NOT NULL DEFAULT 'success',
|
||||
details TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(actor_id) REFERENCES users(id) ON DELETE SET NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_security_audit_events_created_at ON security_audit_events(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_security_audit_events_actor_id ON security_audit_events(actor_id);
|
||||
''')
|
||||
]
|
||||
|
||||
|
||||
@@ -134,23 +295,6 @@ def seed_default_tags(conn: sqlite3.Connection) -> None:
|
||||
def init_db() -> None:
|
||||
with get_connection() as conn:
|
||||
apply_migrations(conn)
|
||||
alice_hash = hash_password('secret123')
|
||||
bob_hash = hash_password('secret123')
|
||||
conn.execute(
|
||||
'''
|
||||
INSERT OR IGNORE INTO users (id, username, email, password_hash, is_admin)
|
||||
VALUES (?, ?, ?, ?, 1)
|
||||
''',
|
||||
('user-1', 'alice', 'alice@example.com', alice_hash)
|
||||
)
|
||||
conn.execute("UPDATE users SET is_admin = 1 WHERE id = 'user-1'")
|
||||
conn.execute(
|
||||
'''
|
||||
INSERT OR IGNORE INTO users (id, username, email, password_hash, is_admin)
|
||||
VALUES (?, ?, ?, ?, 0)
|
||||
''',
|
||||
('user-2', 'bob', 'bob@example.com', bob_hash)
|
||||
)
|
||||
conn.execute(
|
||||
'''
|
||||
INSERT OR IGNORE INTO plugins (id, name, version, enabled, config)
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
from fastapi import FastAPI
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
import logging
|
||||
from uuid import uuid4
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from starlette.requests import Request
|
||||
@@ -7,49 +13,95 @@ from starlette.requests import Request
|
||||
from backend.app.api.admin import router as admin_router
|
||||
from backend.app.api.auth import router as auth_router
|
||||
from backend.app.api.links import router as links_router
|
||||
from backend.app.api.mastodon import router as mastodon_router
|
||||
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 has_administrator
|
||||
from backend.app.api.user_config import router as user_config_router
|
||||
from backend.app.core.config import settings, validate_configuration
|
||||
from backend.app.database import AVATARS_DIR
|
||||
from backend.app.services.link_service import list_public_links
|
||||
from backend.app.services.link_service import get_public_profile, list_public_links
|
||||
|
||||
logging.basicConfig(level=getattr(logging, settings.log_level, logging.INFO))
|
||||
validate_configuration(settings)
|
||||
|
||||
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 = FastAPI(title='LinkLog API')
|
||||
app.mount('/static', StaticFiles(directory='frontend/static'), name='static')
|
||||
app.mount('/media', StaticFiles(directory=AVATARS_DIR), name='media')
|
||||
app.include_router(auth_router, prefix='/api/auth')
|
||||
app.include_router(links_router, prefix='/api')
|
||||
app.include_router(mastodon_router, prefix='/api/mastodon')
|
||||
app.include_router(public_router, prefix='/api/public')
|
||||
app.include_router(admin_router, prefix='/api/admin')
|
||||
app.include_router(user_config_router, prefix='/api/user')
|
||||
app.include_router(setup_router, prefix='/api/setup')
|
||||
|
||||
templates = Jinja2Templates(directory='frontend/templates')
|
||||
templates.env.globals['app_version'] = settings.version
|
||||
|
||||
|
||||
@app.get('/', response_class=HTMLResponse)
|
||||
async def public_root(request: Request):
|
||||
if not has_administrator():
|
||||
return RedirectResponse('/setup')
|
||||
feed = list_public_links()
|
||||
return templates.TemplateResponse(request, 'feed.html', {'feed': feed})
|
||||
|
||||
|
||||
@app.get('/admin', response_class=HTMLResponse)
|
||||
async def admin_dashboard(request: Request):
|
||||
if not has_administrator():
|
||||
return RedirectResponse('/setup')
|
||||
return templates.TemplateResponse(request, 'admin.html', {})
|
||||
|
||||
|
||||
@app.get('/profile', response_class=HTMLResponse)
|
||||
async def user_profile_page(request: Request):
|
||||
if not has_administrator():
|
||||
return RedirectResponse('/setup')
|
||||
return templates.TemplateResponse(request, 'user_profile.html', {})
|
||||
|
||||
|
||||
@app.get('/labels', response_class=HTMLResponse)
|
||||
async def labels_page(request: Request):
|
||||
if not has_administrator():
|
||||
return RedirectResponse('/setup')
|
||||
return templates.TemplateResponse(request, 'labels.html', {})
|
||||
|
||||
|
||||
@app.get('/about', response_class=HTMLResponse)
|
||||
async def about_page(request: Request):
|
||||
return templates.TemplateResponse(request, 'about.html', {})
|
||||
|
||||
|
||||
@app.get('/login', response_class=HTMLResponse)
|
||||
async def login_page(request: Request):
|
||||
if not has_administrator():
|
||||
return RedirectResponse('/setup')
|
||||
return templates.TemplateResponse(request, 'login.html', {})
|
||||
|
||||
|
||||
@app.get('/reset-password', response_class=HTMLResponse)
|
||||
async def reset_password_page(request: Request):
|
||||
return templates.TemplateResponse(request, 'reset-password.html', {})
|
||||
|
||||
|
||||
@app.get('/setup', response_class=HTMLResponse)
|
||||
async def setup_page(request: Request):
|
||||
if has_administrator():
|
||||
return RedirectResponse('/')
|
||||
return templates.TemplateResponse(request, 'setup.html', {})
|
||||
|
||||
|
||||
@app.get('/health')
|
||||
def health_check():
|
||||
return {'status': 'ok'}
|
||||
@@ -59,13 +111,7 @@ def health_check():
|
||||
@app.get('/{username}/', response_class=HTMLResponse)
|
||||
async def public_user_feed(request: Request, username: str):
|
||||
feed = list_public_links(username)
|
||||
profile = None
|
||||
if feed:
|
||||
profile = {
|
||||
'username': feed[0]['username'],
|
||||
'avatar_url': feed[0]['avatar_url'],
|
||||
'bio': feed[0]['bio'],
|
||||
}
|
||||
profile = get_public_profile(username)
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
'feed.html',
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
class BasePlugin:
|
||||
name = 'base'
|
||||
version = '1.0.0'
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.app.database import get_connection
|
||||
|
||||
|
||||
def record_audit_event(
|
||||
actor_id: str | None,
|
||||
action: str,
|
||||
target_type: str,
|
||||
target_id: str | None = None,
|
||||
outcome: str = 'success',
|
||||
details: dict | None = None,
|
||||
) -> None:
|
||||
safe_details = details or {}
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO security_audit_events
|
||||
(id, actor_id, action, target_type, target_id, outcome, details)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)''',
|
||||
(str(uuid4()), actor_id, action, target_type, target_id, outcome, json.dumps(safe_details)),
|
||||
)
|
||||
conn.commit()
|
||||
@@ -1,18 +1,44 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from hashlib import sha256
|
||||
|
||||
from backend.app.database import get_connection
|
||||
from backend.app.database import get_connection, hash_password, verify_password
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return sha256(password.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def authenticate_user(username: str, password: str):
|
||||
password_hash = hash_password(password)
|
||||
def authenticate_user(email: str, password: str):
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'SELECT * FROM users WHERE username = ? AND password_hash = ?',
|
||||
(username, password_hash),
|
||||
'''SELECT * FROM users WHERE email = ?
|
||||
UNION ALL
|
||||
SELECT users.* FROM users JOIN user_email_addresses
|
||||
ON user_email_addresses.user_id = users.id
|
||||
WHERE user_email_addresses.email = ? AND user_email_addresses.verified = 1
|
||||
LIMIT 1''',
|
||||
(email, email),
|
||||
).fetchone()
|
||||
if row is None or not verify_password(password, row['password_hash']):
|
||||
return None
|
||||
user = dict(row)
|
||||
if not row['password_hash'].startswith('scrypt$'):
|
||||
conn.execute(
|
||||
'UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
(hash_password(password), row['id']),
|
||||
)
|
||||
conn.commit()
|
||||
user['password_hash'] = conn.execute(
|
||||
'SELECT password_hash FROM users WHERE id = ?', (row['id'],)
|
||||
).fetchone()['password_hash']
|
||||
return user
|
||||
|
||||
|
||||
def find_user(email: str):
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT * FROM users WHERE email = ?', (email,)).fetchone()
|
||||
if row is None:
|
||||
row = conn.execute(
|
||||
'''SELECT users.* FROM users JOIN user_email_addresses
|
||||
ON user_email_addresses.user_id = users.id
|
||||
WHERE user_email_addresses.email = ?''',
|
||||
(email,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import sha256
|
||||
from secrets import token_urlsafe
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.database import get_connection
|
||||
from backend.app.services.email_service import send_verification_email
|
||||
|
||||
|
||||
def list_user_email_addresses(user_id: str) -> list[dict]:
|
||||
with get_connection() as conn:
|
||||
rows = conn.execute(
|
||||
'SELECT id, email, verified, created_at FROM user_email_addresses WHERE user_id = ? ORDER BY created_at',
|
||||
(user_id,),
|
||||
).fetchall()
|
||||
return [dict(row) | {'verified': bool(row['verified']), 'can_be_primary': bool(row['verified'])} for row in rows]
|
||||
|
||||
|
||||
def add_user_email_address(user_id: str, email: str) -> dict:
|
||||
email = email.strip().lower()
|
||||
if not email:
|
||||
raise ValueError('Email address is required')
|
||||
with get_connection() as conn:
|
||||
try:
|
||||
row = conn.execute(
|
||||
'INSERT INTO user_email_addresses (id, user_id, email) VALUES (?, ?, ?) RETURNING id, email, verified, created_at',
|
||||
(str(uuid4()), user_id, email),
|
||||
).fetchone()
|
||||
conn.commit()
|
||||
except Exception as error:
|
||||
if 'UNIQUE constraint failed' in str(error):
|
||||
raise ValueError('Email address already exists') from error
|
||||
raise
|
||||
return dict(row) | {'verified': bool(row['verified']), 'can_be_primary': bool(row['verified'])}
|
||||
|
||||
|
||||
def create_email_verification(user_id: str, address_id: str) -> tuple[str, str]:
|
||||
token = token_urlsafe(32)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(hours=settings.email_verification_expiry_hours)
|
||||
with get_connection() as conn:
|
||||
address = conn.execute(
|
||||
'SELECT email FROM user_email_addresses WHERE id = ? AND user_id = ?',
|
||||
(address_id, user_id),
|
||||
).fetchone()
|
||||
if address is None:
|
||||
raise ValueError('Email address not found')
|
||||
conn.execute('DELETE FROM email_address_verification_tokens WHERE email_address_id = ?', (address_id,))
|
||||
conn.execute(
|
||||
'INSERT INTO email_address_verification_tokens (id, email_address_id, token_hash, expires_at) VALUES (?, ?, ?, ?)',
|
||||
(str(uuid4()), address_id, sha256(token.encode()).hexdigest(), expires_at.isoformat()),
|
||||
)
|
||||
conn.commit()
|
||||
return address['email'], token
|
||||
|
||||
|
||||
def verify_user_email_address(token: str) -> bool:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'''SELECT email_address_id FROM email_address_verification_tokens
|
||||
WHERE token_hash = ? AND expires_at > ?''',
|
||||
(sha256(token.encode()).hexdigest(), now),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
conn.execute('UPDATE user_email_addresses SET verified = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (row['email_address_id'],))
|
||||
conn.execute('DELETE FROM email_address_verification_tokens WHERE email_address_id = ?', (row['email_address_id'],))
|
||||
conn.commit()
|
||||
return True
|
||||
@@ -0,0 +1,148 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from email.message import EmailMessage
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from smtplib import SMTP
|
||||
import json
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.database import get_connection
|
||||
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
|
||||
|
||||
LOGO_PATH = Path(__file__).resolve().parents[3] / 'frontend' / 'static' / 'logo.svg'
|
||||
|
||||
|
||||
def _html_email(body_html: str) -> str:
|
||||
public_url = settings.public_url
|
||||
parsed_url = urlparse(public_url)
|
||||
public_hostname = parsed_url.hostname or public_url
|
||||
safe_public_url = escape(public_url, quote=True)
|
||||
safe_public_hostname = escape(public_hostname)
|
||||
return f'''<!doctype html>
|
||||
<html lang="en">
|
||||
<body style="margin:0;background:#1e1e2e;color:#cdd6f4;font-family:Arial,sans-serif;line-height:1.6;">
|
||||
<div style="max-width:620px;margin:32px auto;padding:0 20px;">
|
||||
<div style="background:#11111b;border:1px solid #45475a;border-radius:12px;overflow:hidden;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#181825;">
|
||||
<tr>
|
||||
<td style="padding:20px 24px;text-align:left;vertical-align:top;width:50px;">
|
||||
<img src="cid:linklog-logo" alt="LinkLog" width="50" height="50" style="display:block;width:50px;height:50px;">
|
||||
</td>
|
||||
<td style="padding:20px 0 20px 12px;text-align:left;vertical-align:top;">
|
||||
<span style="color:#cba6f7;font-family:'Asset',Georgia,serif;font-size:18px;line-height:50px;">Hello, a message from <a href="{safe_public_url}" style="color:#cba6f7;text-decoration:underline;">{safe_public_hostname}</a></span>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<div style="padding:28px 32px;">{body_html}</div>
|
||||
</div>
|
||||
<p style="margin:18px 0;text-align:center;color:#a6adc8;font-size:12px;">LinkLog</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>'''
|
||||
|
||||
|
||||
def _add_html_body(message: EmailMessage, html_body: str) -> None:
|
||||
message.add_alternative(_html_email(html_body), subtype='html')
|
||||
html_part = message.get_payload()[-1]
|
||||
try:
|
||||
logo = LOGO_PATH.read_bytes()
|
||||
except OSError:
|
||||
return
|
||||
html_part.add_related(logo, maintype='image', subtype='svg+xml', cid='<linklog-logo>')
|
||||
|
||||
|
||||
def get_smtp_settings() -> dict:
|
||||
values = {
|
||||
'smtp_host': settings.smtp_host,
|
||||
'smtp_port': settings.smtp_port,
|
||||
'smtp_username': settings.smtp_username,
|
||||
'smtp_password': settings.smtp_password,
|
||||
'smtp_from': settings.smtp_from,
|
||||
'smtp_use_tls': settings.smtp_use_tls,
|
||||
}
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone()
|
||||
if row:
|
||||
values.update(json.loads(row['value']))
|
||||
values['smtp_password'] = decrypt_secret(values['smtp_password'])
|
||||
return values
|
||||
|
||||
|
||||
def save_smtp_settings(values: dict) -> None:
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||
('smtp', json.dumps({**values, 'smtp_password': encrypt_secret(values['smtp_password'])})),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def smtp_configured(smtp_values: dict | None = None) -> bool:
|
||||
smtp = smtp_values or get_smtp_settings()
|
||||
return bool(smtp['smtp_host'] and smtp['smtp_from'])
|
||||
|
||||
|
||||
def send_message(email: str, subject: str, body: str, html_body: str | None = None,
|
||||
smtp_values: dict | None = None) -> None:
|
||||
smtp = smtp_values or get_smtp_settings()
|
||||
if not smtp_configured(smtp):
|
||||
raise RuntimeError('SMTP is not configured; set LINKLOG_SMTP_HOST and LINKLOG_SMTP_FROM')
|
||||
|
||||
message = EmailMessage()
|
||||
message['Subject'] = subject
|
||||
message['From'] = smtp['smtp_from']
|
||||
message['To'] = email
|
||||
message.set_content(body)
|
||||
if html_body:
|
||||
_add_html_body(message, html_body)
|
||||
|
||||
with SMTP(smtp['smtp_host'], smtp['smtp_port'], timeout=10) as connection:
|
||||
if smtp['smtp_use_tls']:
|
||||
connection.starttls()
|
||||
if smtp['smtp_username']:
|
||||
connection.login(smtp['smtp_username'], smtp['smtp_password'])
|
||||
connection.send_message(message)
|
||||
|
||||
|
||||
def send_verification_email(email: str, username: str, verification_url: str) -> None:
|
||||
safe_username = escape(username)
|
||||
safe_url = escape(verification_url, quote=True)
|
||||
send_message(
|
||||
email,
|
||||
'Verify your LinkLog email address',
|
||||
f'Hello {username},\n\n'
|
||||
f'Verify your LinkLog email address by opening this link:\n{verification_url}\n\n'
|
||||
f'This link expires in {settings.email_verification_expiry_hours} hours.\n',
|
||||
f'<p>Hello {safe_username},</p><p>Verify your LinkLog email address:</p>'
|
||||
f'<p><a href="{safe_url}" style="display:inline-block;padding:10px 16px;background:#89b4fa;color:#11111b;text-decoration:none;border-radius:6px;">Verify email address</a></p>'
|
||||
f'<p style="color:#a6adc8;font-size:14px;">This link expires in {settings.email_verification_expiry_hours} hours.</p>',
|
||||
)
|
||||
|
||||
|
||||
def send_test_email(email: str, smtp_values: dict | None = None) -> None:
|
||||
send_message(
|
||||
email,
|
||||
'LinkLog SMTP test',
|
||||
'This is a test message from LinkLog. SMTP is configured correctly.\n',
|
||||
'<p>This is a test message from LinkLog.</p><p style="color:#a6adc8;">SMTP is configured correctly.</p>',
|
||||
smtp_values=smtp_values,
|
||||
)
|
||||
|
||||
|
||||
def send_password_reset_email(email: str, username: str, reset_url: str) -> None:
|
||||
safe_username = escape(username)
|
||||
safe_url = escape(reset_url, quote=True)
|
||||
send_message(
|
||||
email,
|
||||
'Reset your LinkLog password',
|
||||
f'Hello {username},\n\n'
|
||||
f'Reset your LinkLog password by opening this link:\n{reset_url}\n\n'
|
||||
f'This link expires in {settings.password_reset_expiry_hours} hours.\n',
|
||||
f'<p>Hello {safe_username},</p><p>Reset your LinkLog password:</p>'
|
||||
f'<p><a href="{safe_url}" style="display:inline-block;padding:10px 16px;background:#f38ba8;color:#11111b;text-decoration:none;border-radius:6px;">Reset password</a></p>'
|
||||
f'<p style="color:#a6adc8;font-size:14px;">This link expires in {settings.password_reset_expiry_hours} hours.</p>',
|
||||
)
|
||||
@@ -0,0 +1,44 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import sha256
|
||||
from secrets import token_urlsafe
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.database import get_connection
|
||||
|
||||
|
||||
def hash_verification_token(token: str) -> str:
|
||||
return sha256(token.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def create_verification_token(user_id: str) -> str:
|
||||
token = token_urlsafe(32)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(hours=settings.email_verification_expiry_hours)
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM email_verification_tokens WHERE user_id = ?', (user_id,))
|
||||
conn.execute(
|
||||
'''INSERT INTO email_verification_tokens
|
||||
(id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)''',
|
||||
(str(uuid4()), user_id, hash_verification_token(token), expires_at.isoformat()),
|
||||
)
|
||||
conn.commit()
|
||||
return token
|
||||
|
||||
|
||||
def verify_email(token: str) -> bool:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'''SELECT user_id FROM email_verification_tokens
|
||||
WHERE token_hash = ? AND expires_at > ?''',
|
||||
(hash_verification_token(token), now),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
conn.execute('UPDATE users SET email_verified = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (row['user_id'],))
|
||||
conn.execute('DELETE FROM email_verification_tokens WHERE user_id = ?', (row['user_id'],))
|
||||
conn.commit()
|
||||
return True
|
||||
@@ -1,4 +1,8 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.app.core.security import clean_url
|
||||
@@ -105,6 +109,20 @@ def create_link(
|
||||
return record
|
||||
|
||||
|
||||
def find_owned_link_by_title_url(user_id: str, title: str, url: str) -> dict | None:
|
||||
cleaned_url = clean_url(url)
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'SELECT * FROM links WHERE user_id = ? AND title = ? AND url = ? ORDER BY created_at DESC LIMIT 1',
|
||||
(user_id, title, cleaned_url),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
record = dict(row)
|
||||
record['tags'] = get_link_tags(conn, record['id'])
|
||||
return record
|
||||
|
||||
|
||||
def list_public_links(username: str | None = None):
|
||||
with get_connection() as conn:
|
||||
rows = conn.execute(
|
||||
@@ -124,6 +142,15 @@ def list_public_links(username: str | None = None):
|
||||
return records
|
||||
|
||||
|
||||
def get_public_profile(username: str) -> dict | None:
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'SELECT username, avatar_url, bio FROM users WHERE username = ?',
|
||||
(username,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def update_link(
|
||||
link_id: str,
|
||||
user_id: str,
|
||||
@@ -154,6 +181,44 @@ def update_link(
|
||||
return record
|
||||
|
||||
|
||||
def delete_link(link_id: str, user_id: str) -> bool:
|
||||
with get_connection() as conn:
|
||||
cursor = conn.execute(
|
||||
'DELETE FROM links WHERE id = ? AND user_id = ?',
|
||||
(link_id, user_id),
|
||||
)
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
|
||||
def get_owned_link(link_id: str, user_id: str) -> dict | None:
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'SELECT * FROM links WHERE id = ? AND user_id = ?',
|
||||
(link_id, user_id),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def mark_mastodon_posted(link_id: str, user_id: str, post_id: str | None) -> bool:
|
||||
with get_connection() as conn:
|
||||
current = conn.execute(
|
||||
'SELECT mastodon_post_ids FROM links WHERE id = ? AND user_id = ?',
|
||||
(link_id, user_id),
|
||||
).fetchone()
|
||||
post_ids = json.loads(current['mastodon_post_ids']) if current and current['mastodon_post_ids'] else []
|
||||
if post_id and post_id not in post_ids:
|
||||
post_ids.append(post_id)
|
||||
cursor = conn.execute(
|
||||
'''UPDATE links
|
||||
SET mastodon_posted = 1, mastodon_post_id = ?, mastodon_post_ids = ?, mastodon_posted_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ? AND user_id = ?''',
|
||||
(post_id, json.dumps(post_ids), link_id, user_id),
|
||||
)
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
|
||||
def list_public_users():
|
||||
with get_connection() as conn:
|
||||
rows = conn.execute(
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import sha256
|
||||
import json
|
||||
|
||||
from backend.app.database import get_connection
|
||||
|
||||
MAX_FAILURES = 5
|
||||
FAILURE_WINDOW = timedelta(minutes=15)
|
||||
LOCKOUT_DURATION = timedelta(minutes=2)
|
||||
|
||||
|
||||
def _setting_name(ip_address: str, email: str) -> str:
|
||||
key = sha256(f'{ip_address}\0{email.casefold()}'.encode('utf-8')).hexdigest()
|
||||
return f'login_rate:{key}'
|
||||
|
||||
|
||||
def _read_rate(setting_name: str) -> dict:
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
|
||||
if not row:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(row['value'])
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
return {}
|
||||
|
||||
|
||||
def check_login_allowed(ip_address: str, email: str) -> int | None:
|
||||
rate = _read_rate(_setting_name(ip_address, email))
|
||||
now = datetime.now(timezone.utc)
|
||||
locked_until = datetime.fromisoformat(rate['locked_until']) if rate.get('locked_until') else None
|
||||
if locked_until and locked_until > now:
|
||||
return int((locked_until - now).total_seconds()) + 1
|
||||
return None
|
||||
|
||||
|
||||
def record_login_failure(ip_address: str, email: str) -> None:
|
||||
setting_name = _setting_name(ip_address, email)
|
||||
now = datetime.now(timezone.utc)
|
||||
rate = _read_rate(setting_name)
|
||||
first_failure = datetime.fromisoformat(rate['first_failure']) if rate.get('first_failure') else now
|
||||
if now - first_failure >= FAILURE_WINDOW:
|
||||
rate = {}
|
||||
first_failure = now
|
||||
failures = int(rate.get('failures', 0)) + 1
|
||||
updated = {'failures': failures, 'first_failure': first_failure.isoformat()}
|
||||
if failures >= MAX_FAILURES:
|
||||
updated['locked_until'] = (now + LOCKOUT_DURATION).isoformat()
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||
(setting_name, json.dumps(updated)),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def clear_login_failures(ip_address: str, email: str) -> None:
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM app_settings WHERE name = ?', (_setting_name(ip_address, email),))
|
||||
conn.commit()
|
||||
@@ -0,0 +1,120 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import sha256
|
||||
import json
|
||||
from secrets import token_urlsafe
|
||||
from urllib.parse import urlencode
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.database import get_connection
|
||||
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
|
||||
from backend.app.services.mastodon_security import open_no_redirect, validate_public_instance
|
||||
|
||||
|
||||
def normalize_instance(instance: str) -> str:
|
||||
return validate_public_instance(instance)
|
||||
|
||||
|
||||
def post_form(url: str, values: dict) -> dict:
|
||||
request = Request(
|
||||
url,
|
||||
data=urlencode(values).encode('utf-8'),
|
||||
headers={'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
method='POST',
|
||||
)
|
||||
with open_no_redirect(request, timeout=10) as response:
|
||||
return json.loads(response.read().decode('utf-8'))
|
||||
|
||||
|
||||
def start_authorization(user_id: str, instance: str) -> str:
|
||||
instance = normalize_instance(instance)
|
||||
redirect_uri = f'{settings.public_url}/api/mastodon/oauth/callback'
|
||||
setting_name = f'mastodon_app:{instance}'
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
|
||||
app = json.loads(row['value']) if row else None
|
||||
if app and app.get('client_secret'):
|
||||
app['client_secret'] = decrypt_secret(app['client_secret'])
|
||||
if not app:
|
||||
app = post_form(f'{instance}/api/v1/apps', {
|
||||
'client_name': settings.mastodon_client_name,
|
||||
'redirect_uris': redirect_uri,
|
||||
'scopes': 'read:accounts write:statuses',
|
||||
'website': settings.public_url,
|
||||
})
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||
(setting_name, json.dumps({**app, 'client_secret': encrypt_secret(app['client_secret'])})),
|
||||
)
|
||||
conn.commit()
|
||||
state = token_urlsafe(32)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(minutes=settings.mastodon_oauth_expiry_minutes)
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM mastodon_oauth_states WHERE user_id = ?', (user_id,))
|
||||
conn.execute(
|
||||
'''INSERT INTO mastodon_oauth_states
|
||||
(id, user_id, state_hash, instance, client_id, client_secret, redirect_uri, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(str(uuid4()), user_id, sha256(state.encode()).hexdigest(), instance,
|
||||
app['client_id'], encrypt_secret(app['client_secret']), redirect_uri, expires_at.isoformat()),
|
||||
)
|
||||
conn.commit()
|
||||
return f'{instance}/oauth/authorize?' + urlencode({
|
||||
'client_id': app['client_id'],
|
||||
'redirect_uri': redirect_uri,
|
||||
'response_type': 'code',
|
||||
'scope': 'read:accounts write:statuses',
|
||||
'state': state,
|
||||
})
|
||||
|
||||
|
||||
def finish_authorization(code: str, state: str) -> str:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
with get_connection() as conn:
|
||||
record = conn.execute(
|
||||
'''SELECT * FROM mastodon_oauth_states
|
||||
WHERE state_hash = ? AND expires_at > ?''',
|
||||
(sha256(state.encode()).hexdigest(), now),
|
||||
).fetchone()
|
||||
if record is None:
|
||||
raise ValueError('OAuth state is invalid or expired')
|
||||
conn.execute('DELETE FROM mastodon_oauth_states WHERE id = ?', (record['id'],))
|
||||
conn.commit()
|
||||
token = post_form(f"{record['instance']}/oauth/token", {
|
||||
'grant_type': 'authorization_code',
|
||||
'code': code,
|
||||
'client_id': record['client_id'],
|
||||
'client_secret': decrypt_secret(record['client_secret']),
|
||||
'redirect_uri': record['redirect_uri'],
|
||||
})
|
||||
access_token = token.get('access_token')
|
||||
if not access_token:
|
||||
raise ValueError('Mastodon did not return an access token')
|
||||
with get_connection() as conn:
|
||||
current = conn.execute(
|
||||
'SELECT config FROM user_plugin_config WHERE user_id = ? AND plugin_name = ?',
|
||||
(record['user_id'], 'mastodon'),
|
||||
).fetchone()
|
||||
config = json.loads(current['config']) if current and current['config'] else {}
|
||||
config.update({'instance': record['instance'], 'access_token': encrypt_secret(access_token)})
|
||||
if current:
|
||||
conn.execute(
|
||||
'UPDATE user_plugin_config SET config = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND plugin_name = ?',
|
||||
(json.dumps(config), record['user_id'], 'mastodon'),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
'''INSERT INTO user_plugin_config
|
||||
(id, user_id, plugin_name, config, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)''',
|
||||
(str(uuid4()), record['user_id'], 'mastodon', json.dumps(config)),
|
||||
)
|
||||
conn.commit()
|
||||
return record['user_id']
|
||||
@@ -0,0 +1,62 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
|
||||
class RejectRedirectHandler(HTTPRedirectHandler):
|
||||
def redirect_request(self, request, file, code, msg, headers, newurl):
|
||||
raise HTTPError(request.full_url, code, 'Redirects are not allowed', headers, None)
|
||||
|
||||
|
||||
NO_REDIRECT_OPENER = build_opener(RejectRedirectHandler)
|
||||
|
||||
|
||||
def _is_blocked_address(address: str) -> bool:
|
||||
parsed = ipaddress.ip_address(address)
|
||||
mapped = parsed.ipv4_mapped if isinstance(parsed, ipaddress.IPv6Address) else None
|
||||
candidates = (parsed, mapped) if mapped else (parsed,)
|
||||
return any(
|
||||
candidate.is_loopback
|
||||
or candidate.is_link_local
|
||||
or candidate.is_private
|
||||
or candidate.is_multicast
|
||||
or candidate.is_unspecified
|
||||
or candidate.is_reserved
|
||||
for candidate in candidates
|
||||
)
|
||||
|
||||
|
||||
def validate_public_instance(instance: str) -> str:
|
||||
value = instance.strip().rstrip('/')
|
||||
if not value:
|
||||
raise ValueError('Mastodon instance is required')
|
||||
if '://' not in value:
|
||||
value = f'https://{value}'
|
||||
parsed = urlsplit(value)
|
||||
if parsed.scheme.lower() != 'https' or not parsed.hostname:
|
||||
raise ValueError('Mastodon instance must be an HTTPS public hostname')
|
||||
if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/'):
|
||||
raise ValueError('Mastodon instance must be a hostname-only HTTPS URL')
|
||||
try:
|
||||
port = parsed.port
|
||||
except ValueError as error:
|
||||
raise ValueError('Mastodon instance has an invalid port') from error
|
||||
if port not in (None, 443):
|
||||
raise ValueError('Mastodon instance must use HTTPS port 443')
|
||||
hostname = parsed.hostname.rstrip('.').lower()
|
||||
try:
|
||||
addresses = {result[4][0] for result in socket.getaddrinfo(hostname, port or 443, type=socket.SOCK_STREAM)}
|
||||
except socket.gaierror as error:
|
||||
raise ValueError('Mastodon instance hostname could not be resolved') from error
|
||||
if not addresses or any(_is_blocked_address(address) for address in addresses):
|
||||
raise ValueError('Mastodon instance must resolve only to public IP addresses')
|
||||
return f'https://{hostname}'
|
||||
|
||||
|
||||
def open_no_redirect(request: Request, timeout: int = 10):
|
||||
return NO_REDIRECT_OPENER.open(request, timeout=timeout)
|
||||
@@ -0,0 +1,79 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.app.database import get_connection
|
||||
|
||||
|
||||
def create_secret() -> str:
|
||||
return base64.b32encode(secrets.token_bytes(20)).decode('ascii').rstrip('=')
|
||||
|
||||
|
||||
def create_recovery_codes(user_id: str, count: int = 10) -> list[str]:
|
||||
codes = [secrets.token_urlsafe(9) for _ in range(count)]
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM otp_recovery_codes WHERE user_id = ?', (user_id,))
|
||||
conn.executemany(
|
||||
'INSERT INTO otp_recovery_codes (id, user_id, code_hash) VALUES (?, ?, ?)',
|
||||
[(str(uuid4()), user_id, hash_recovery_code(code)) for code in codes],
|
||||
)
|
||||
conn.commit()
|
||||
return codes
|
||||
|
||||
|
||||
def hash_recovery_code(code: str) -> str:
|
||||
return hashlib.sha256(code.strip().encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def consume_recovery_code(user_id: str, code: str) -> bool:
|
||||
with get_connection() as conn:
|
||||
cursor = conn.execute(
|
||||
'''UPDATE otp_recovery_codes
|
||||
SET used = 1, used_at = CURRENT_TIMESTAMP
|
||||
WHERE user_id = ? AND code_hash = ? AND used = 0''',
|
||||
(user_id, hash_recovery_code(code)),
|
||||
)
|
||||
conn.commit()
|
||||
return cursor.rowcount == 1
|
||||
|
||||
|
||||
def provisioning_uri(secret: str, username: str, issuer: str = 'LinkLog') -> str:
|
||||
return f'otpauth://totp/{quote(issuer)}:{quote(username)}?secret={secret}&issuer={quote(issuer)}'
|
||||
|
||||
|
||||
def current_code(secret: str, timestamp: float | None = None) -> str:
|
||||
padded_secret = secret + '=' * (-len(secret) % 8)
|
||||
key = base64.b32decode(padded_secret, casefold=True)
|
||||
counter = int(timestamp if timestamp is not None else time.time()) // 30
|
||||
digest = hmac.new(key, counter.to_bytes(8, 'big'), hashlib.sha1).digest()
|
||||
index = digest[-1] & 0x0f
|
||||
value = (int.from_bytes(digest[index:index + 4], 'big') & 0x7fffffff) % 1_000_000
|
||||
return f'{value:06d}'
|
||||
|
||||
|
||||
def verify_code(secret: str | None, code: str | None) -> bool:
|
||||
if not secret or not code:
|
||||
return False
|
||||
normalized_code = code.strip()
|
||||
if len(normalized_code) != 6 or not normalized_code.isdigit():
|
||||
return False
|
||||
padded_secret = secret + '=' * (-len(secret) % 8)
|
||||
try:
|
||||
key = base64.b32decode(padded_secret, casefold=True)
|
||||
except (ValueError, base64.binascii.Error):
|
||||
return False
|
||||
counter = int(time.time()) // 30
|
||||
for offset in (-1, 0, 1):
|
||||
digest = hmac.new(key, (counter + offset).to_bytes(8, 'big'), hashlib.sha1).digest()
|
||||
index = digest[-1] & 0x0f
|
||||
value = (int.from_bytes(digest[index:index + 4], 'big') & 0x7fffffff) % 1_000_000
|
||||
if hmac.compare_digest(f'{value:06d}', normalized_code):
|
||||
return True
|
||||
return False
|
||||
@@ -0,0 +1,48 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import sha256
|
||||
from secrets import token_urlsafe
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.database import get_connection, hash_password
|
||||
|
||||
|
||||
def hash_reset_token(token: str) -> str:
|
||||
return sha256(token.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def create_reset_token(user_id: str) -> str:
|
||||
token = token_urlsafe(32)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(hours=settings.password_reset_expiry_hours)
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM password_reset_tokens WHERE user_id = ?', (user_id,))
|
||||
conn.execute(
|
||||
'''INSERT INTO password_reset_tokens
|
||||
(id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)''',
|
||||
(str(uuid4()), user_id, hash_reset_token(token), expires_at.isoformat()),
|
||||
)
|
||||
conn.commit()
|
||||
return token
|
||||
|
||||
|
||||
def reset_password(token: str, password: str) -> bool:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'''SELECT user_id FROM password_reset_tokens
|
||||
WHERE token_hash = ? AND expires_at > ?''',
|
||||
(hash_reset_token(token), now),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
conn.execute(
|
||||
'UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
(hash_password(password), row['user_id']),
|
||||
)
|
||||
conn.execute('DELETE FROM password_reset_tokens WHERE user_id = ?', (row['user_id'],))
|
||||
conn.execute('DELETE FROM tokens WHERE user_id = ?', (row['user_id'],))
|
||||
conn.commit()
|
||||
return True
|
||||
@@ -1,10 +1,18 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import json
|
||||
import logging
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request
|
||||
|
||||
from backend.app.plugins.base import BasePlugin
|
||||
from backend.app.services.secret_store import decrypt_secret
|
||||
from backend.app.services.mastodon_security import open_no_redirect, validate_public_instance
|
||||
|
||||
DEFAULT_POST_PREFIX = 'From my #LinkLog: "'
|
||||
DEFAULT_POST_PREFIX = 'From my #LinkLog: '
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DefaultFrontendPlugin(BasePlugin):
|
||||
@@ -41,50 +49,127 @@ class MastodonPlugin(BasePlugin):
|
||||
).fetchone()
|
||||
if row and row['config']:
|
||||
config.update(json.loads(row['config']))
|
||||
config['access_token'] = decrypt_secret(config.get('access_token', ''))
|
||||
|
||||
instance = str(config.get('instance', '')).strip().rstrip('/')
|
||||
if instance and '://' not in instance:
|
||||
instance = f'https://{instance}'
|
||||
try:
|
||||
instance = validate_public_instance(str(config.get('instance', '')))
|
||||
except ValueError as error:
|
||||
return {'status': 'failed', 'plugin': self.name, 'reason': str(error)}
|
||||
access_token = str(config.get('access_token', '')).strip()
|
||||
if not instance or not access_token:
|
||||
logger.debug(
|
||||
'Mastodon post skipped: instance_configured=%s token_configured=%s user_id=%s',
|
||||
bool(instance), bool(access_token), user_id,
|
||||
)
|
||||
return {'status': 'skipped', 'plugin': self.name, 'reason': 'not_configured'}
|
||||
|
||||
status_parts = [event.get('title') or event.get('url', '')]
|
||||
if event.get('comment'):
|
||||
status_parts.append(event['comment'])
|
||||
post_prefix = config.get('post_prefix')
|
||||
if post_prefix is None and config.get('hashtag'):
|
||||
post_prefix = f'#{str(config["hashtag"]).strip().lstrip("#")} '
|
||||
post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX)
|
||||
status = f'{post_prefix}{event.get("url", "")}'.strip()
|
||||
post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX).strip()
|
||||
title = str(event.get('title') or '').strip()
|
||||
status_parts = [post_prefix.strip()]
|
||||
if title:
|
||||
status_parts.append(title)
|
||||
if event.get('comment'):
|
||||
status_parts.append(event['comment'])
|
||||
if title:
|
||||
status_parts.append(f'from: {event.get("url", "")}')
|
||||
if event.get('tags'):
|
||||
status = f'{status} {" ".join(event["tags"])}'
|
||||
status_parts.append(status)
|
||||
status_parts.append(' '.join(event['tags']))
|
||||
post_body = '\n\n'.join(status_parts)
|
||||
endpoint = f'{instance}/api/v1/statuses'
|
||||
logger.debug(
|
||||
'Posting link to Mastodon: endpoint=%s user_id=%s event_id=%s body_length=%d',
|
||||
endpoint, user_id, event.get('id'), len(post_body),
|
||||
)
|
||||
|
||||
try:
|
||||
request = Request(
|
||||
f'{instance}/api/v1/statuses',
|
||||
data=json.dumps({'status': '\n'.join(status_parts)}).encode('utf-8'),
|
||||
endpoint,
|
||||
data=urlencode({'status': post_body}).encode('utf-8'),
|
||||
headers={
|
||||
'Authorization': f'Bearer {access_token}',
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Accept': 'application/json',
|
||||
'User-Agent': 'LinkLog/1.0',
|
||||
},
|
||||
method='POST',
|
||||
)
|
||||
with urlopen(request, timeout=5) as response:
|
||||
response_data = json.loads(response.read().decode('utf-8'))
|
||||
with open_no_redirect(request, timeout=5) as response:
|
||||
response_body = response.read().decode('utf-8')
|
||||
logger.debug(
|
||||
'Mastodon post response: endpoint=%s status=%s body_length=%d',
|
||||
endpoint, response.status, len(response_body),
|
||||
)
|
||||
response_data = json.loads(response_body)
|
||||
logger.info('Mastodon post succeeded: instance=%s user_id=%s post_id=%s', instance, user_id, response_data.get('id'))
|
||||
return {
|
||||
'status': 'posted',
|
||||
'plugin': self.name,
|
||||
'post_id': response_data.get('id'),
|
||||
}
|
||||
except (HTTPError, URLError, TimeoutError, OSError, ValueError) as error:
|
||||
except HTTPError as error:
|
||||
response_body = error.read().decode('utf-8', errors='replace')
|
||||
logger.warning(
|
||||
'Mastodon post failed: endpoint=%s user_id=%s status=%s response=%s',
|
||||
endpoint, user_id, error.code, response_body[:500],
|
||||
)
|
||||
return {
|
||||
'status': 'failed',
|
||||
'plugin': self.name,
|
||||
'reason': f'HTTP {error.code}: {response_body[:500]}',
|
||||
}
|
||||
except (URLError, TimeoutError, OSError, ValueError) as error:
|
||||
logger.exception('Mastodon post failed: endpoint=%s user_id=%s error=%s', endpoint, user_id, error)
|
||||
return {
|
||||
'status': 'failed',
|
||||
'plugin': self.name,
|
||||
'reason': str(error),
|
||||
}
|
||||
|
||||
def delete_posts(self, event):
|
||||
config = dict(self.config)
|
||||
user_id = event.get('user_id')
|
||||
if user_id:
|
||||
from backend.app.database import get_connection
|
||||
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'SELECT config FROM user_plugin_config WHERE user_id = ? AND plugin_name = ?',
|
||||
(user_id, self.name),
|
||||
).fetchone()
|
||||
if row and row['config']:
|
||||
config.update(json.loads(row['config']))
|
||||
config['access_token'] = decrypt_secret(config.get('access_token', ''))
|
||||
|
||||
try:
|
||||
instance = validate_public_instance(str(config.get('instance', '')))
|
||||
except ValueError as error:
|
||||
return {'status': 'failed', 'plugin': self.name, 'reason': str(error)}
|
||||
access_token = str(config.get('access_token', '')).strip()
|
||||
post_ids = event.get('mastodon_post_ids') or []
|
||||
if not post_ids and event.get('mastodon_post_id'):
|
||||
post_ids = [event['mastodon_post_id']]
|
||||
if not instance or not access_token:
|
||||
return {'status': 'failed', 'plugin': self.name, 'reason': 'Mastodon is not configured'}
|
||||
|
||||
try:
|
||||
for post_id in post_ids:
|
||||
request = Request(
|
||||
f'{instance}/api/v1/statuses/{post_id}',
|
||||
headers={'Authorization': f'Bearer {access_token}', 'User-Agent': 'LinkLog/1.0'},
|
||||
method='DELETE',
|
||||
)
|
||||
with open_no_redirect(request, timeout=5) as response:
|
||||
response.read()
|
||||
return {'status': 'deleted', 'plugin': self.name, 'count': len(post_ids)}
|
||||
except HTTPError as error:
|
||||
response_body = error.read().decode('utf-8', errors='replace')
|
||||
return {'status': 'failed', 'plugin': self.name, 'reason': f'HTTP {error.code}: {response_body[:500]}'}
|
||||
except (URLError, TimeoutError, OSError) as error:
|
||||
return {'status': 'failed', 'plugin': self.name, 'reason': str(error)}
|
||||
|
||||
|
||||
class PluginManager:
|
||||
def __init__(self):
|
||||
@@ -108,8 +193,22 @@ class PluginManager:
|
||||
results = []
|
||||
for plugin in self.plugins:
|
||||
if plugin.enabled:
|
||||
results.append(plugin.handle_event(event))
|
||||
result = plugin.handle_event(event)
|
||||
results.append(result)
|
||||
logger.debug('Plugin dispatch result: plugin=%s event_id=%s result=%s', plugin.name, event.get('id'), result)
|
||||
return results
|
||||
|
||||
def post_to_mastodon(self, event):
|
||||
self.refresh_from_db()
|
||||
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
|
||||
if not plugin.enabled:
|
||||
return {'status': 'skipped', 'plugin': 'mastodon', 'reason': 'disabled'}
|
||||
return plugin.handle_event(event)
|
||||
|
||||
def delete_mastodon_posts(self, event):
|
||||
self.refresh_from_db()
|
||||
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
|
||||
return plugin.delete_posts(event)
|
||||
|
||||
|
||||
plugin_manager = PluginManager()
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
from backend.app.core.config import settings
|
||||
|
||||
|
||||
def _cipher() -> Fernet:
|
||||
if not settings.data_encryption_key:
|
||||
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY is required to access encrypted secrets')
|
||||
try:
|
||||
return Fernet(settings.data_encryption_key.encode('ascii'))
|
||||
except (ValueError, UnicodeEncodeError) as error:
|
||||
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY must be a valid Fernet key') from error
|
||||
|
||||
|
||||
def encrypt_secret(value: str) -> str:
|
||||
if not value:
|
||||
return value
|
||||
if value.startswith('enc:v1:'):
|
||||
return value
|
||||
return 'enc:v1:' + _cipher().encrypt(value.encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_secret(value: str) -> str:
|
||||
if not value or not value.startswith('enc:v1:'):
|
||||
return value
|
||||
try:
|
||||
return _cipher().decrypt(value[7:].encode('ascii')).decode('utf-8')
|
||||
except (InvalidToken, UnicodeEncodeError) as error:
|
||||
raise RuntimeError('Encrypted secret cannot be decrypted with LINKLOG_DATA_ENCRYPTION_KEY') from error
|
||||
@@ -0,0 +1,46 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import json
|
||||
|
||||
from backend.app.database import get_connection
|
||||
|
||||
|
||||
THEMES = {
|
||||
'plain-day': {'label': 'Plain Day', 'description': 'A bright, neutral daytime theme.'},
|
||||
'plain-night': {'label': 'Plain Night', 'description': 'A neutral dark nighttime theme.'},
|
||||
'latte': {'label': 'Catppuccin Latte', 'description': 'Catppuccin light theme.'},
|
||||
'frappe': {'label': 'Catppuccin Frappe', 'description': 'Catppuccin soft dark theme.'},
|
||||
'macchiato': {'label': 'Catppuccin Macchiato', 'description': 'Catppuccin medium dark theme.'},
|
||||
'mocha': {'label': 'Catppuccin Mocha', 'description': 'Catppuccin deep dark theme.'},
|
||||
'dracula': {'label': 'Dracula', 'description': 'A vivid dark theme with high-contrast accents.'},
|
||||
'nord': {'label': 'Nord', 'description': 'A cool, muted blue-gray theme.'},
|
||||
'solarized': {'label': 'Solarized', 'description': 'A balanced theme available in a light style.'},
|
||||
}
|
||||
DEFAULT_ENABLED_THEMES = tuple(THEMES)
|
||||
|
||||
|
||||
def get_enabled_themes() -> list[str]:
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('enabled_themes',)).fetchone()
|
||||
if row is None:
|
||||
return list(DEFAULT_ENABLED_THEMES)
|
||||
try:
|
||||
configured = json.loads(row['value'])
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
return list(DEFAULT_ENABLED_THEMES)
|
||||
return [theme for theme in configured if theme in THEMES] or ['mocha']
|
||||
|
||||
|
||||
def save_enabled_themes(themes: list[str]) -> list[str]:
|
||||
selected = list(dict.fromkeys(theme for theme in themes if theme in THEMES))
|
||||
if not selected:
|
||||
raise ValueError('At least one theme must be enabled')
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||
('enabled_themes', json.dumps(selected)),
|
||||
)
|
||||
conn.commit()
|
||||
return selected
|
||||
@@ -1,4 +1,7 @@
|
||||
from datetime import datetime, timezone
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import sha256
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -10,29 +13,42 @@ def hash_token(token: str) -> str:
|
||||
return sha256(token.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def issue_token(user_id: str, username: str) -> dict:
|
||||
token = f'token-{username}-{uuid4().hex}'
|
||||
expires_at = datetime.now(timezone.utc).replace(microsecond=0)
|
||||
expires_at = expires_at.replace(day=expires_at.day + 30 if False else expires_at.day)
|
||||
# one-month expiry, held as a configured value in settings
|
||||
from datetime import timedelta
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(days=settings.token_expiry_days)
|
||||
def _token_expiry() -> datetime:
|
||||
return datetime.now(timezone.utc) + timedelta(minutes=settings.token_expiry_minutes)
|
||||
|
||||
|
||||
def _persist_token(conn, user_id: str, token: str, token_type: str, expires_at: datetime,
|
||||
device_id: str, family_id: str) -> None:
|
||||
conn.execute(
|
||||
'''
|
||||
INSERT INTO tokens
|
||||
(id, user_id, token_hash, token_type, expires_at, created_at, revoked, device_id, token_family_id)
|
||||
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, 0, ?, ?)
|
||||
''',
|
||||
(str(uuid4()), user_id, hash_token(token), token_type, expires_at.isoformat(), device_id, family_id),
|
||||
)
|
||||
|
||||
|
||||
def issue_token(user_id: str, username: str, device_id: str | None = None) -> dict:
|
||||
device_id = device_id.strip() if device_id and device_id.strip() else f'device-{uuid4().hex}'
|
||||
family_id = str(uuid4())
|
||||
access_token = f'token-{username}-{uuid4().hex}'
|
||||
refresh_token = f'refresh-{username}-{uuid4().hex}'
|
||||
access_expires_at = _token_expiry()
|
||||
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
|
||||
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''
|
||||
INSERT INTO tokens (id, user_id, token_hash, token_type, expires_at, created_at, revoked)
|
||||
VALUES (?, ?, ?, 'access', ?, CURRENT_TIMESTAMP, 0)
|
||||
''',
|
||||
(str(uuid4()), user_id, hash_token(token), expires_at.isoformat())
|
||||
)
|
||||
_persist_token(conn, user_id, access_token, 'access', access_expires_at, device_id, family_id)
|
||||
_persist_token(conn, user_id, refresh_token, 'refresh', refresh_expires_at, device_id, family_id)
|
||||
conn.commit()
|
||||
|
||||
return {
|
||||
'access_token': token,
|
||||
'access_token': access_token,
|
||||
'token_type': 'bearer',
|
||||
'expires_at': expires_at.isoformat(),
|
||||
'refresh_token': f'refresh-{uuid4().hex}',
|
||||
'expires_at': access_expires_at.isoformat(),
|
||||
'refresh_token': refresh_token,
|
||||
'device_id': device_id,
|
||||
'token_family_id': family_id,
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +58,7 @@ def validate_token(token: str) -> dict | None:
|
||||
row = conn.execute(
|
||||
'''
|
||||
SELECT * FROM tokens
|
||||
WHERE token_hash = ? AND revoked = 0 AND expires_at > ?
|
||||
WHERE token_hash = ? AND token_type = 'access' AND revoked = 0 AND expires_at > ?
|
||||
''',
|
||||
(token_hash, datetime.now(timezone.utc).isoformat()),
|
||||
).fetchone()
|
||||
@@ -51,12 +67,64 @@ def validate_token(token: str) -> dict | None:
|
||||
return dict(row)
|
||||
|
||||
|
||||
def validate_refresh_token(token: str, device_id: str | None = None) -> dict | None:
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
'''
|
||||
SELECT * FROM tokens
|
||||
WHERE token_hash = ? AND token_type = 'refresh' AND revoked = 0 AND expires_at > ?
|
||||
AND (? IS NULL OR device_id = ?)
|
||||
''',
|
||||
(hash_token(token), datetime.now(timezone.utc).isoformat(), device_id, device_id),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def rotate_refresh_token(refresh_token: str, device_id: str | None = None) -> dict | None:
|
||||
current = validate_refresh_token(refresh_token, device_id)
|
||||
with get_connection() as conn:
|
||||
if current is None:
|
||||
row = conn.execute(
|
||||
'SELECT token_family_id FROM tokens WHERE token_hash = ? AND token_type = ? AND token_family_id IS NOT NULL',
|
||||
(hash_token(refresh_token), 'refresh'),
|
||||
).fetchone()
|
||||
if row:
|
||||
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (row['token_family_id'],))
|
||||
conn.commit()
|
||||
return None
|
||||
|
||||
user = conn.execute('SELECT username FROM users WHERE id = ?', (current['user_id'],)).fetchone()
|
||||
if user is None:
|
||||
return None
|
||||
family_id = current['token_family_id']
|
||||
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (family_id,))
|
||||
new_access = f'token-{user["username"]}-{uuid4().hex}'
|
||||
new_refresh = f'refresh-{user["username"]}-{uuid4().hex}'
|
||||
access_expires_at = _token_expiry()
|
||||
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
|
||||
_persist_token(conn, current['user_id'], new_access, 'access', access_expires_at, current['device_id'], family_id)
|
||||
_persist_token(conn, current['user_id'], new_refresh, 'refresh', refresh_expires_at, current['device_id'], family_id)
|
||||
conn.commit()
|
||||
return {
|
||||
'access_token': new_access,
|
||||
'token_type': 'bearer',
|
||||
'expires_at': access_expires_at.isoformat(),
|
||||
'refresh_token': new_refresh,
|
||||
'device_id': current['device_id'],
|
||||
'user_id': current['user_id'],
|
||||
'username': user['username'],
|
||||
}
|
||||
|
||||
|
||||
def revoke_token(token: str) -> bool:
|
||||
token_hash = hash_token(token)
|
||||
with get_connection() as conn:
|
||||
cursor = conn.execute(
|
||||
'UPDATE tokens SET revoked = 1 WHERE token_hash = ?',
|
||||
(token_hash,),
|
||||
'''UPDATE tokens SET revoked = 1
|
||||
WHERE token_hash = ? OR token_family_id = (
|
||||
SELECT token_family_id FROM tokens WHERE token_hash = ?
|
||||
)''',
|
||||
(token_hash, token_hash),
|
||||
)
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
@@ -3,6 +3,8 @@ uvicorn==0.52.4
|
||||
pydantic==2.13.4
|
||||
jinja2==3.1.6
|
||||
python-multipart==0.0.20
|
||||
Pillow==11.3.0
|
||||
pytest==9.1.1
|
||||
httpx==0.28.1
|
||||
httpx2==2.12.0
|
||||
cryptography==46.0.3
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
TEST_DATABASE_DIRECTORY = tempfile.TemporaryDirectory(prefix='linklog-tests-')
|
||||
TEST_DATABASE_PATH = os.path.join(TEST_DATABASE_DIRECTORY.name, 'linklog.db')
|
||||
os.environ['LINKLOG_DATABASE_PATH'] = TEST_DATABASE_PATH
|
||||
os.environ['LINKLOG_DATA_ENCRYPTION_KEY'] = 'L5M4sQYVjD1N7pT2Xk8R0aBcDeFgHiJkLmNoPqRsTuV='
|
||||
|
||||
|
||||
@pytest.fixture(scope='session', autouse=True)
|
||||
def test_users():
|
||||
from backend.app.database import get_connection, hash_password, init_db
|
||||
|
||||
init_db()
|
||||
with get_connection() as conn:
|
||||
conn.executemany(
|
||||
'''INSERT INTO users
|
||||
(id, username, email, password_hash, is_admin, email_verified)
|
||||
VALUES (?, ?, ?, ?, ?, 1)''',
|
||||
[
|
||||
('user-1', 'alice', 'alice@example.com', hash_password('secret123'), 1),
|
||||
('user-2', 'bob', 'bob@example.com', hash_password('secret123'), 0),
|
||||
],
|
||||
)
|
||||
conn.commit()
|
||||
yield
|
||||
TEST_DATABASE_DIRECTORY.cleanup()
|
||||
@@ -1,10 +1,22 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs
|
||||
from uuid import uuid4
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.app.main import app
|
||||
from backend.app.database import get_connection
|
||||
from backend.app.services.email_service import get_smtp_settings
|
||||
from backend.app.services.login_throttle import clear_login_failures
|
||||
from backend.app.services.otp_service import current_code
|
||||
from backend.app.services.password_reset import create_reset_token
|
||||
from backend.app.services.token_service import issue_token
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
@@ -12,15 +24,16 @@ client = TestClient(app)
|
||||
|
||||
def login_headers(username='alice'):
|
||||
token = client.post('/api/auth/login', json={
|
||||
'username': username,
|
||||
'email': 'alice@example.com' if username == 'alice' else f'{username}@example.com',
|
||||
'password': 'secret123',
|
||||
}).json()['access_token']
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
|
||||
def test_login_returns_token():
|
||||
assert app.version == '0.1.0'
|
||||
response = client.post('/api/auth/login', json={
|
||||
'username': 'alice',
|
||||
'email': 'alice@example.com',
|
||||
'password': 'secret123',
|
||||
})
|
||||
assert response.status_code == 200
|
||||
@@ -28,17 +41,100 @@ def test_login_returns_token():
|
||||
assert 'access_token' in payload
|
||||
assert payload['token_type'] == 'bearer'
|
||||
|
||||
admin_session = client.get('/api/auth/me', params={'token': payload['access_token']})
|
||||
admin_session = client.get('/api/auth/me', headers={'Authorization': f"Bearer {payload['access_token']}"})
|
||||
assert admin_session.status_code == 200
|
||||
assert admin_session.json()['is_admin'] is True
|
||||
|
||||
user_token = client.post('/api/auth/login', json={
|
||||
'username': 'bob',
|
||||
'email': 'bob@example.com',
|
||||
'password': 'secret123',
|
||||
}).json()['access_token']
|
||||
user_session = client.get('/api/auth/me', params={'token': user_token})
|
||||
user_session = client.get('/api/auth/me', headers={'Authorization': f"Bearer {user_token}"})
|
||||
assert user_session.status_code == 200
|
||||
assert user_session.json()['is_admin'] is False
|
||||
assert client.get('/api/auth/me', params={'token': payload['access_token']}).status_code == 401
|
||||
|
||||
|
||||
def test_logout_requires_bearer_header_and_revokes_token_family():
|
||||
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
|
||||
token = login['access_token']
|
||||
headers = {'Authorization': f'Bearer {token}'}
|
||||
assert client.post('/api/auth/logout', json={'token': token}).status_code == 401
|
||||
assert client.get('/api/auth/me', headers=headers).status_code == 200
|
||||
assert client.post('/api/auth/logout', headers=headers).status_code == 200
|
||||
assert client.get('/api/auth/me', headers=headers).status_code == 401
|
||||
assert client.post('/api/auth/refresh', json={'refresh_token': login['refresh_token'], 'device_id': login['device_id']}).status_code == 401
|
||||
|
||||
|
||||
def test_login_rate_limit_locks_out_after_five_failures_and_resets_on_success():
|
||||
email = f'unknown-{uuid4().hex}@example.com'
|
||||
for attempt in range(5):
|
||||
response = client.post('/api/auth/login', json={'email': email, 'password': 'wrong-password'})
|
||||
assert response.status_code == 401, attempt
|
||||
locked = client.post('/api/auth/login', json={'email': email, 'password': 'wrong-password'})
|
||||
assert locked.status_code == 429
|
||||
assert int(locked.headers['Retry-After']) > 0
|
||||
|
||||
clear_login_failures('testclient', email)
|
||||
valid = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'})
|
||||
assert valid.status_code == 200
|
||||
|
||||
|
||||
def test_refresh_token_rotates_and_reuse_revokes_family():
|
||||
device_id = f'device-{uuid4().hex}'
|
||||
login = client.post('/api/auth/login', json={
|
||||
'email': 'alice@example.com',
|
||||
'password': 'secret123',
|
||||
'device_id': device_id,
|
||||
})
|
||||
assert login.status_code == 200
|
||||
first = login.json()
|
||||
|
||||
rotated = client.post('/api/auth/refresh', json={
|
||||
'refresh_token': first['refresh_token'],
|
||||
'device_id': device_id,
|
||||
})
|
||||
assert rotated.status_code == 200
|
||||
second = rotated.json()
|
||||
assert second['refresh_token'] != first['refresh_token']
|
||||
assert client.get('/api/auth/me', headers={'Authorization': f"Bearer {second['access_token']}"}).status_code == 200
|
||||
|
||||
reused = client.post('/api/auth/refresh', json={
|
||||
'refresh_token': first['refresh_token'],
|
||||
'device_id': device_id,
|
||||
})
|
||||
assert reused.status_code == 401
|
||||
family_revoked = client.post('/api/auth/refresh', json={
|
||||
'refresh_token': second['refresh_token'],
|
||||
'device_id': device_id,
|
||||
})
|
||||
assert family_revoked.status_code == 401
|
||||
|
||||
|
||||
def test_password_hashes_are_salted_and_legacy_hashes_upgrade_on_login():
|
||||
from hashlib import sha256
|
||||
from backend.app.database import hash_password
|
||||
|
||||
first = hash_password('same-password')
|
||||
second = hash_password('same-password')
|
||||
assert first.startswith('scrypt$16384$8$1$')
|
||||
assert first != second
|
||||
|
||||
legacy_username = f'legacy-{uuid4().hex}'
|
||||
legacy_hash = sha256('legacy-password'.encode('utf-8')).hexdigest()
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'''INSERT INTO users
|
||||
(id, username, email, password_hash, is_admin, email_verified)
|
||||
VALUES (?, ?, ?, ?, 0, 1)''',
|
||||
(str(uuid4()), legacy_username, f'{legacy_username}@example.com', legacy_hash),
|
||||
)
|
||||
conn.commit()
|
||||
response = client.post('/api/auth/login', json={'email': legacy_username + '@example.com', 'password': 'legacy-password'})
|
||||
assert response.status_code == 200
|
||||
with get_connection() as conn:
|
||||
upgraded = conn.execute('SELECT password_hash FROM users WHERE username = ?', (legacy_username,)).fetchone()['password_hash']
|
||||
assert upgraded.startswith('scrypt$16384$8$1$')
|
||||
|
||||
|
||||
def test_configuration_requires_authentication_and_admin_role():
|
||||
@@ -47,6 +143,115 @@ def test_configuration_requires_authentication_and_admin_role():
|
||||
assert client.get('/api/admin/users').status_code == 401
|
||||
assert client.get('/api/admin/plugins', headers=login_headers('bob')).status_code == 403
|
||||
assert client.get('/api/admin/users', headers=login_headers('bob')).status_code == 403
|
||||
assert client.get('/api/admin/smtp').status_code == 401
|
||||
assert client.get('/api/admin/smtp', headers=login_headers('bob')).status_code == 403
|
||||
|
||||
|
||||
def test_admin_can_select_multiple_themes():
|
||||
headers = login_headers()
|
||||
response = client.put('/api/admin/themes', headers=headers, json={
|
||||
'themes': ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized'],
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.json()['enabled'] == ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized']
|
||||
public_response = client.get('/api/public/themes')
|
||||
assert public_response.status_code == 200
|
||||
assert [theme['id'] for theme in public_response.json()] == response.json()['enabled']
|
||||
|
||||
assert client.put('/api/admin/themes', headers=headers, json={'themes': []}).status_code == 422
|
||||
|
||||
|
||||
def test_admin_can_save_and_validate_smtp_settings():
|
||||
headers = login_headers()
|
||||
original = get_smtp_settings()
|
||||
with get_connection() as conn:
|
||||
original_row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone()
|
||||
response = client.put('/api/admin/smtp', headers=headers, json={
|
||||
'smtp_host': 'smtp.example.com',
|
||||
'smtp_port': 587,
|
||||
'smtp_username': 'mailer',
|
||||
'smtp_password': 'secret',
|
||||
'smtp_from': 'LinkLog <no-reply@example.com>',
|
||||
'smtp_use_tls': True,
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.json()['smtp_host'] == 'smtp.example.com'
|
||||
assert response.json()['password_configured'] is True
|
||||
assert 'smtp_password' not in response.json()
|
||||
|
||||
with patch('backend.app.api.admin.send_test_email') as send_test_email:
|
||||
validation = client.post('/api/admin/smtp/test', headers=headers, json={
|
||||
'smtp_host': 'smtp.unsaved.example.com',
|
||||
'smtp_port': 2525,
|
||||
'smtp_username': 'temporary-user',
|
||||
'smtp_password': 'temporary-secret',
|
||||
'smtp_from': 'Temporary <temporary@example.com>',
|
||||
'smtp_use_tls': False,
|
||||
})
|
||||
assert validation.status_code == 200
|
||||
send_test_email.assert_called_once_with('alice@example.com', {
|
||||
'smtp_host': 'smtp.unsaved.example.com',
|
||||
'smtp_port': 2525,
|
||||
'smtp_username': 'temporary-user',
|
||||
'smtp_password': 'temporary-secret',
|
||||
'smtp_from': 'Temporary <temporary@example.com>',
|
||||
'smtp_use_tls': False,
|
||||
})
|
||||
|
||||
with get_connection() as conn:
|
||||
if original_row is None:
|
||||
conn.execute('DELETE FROM app_settings WHERE name = ?', ('smtp',))
|
||||
else:
|
||||
conn.execute(
|
||||
'UPDATE app_settings SET value = ?, updated_at = CURRENT_TIMESTAMP WHERE name = ?',
|
||||
(original_row['value'], 'smtp'),
|
||||
)
|
||||
conn.commit()
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def test_admin_reports_smtp_validation_errors():
|
||||
headers = login_headers()
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',))
|
||||
conn.commit()
|
||||
with patch('backend.app.api.admin.send_test_email', side_effect=RuntimeError('connection refused')):
|
||||
failed_validation = client.post('/api/admin/smtp/test', headers=headers, json={
|
||||
'smtp_host': 'smtp.unsaved.example.com',
|
||||
'smtp_port': 2525,
|
||||
'smtp_username': 'temporary-user',
|
||||
'smtp_password': 'temporary-secret',
|
||||
'smtp_from': 'Temporary <temporary@example.com>',
|
||||
'smtp_use_tls': False,
|
||||
})
|
||||
assert failed_validation.status_code == 503
|
||||
assert failed_validation.json()['detail'].startswith('SMTP validation failed. Reference: ')
|
||||
assert 'connection refused' not in failed_validation.json()['detail']
|
||||
assert failed_validation.headers['X-Request-ID']
|
||||
|
||||
|
||||
def test_request_id_is_preserved_and_sensitive_error_text_is_not_returned():
|
||||
headers = login_headers()
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',))
|
||||
conn.commit()
|
||||
with patch('backend.app.api.admin.send_test_email', side_effect=RuntimeError('password=super-secret token=abc123')):
|
||||
response = client.post(
|
||||
'/api/admin/smtp/test',
|
||||
headers={**headers, 'X-Request-ID': 'audit-test-123'},
|
||||
json={
|
||||
'smtp_host': 'smtp.example.com',
|
||||
'smtp_port': 2525,
|
||||
'smtp_from': 'admin@example.com',
|
||||
},
|
||||
)
|
||||
assert response.status_code == 503
|
||||
assert response.headers['X-Request-ID'] == 'audit-test-123'
|
||||
assert response.json()['detail'] == 'SMTP validation failed. Reference: audit-test-123'
|
||||
assert 'super-secret' not in response.text
|
||||
assert 'abc123' not in response.text
|
||||
|
||||
|
||||
def test_admin_can_add_list_and_remove_users():
|
||||
@@ -56,6 +261,7 @@ def test_admin_can_add_list_and_remove_users():
|
||||
'email': 'charlie@example.com',
|
||||
'password': 'charlie-secret',
|
||||
})
|
||||
|
||||
assert create_response.status_code == 201
|
||||
user = create_response.json()
|
||||
assert user['username'] == 'charlie'
|
||||
@@ -66,6 +272,206 @@ def test_admin_can_add_list_and_remove_users():
|
||||
assert client.delete(f"/api/admin/users/{user['id']}", headers=headers).status_code == 200
|
||||
assert all(item['id'] != user['id'] for item in client.get('/api/admin/users', headers=headers).json())
|
||||
assert client.delete('/api/admin/users/user-1', headers=headers).status_code == 400
|
||||
assert client.put('/api/admin/users/user-1', headers=headers, json={'is_admin': False}).status_code == 400
|
||||
|
||||
|
||||
def test_admin_can_reset_another_users_otp():
|
||||
admin_headers = login_headers()
|
||||
user_login = client.post('/api/auth/login', json={
|
||||
'email': 'bob@example.com',
|
||||
'password': 'secret123',
|
||||
}).json()
|
||||
user_headers = {'Authorization': f"Bearer {user_login['access_token']}"}
|
||||
setup = client.post('/api/user/otp/setup', headers=user_headers)
|
||||
assert setup.status_code == 200
|
||||
secret = setup.json()['secret']
|
||||
recovery_code = setup.json()['recovery_codes'][0]
|
||||
assert client.post('/api/user/otp', headers=user_headers, json={
|
||||
'action': 'enable', 'code': current_code(secret),
|
||||
}).status_code == 200
|
||||
|
||||
assert client.post('/api/admin/users/user-2/otp/reset', headers=admin_headers).json() == {
|
||||
'status': 'otp_reset', 'enabled': False, 'user_id': 'user-2',
|
||||
}
|
||||
assert client.get('/api/user/otp', headers=user_headers).json() == {'enabled': False}
|
||||
assert client.post('/api/user/otp/recover', headers=user_headers, json={
|
||||
'current_password': 'secret123', 'recovery_code': recovery_code,
|
||||
}).status_code == 400
|
||||
assert client.post('/api/admin/users/user-2/otp/reset', headers=login_headers('bob')).status_code == 403
|
||||
assert client.post('/api/admin/users/missing-user/otp/reset', headers=admin_headers).status_code == 404
|
||||
|
||||
|
||||
def test_security_audit_events_are_append_only_and_do_not_store_secrets():
|
||||
admin_headers = login_headers()
|
||||
response = client.put('/api/admin/themes', headers=admin_headers, json={'themes': ['plain-day']})
|
||||
assert response.status_code == 200
|
||||
with get_connection() as conn:
|
||||
event = conn.execute(
|
||||
'''SELECT actor_id, action, target_type, outcome, details
|
||||
FROM security_audit_events
|
||||
WHERE action = 'themes_updated'
|
||||
ORDER BY created_at DESC, rowid DESC LIMIT 1''',
|
||||
).fetchone()
|
||||
assert event is not None
|
||||
assert event['actor_id'] == 'user-1'
|
||||
assert event['target_type'] == 'application'
|
||||
assert event['outcome'] == 'success'
|
||||
assert 'password' not in event['details'].lower()
|
||||
assert 'token' not in event['details'].lower()
|
||||
assert 'secret' not in event['details'].lower()
|
||||
|
||||
|
||||
def test_new_user_must_verify_email_before_login():
|
||||
headers = login_headers()
|
||||
username = f'unverified-{uuid4().hex}'
|
||||
created = client.post('/api/admin/users', headers=headers, json={
|
||||
'username': username,
|
||||
'email': f'{username}@example.com',
|
||||
'password': 'secret123',
|
||||
})
|
||||
assert created.status_code == 201
|
||||
assert created.json()['email_verified'] is False
|
||||
|
||||
login = client.post('/api/auth/login', json={'email': f'{username}@example.com', 'password': 'secret123'})
|
||||
assert login.status_code == 403
|
||||
assert login.json()['detail'] == 'Email address is not verified'
|
||||
|
||||
|
||||
def test_email_verification_link_enables_login():
|
||||
headers = login_headers()
|
||||
username = f'verifiable-{uuid4().hex}'
|
||||
created = client.post('/api/admin/users', headers=headers, json={
|
||||
'username': username,
|
||||
'email': f'{username}@example.com',
|
||||
'password': 'secret123',
|
||||
})
|
||||
assert created.status_code == 201
|
||||
user_id = created.json()['id']
|
||||
from backend.app.services.email_verification import create_verification_token
|
||||
verification_token = create_verification_token(user_id)
|
||||
|
||||
verified = client.get('/api/auth/verify-email', params={'token': verification_token})
|
||||
assert verified.status_code == 200
|
||||
assert client.post('/api/auth/login', json={'email': f'{username}@example.com', 'password': 'secret123'}).status_code == 200
|
||||
assert client.get('/api/auth/verify-email', params={'token': verification_token}).status_code == 400
|
||||
|
||||
|
||||
def test_mistyped_password_sends_reset_link_without_changing_login_error():
|
||||
username = f'mistyped-{uuid4().hex}'
|
||||
admin_headers = {'Authorization': f"Bearer {issue_token('user-1', 'alice')['access_token']}"}
|
||||
created = client.post('/api/admin/users', headers=admin_headers, json={
|
||||
'username': username,
|
||||
'email': f'{username}@example.com',
|
||||
'password': 'secret123',
|
||||
})
|
||||
user_id = created.json()['id']
|
||||
with get_connection() as conn:
|
||||
conn.execute('UPDATE users SET email_verified = 1 WHERE id = ?', (user_id,))
|
||||
conn.commit()
|
||||
with patch('backend.app.api.auth.smtp_configured', return_value=True), \
|
||||
patch('backend.app.api.auth.create_reset_token', return_value='reset-token') as create_token, \
|
||||
patch('backend.app.api.auth.send_password_reset_email') as send_email:
|
||||
response = client.post('/api/auth/login', json={'email': f'{username}@example.com', 'password': 'wrong-password'})
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.json()['detail'] == 'Invalid username or password'
|
||||
create_token.assert_called_once_with(user_id)
|
||||
send_email.assert_called_once()
|
||||
assert send_email.call_args.args[2].endswith('/reset-password?token=reset-token')
|
||||
|
||||
|
||||
def test_password_reset_is_single_use_and_revokes_sessions():
|
||||
username = f'reset-owner-{uuid4().hex}'
|
||||
admin_headers = {'Authorization': f"Bearer {issue_token('user-1', 'alice')['access_token']}"}
|
||||
created = client.post('/api/admin/users', headers=admin_headers, json={
|
||||
'username': username,
|
||||
'email': f'{username}@example.com',
|
||||
'password': 'secret123',
|
||||
})
|
||||
user_id = created.json()['id']
|
||||
with get_connection() as conn:
|
||||
conn.execute('UPDATE users SET email_verified = 1 WHERE id = ?', (user_id,))
|
||||
conn.commit()
|
||||
token = create_reset_token(user_id)
|
||||
reset = client.post('/api/auth/reset-password', json={'token': token, 'password': 'new-secret123'})
|
||||
assert reset.status_code == 200
|
||||
assert client.post('/api/auth/reset-password', json={'token': token, 'password': 'another-secret'}).status_code == 400
|
||||
assert client.post('/api/auth/login', json={'email': f'{username}@example.com', 'password': 'new-secret123'}).status_code == 200
|
||||
|
||||
|
||||
def test_admin_can_remove_user_with_owned_data():
|
||||
headers = login_headers()
|
||||
username = f'data-owner-{uuid4().hex}'
|
||||
create_response = client.post('/api/admin/users', headers=headers, json={
|
||||
'username': username,
|
||||
'email': f'{username}@example.com',
|
||||
'password': 'secret123',
|
||||
})
|
||||
assert create_response.status_code == 201
|
||||
user_id = create_response.json()['id']
|
||||
user_token = issue_token(user_id, username)['access_token']
|
||||
user_headers = {'Authorization': f'Bearer {user_token}'}
|
||||
|
||||
link_response = client.post('/api/links', headers=user_headers, json={
|
||||
'title': 'Owned link',
|
||||
'url': 'https://example.com/owned',
|
||||
'comment': 'Owned data',
|
||||
'tags': ['owned'],
|
||||
})
|
||||
assert link_response.status_code == 201
|
||||
label_response = client.post('/api/user/labels', headers=user_headers, json={'name': f'{username}-label'})
|
||||
assert label_response.status_code == 201
|
||||
plugin_response = client.put('/api/user/plugins/mastodon', headers=user_headers, json={
|
||||
'instance': 'mastodon.social',
|
||||
})
|
||||
assert plugin_response.status_code == 200
|
||||
|
||||
removed = client.delete(f'/api/admin/users/{user_id}', headers=headers)
|
||||
assert removed.status_code == 200
|
||||
assert client.get('/api/auth/me', params={'token': user_token}).status_code == 401
|
||||
|
||||
|
||||
def test_deleting_link_removes_all_mastodon_posts_first():
|
||||
owner_headers = login_headers('alice')
|
||||
created = client.post('/api/links', headers=owner_headers, json={
|
||||
'title': 'Remote cleanup',
|
||||
'url': 'https://example.com/remote-cleanup',
|
||||
})
|
||||
assert created.status_code == 201
|
||||
link_id = created.json()['id']
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'UPDATE links SET mastodon_posted = 1, mastodon_post_id = ?, mastodon_post_ids = ? WHERE id = ?',
|
||||
('post-2', json.dumps(['post-1', 'post-2']), link_id),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
with patch('backend.app.api.links.plugin_manager.delete_mastodon_posts', return_value={'status': 'deleted', 'count': 2}) as delete_posts:
|
||||
deleted = client.delete(f'/api/links/{link_id}', headers=owner_headers)
|
||||
assert deleted.status_code == 200
|
||||
delete_posts.assert_called_once()
|
||||
assert delete_posts.call_args.args[0]['mastodon_post_ids'] == ['post-1', 'post-2']
|
||||
assert client.delete(f'/api/links/{link_id}', headers=owner_headers).status_code == 404
|
||||
|
||||
|
||||
def test_link_is_kept_when_mastodon_cleanup_fails():
|
||||
owner_headers = login_headers('alice')
|
||||
created = client.post('/api/links', headers=owner_headers, json={
|
||||
'title': 'Failed remote cleanup',
|
||||
'url': 'https://example.com/failed-remote-cleanup',
|
||||
})
|
||||
link_id = created.json()['id']
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
'UPDATE links SET mastodon_posted = 1, mastodon_post_id = ?, mastodon_post_ids = ? WHERE id = ?',
|
||||
('post-failed', json.dumps(['post-failed']), link_id),
|
||||
)
|
||||
conn.commit()
|
||||
with patch('backend.app.api.links.plugin_manager.delete_mastodon_posts', return_value={'status': 'failed', 'reason': 'remote refused'}):
|
||||
deleted = client.delete(f'/api/links/{link_id}', headers=owner_headers)
|
||||
assert deleted.status_code == 502
|
||||
assert 'remote refused' in deleted.json()['detail']
|
||||
assert client.get('/api/links').json()
|
||||
|
||||
|
||||
def test_admin_can_toggle_privileges_without_removing_last_admin():
|
||||
@@ -137,6 +543,57 @@ def test_submit_link_stores_cleaned_url_and_public_feed():
|
||||
assert 'alice' in users_response.json()
|
||||
|
||||
|
||||
def test_duplicate_link_updates_comment_tags_and_retriggers_plugins():
|
||||
headers = login_headers()
|
||||
payload = {
|
||||
'title': 'Duplicate candidate',
|
||||
'url': 'https://example.com/duplicate?utm_source=campaign',
|
||||
'comment': 'first comment',
|
||||
'tags': ['#First'],
|
||||
}
|
||||
first = client.post('/api/links', headers=headers, json=payload)
|
||||
assert first.status_code == 201
|
||||
|
||||
with patch('backend.app.api.links.plugin_manager.dispatch', return_value=[]) as dispatch:
|
||||
duplicate = client.post('/api/links', headers=headers, json={
|
||||
**payload,
|
||||
'comment': 'updated comment',
|
||||
'tags': ['#Second'],
|
||||
})
|
||||
assert duplicate.status_code == 200
|
||||
assert duplicate.json()['duplicate'] is True
|
||||
assert duplicate.json()['id'] == first.json()['id']
|
||||
dispatch.assert_called_once()
|
||||
assert dispatch.call_args.args[0]['comment'] == 'updated comment'
|
||||
assert dispatch.call_args.args[0]['tags'] == ['#Second']
|
||||
feed_item = next(item for item in client.get('/api/public/feed').json() if item['id'] == first.json()['id'])
|
||||
assert feed_item['comment'] == 'updated comment'
|
||||
assert feed_item['tags'] == ['#Second']
|
||||
|
||||
|
||||
def test_duplicate_link_check_is_authenticated_and_detects_existing_entry():
|
||||
headers = login_headers()
|
||||
payload = {'title': 'Check candidate', 'url': 'https://example.com/check-candidate'}
|
||||
assert client.get('/api/links/check', params=payload).status_code == 401
|
||||
created = client.post('/api/links', headers=headers, json=payload)
|
||||
assert created.status_code == 201
|
||||
check = client.get('/api/links/check', headers=headers, params=payload)
|
||||
assert check.status_code == 200
|
||||
assert check.json()['exists'] is True
|
||||
|
||||
|
||||
def test_link_save_reports_plugin_posting_errors():
|
||||
with patch('backend.app.api.links.plugin_manager.dispatch', return_value=[
|
||||
{'status': 'failed', 'plugin': 'mastodon', 'reason': 'HTTP 503: unavailable'},
|
||||
]):
|
||||
response = client.post('/api/links', headers=login_headers(), json={
|
||||
'title': 'Plugin error report',
|
||||
'url': 'https://example.com/plugin-error-report',
|
||||
})
|
||||
assert response.status_code == 201
|
||||
assert response.json()['plugin_errors'] == [{'plugin': 'mastodon', 'reason': 'HTTP 503: unavailable'}]
|
||||
|
||||
|
||||
def test_links_support_tags_and_tag_filtering():
|
||||
headers = login_headers()
|
||||
response = client.post('/api/links', headers=headers, json={
|
||||
@@ -213,11 +670,15 @@ def test_only_link_owner_can_edit_link():
|
||||
})
|
||||
assert denied.status_code == 404
|
||||
|
||||
deleted = client.delete(f'/api/links/{link_id}', headers=owner_headers)
|
||||
assert deleted.status_code == 200
|
||||
assert client.delete(f'/api/links/{link_id}', headers=owner_headers).status_code == 404
|
||||
assert client.delete(f'/api/links/{link_id}', headers=login_headers('bob')).status_code == 404
|
||||
|
||||
|
||||
def test_logout_revokes_token_and_admin_can_list_plugins():
|
||||
headers = login_headers()
|
||||
token = headers['Authorization'].removeprefix('Bearer ')
|
||||
assert client.post('/api/auth/logout', json={'token': token}).status_code == 200
|
||||
assert client.post('/api/auth/logout', headers=headers).status_code == 200
|
||||
|
||||
revoked_response = client.post('/api/links', headers=headers, json={
|
||||
'title': 'Should fail',
|
||||
@@ -234,6 +695,9 @@ def test_logout_revokes_token_and_admin_can_list_plugins():
|
||||
def test_public_and_admin_pages_render_html():
|
||||
root_page = client.get('/')
|
||||
assert 'LinkLog' in root_page.text
|
||||
assert 'src="/static/logo.svg"' in root_page.text
|
||||
assert 'class="site-footer"' in root_page.text
|
||||
assert 'https://git.kolkman.org/' in root_page.text
|
||||
assert 'class="menu-toggle"' in root_page.text
|
||||
assert 'id="auth-menu" class="auth-menu hidden"' in root_page.text
|
||||
assert 'id="auth-home-link" href="/">Home</a>' in root_page.text
|
||||
@@ -243,6 +707,7 @@ def test_public_and_admin_pages_render_html():
|
||||
assert 'id="auth-profile-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 root_page.text.index('class="site-logo"') < root_page.text.index('<section class="toolbar">')
|
||||
assert 'logout.js?v=3' in root_page.text
|
||||
assert client.get('/alice').status_code == 200
|
||||
assert client.get('/alice/').status_code == 200
|
||||
@@ -255,8 +720,16 @@ def test_public_and_admin_pages_render_html():
|
||||
assert client.get('/login').status_code == 200
|
||||
login_page = client.get('/login').text
|
||||
assert 'Sign in' in login_page
|
||||
assert 'name="otp"' in login_page
|
||||
assert 'src="/static/logo.svg"' in login_page
|
||||
assert 'id="auth-session" class="auth-session hidden"' in login_page
|
||||
assert 'logout.js?v=3' in login_page
|
||||
about_page = client.get('/about')
|
||||
assert about_page.status_code == 200
|
||||
assert 'Save the good stuff' in about_page.text
|
||||
assert '<h2>Plugin</h2>' in about_page.text
|
||||
assert 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi' in about_page.text
|
||||
assert 'id="auth-about-link" href="/about"' in about_page.text
|
||||
assert client.get('/admin').status_code == 200
|
||||
admin_page = client.get('/admin').text
|
||||
assert 'Admin' in admin_page
|
||||
@@ -265,11 +738,17 @@ def test_public_and_admin_pages_render_html():
|
||||
assert 'id="auth-menu" class="auth-menu hidden"' 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 'admin.js?v=3' in admin_page
|
||||
assert 'admin.js?v=5' in admin_page
|
||||
feed_script = client.get('/static/feed.js?v=7').text
|
||||
assert 'if (item.is_owner)' in feed_script
|
||||
assert 'if (item.is_owner && !showIdentity)' in feed_script
|
||||
assert 'deleteEntry(item, deleteButton)' in feed_script
|
||||
assert 'postToMastodon(item, mastodonButton)' in feed_script
|
||||
assert 'tag.toLowerCase() === pref.tag.toLowerCase()' in feed_script
|
||||
assert 'return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`' in feed_script
|
||||
assert "entryMeta.className = 'entry-meta'" in feed_script
|
||||
assert "meta.className = 'meta'" in feed_script
|
||||
assert "comment.textContent = item.comment || ''" in feed_script
|
||||
assert 'profileLink.href = `/${encodeURIComponent(username)}/`' in feed_script
|
||||
assert 'edit-tag-options' in feed_script
|
||||
assert 'new_tags' in feed_script
|
||||
assert 'A link can have at most 10 tags.' in feed_script
|
||||
@@ -282,7 +761,8 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
|
||||
def do_POST(self):
|
||||
received['path'] = self.path
|
||||
received['authorization'] = self.headers['Authorization']
|
||||
received['body'] = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
|
||||
received['content_type'] = self.headers['Content-Type']
|
||||
received['body'] = parse_qs(self.rfile.read(int(self.headers['Content-Length'])).decode())
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.end_headers()
|
||||
@@ -297,43 +777,67 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
|
||||
try:
|
||||
headers = login_headers()
|
||||
base_url = f'http://127.0.0.1:{server.server_port}'
|
||||
assert client.put('/api/user/plugins/mastodon', headers=headers, json={
|
||||
'instance': base_url,
|
||||
'access_token': 'test-token',
|
||||
'post_prefix': 'From my #LinkLog: "',
|
||||
}).status_code == 200
|
||||
assert client.put('/api/admin/plugins/mastodon', headers=headers, json={'enabled': True}).status_code == 200
|
||||
with patch('backend.app.services.plugin_manager.validate_public_instance', return_value=base_url):
|
||||
assert client.put('/api/user/plugins/mastodon', headers=headers, json={
|
||||
'instance': base_url,
|
||||
'access_token': 'test-token',
|
||||
'post_prefix': 'From my #LinkLog: ',
|
||||
}).status_code == 200
|
||||
assert client.put('/api/admin/plugins/mastodon', headers=headers, json={'enabled': True}).status_code == 200
|
||||
|
||||
response = client.post('/api/links', headers=headers, json={
|
||||
'title': 'A useful page',
|
||||
'url': 'https://example.com/useful',
|
||||
'comment': 'Worth sharing',
|
||||
'tags': ['#python', '#web'],
|
||||
})
|
||||
response = client.post('/api/links', headers=headers, json={
|
||||
'title': 'A useful page',
|
||||
'url': 'https://example.com/useful',
|
||||
'comment': 'Worth sharing',
|
||||
'tags': ['#python', '#web'],
|
||||
})
|
||||
|
||||
assert response.status_code == 201
|
||||
assert received['path'] == '/api/v1/statuses'
|
||||
assert received['authorization'] == 'Bearer test-token'
|
||||
assert received['body'] == {
|
||||
'status': 'A useful page\nWorth sharing\nFrom my #LinkLog: "https://example.com/useful #python #web',
|
||||
}
|
||||
assert received['content_type'] == 'application/x-www-form-urlencoded'
|
||||
assert received['body'] == {'status': ['From my #LinkLog:\n\nA useful page\n\nWorth sharing\n\nfrom: https://example.com/useful\n\n#python #web']}
|
||||
posted_item = next(item for item in client.get('/api/public/feed/alice', headers=headers).json() if item['id'] == response.json()['id'])
|
||||
assert posted_item['mastodon_posted'] is True
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_mastodon_post_without_title_omits_source_line():
|
||||
from backend.app.services.plugin_manager import MastodonPlugin
|
||||
|
||||
response = MagicMock()
|
||||
response.__enter__.return_value.read.return_value = b'{"id":"status-2"}'
|
||||
plugin = MastodonPlugin()
|
||||
plugin.initialize({'instance': 'https://mastodon.example', 'access_token': 'test-token'})
|
||||
|
||||
with patch('backend.app.services.plugin_manager.open_no_redirect', return_value=response) as open_url, \
|
||||
patch('backend.app.services.plugin_manager.validate_public_instance', return_value='https://mastodon.example'):
|
||||
result = plugin.handle_event({
|
||||
'url': 'https://example.com/useful',
|
||||
'title': '',
|
||||
'comment': 'A comment',
|
||||
'tags': ['#tag'],
|
||||
})
|
||||
|
||||
body = parse_qs(open_url.call_args.args[0].data.decode())['status'][0]
|
||||
assert result['status'] == 'posted'
|
||||
assert body == 'From my #LinkLog:\n\nA comment\n\n#tag'
|
||||
|
||||
|
||||
def test_plugin_config_can_be_saved_for_mastodon():
|
||||
headers = login_headers()
|
||||
assert client.put('/api/user/plugins/mastodon', headers=headers, json={
|
||||
'instance': 'mastodon.social',
|
||||
'access_token': 'demo-token',
|
||||
'post_prefix': 'From my #LinkLog: "',
|
||||
'post_prefix': 'From my #LinkLog: ',
|
||||
}).status_code == 200
|
||||
|
||||
payload = client.get('/api/user/plugins/mastodon', headers=headers).json()
|
||||
assert payload['instance'] == 'mastodon.social'
|
||||
assert payload['post_prefix'] == 'From my #LinkLog: "'
|
||||
assert payload['post_prefix'] == 'From my #LinkLog: '
|
||||
|
||||
admin_update = client.put('/api/admin/plugins/mastodon', headers=headers, json={
|
||||
'enabled': True,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from backend.app.core.config import Settings, validate_configuration
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_production_configuration_rejects_missing_or_default_secret():
|
||||
with pytest.raises(RuntimeError, match='LINKLOG_SECRET_KEY'):
|
||||
validate_configuration(Settings(app_env='production', secret_key='', data_encryption_key=''))
|
||||
with pytest.raises(RuntimeError, match='LINKLOG_SECRET_KEY'):
|
||||
validate_configuration(Settings(app_env='production', secret_key='dev-secret-key-change-me', data_encryption_key=''))
|
||||
|
||||
|
||||
def test_production_configuration_rejects_weak_or_missing_encryption_key():
|
||||
with pytest.raises(RuntimeError, match='entropy'):
|
||||
validate_configuration(Settings(app_env='production', secret_key='A' * 32, data_encryption_key=''))
|
||||
with pytest.raises(RuntimeError, match='DATA_ENCRYPTION_KEY'):
|
||||
validate_configuration(Settings(app_env='production', secret_key='A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6', data_encryption_key='invalid'))
|
||||
|
||||
|
||||
def test_production_configuration_accepts_strong_secrets():
|
||||
values = Settings(
|
||||
app_env='production',
|
||||
secret_key='A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6',
|
||||
data_encryption_key='L5M4sQYVjD1N7pT2Xk8R0aBcDeFgHiJkLmNoPqRsTuV=',
|
||||
)
|
||||
validate_configuration(values)
|
||||
|
||||
|
||||
def test_production_compose_configuration_matches_settings_environment_keys():
|
||||
compose = (ROOT / 'docker-compose.yml').read_text()
|
||||
settings = (ROOT / 'backend' / 'app' / 'core' / 'config.py').read_text()
|
||||
database = (ROOT / 'backend' / 'app' / 'database.py').read_text()
|
||||
|
||||
compose_keys = set(re.findall(r'\b(LINKLOG_[A-Z0-9_]+):', compose))
|
||||
settings_keys = set(re.findall(r"os\.getenv\('([^']+)'", settings + database))
|
||||
|
||||
assert {'LINKLOG_TOKEN_EXPIRY_MINUTES', 'LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS'} <= compose_keys
|
||||
assert compose_keys & settings_keys == compose_keys
|
||||
assert 'LINKLOG_TOKEN_EXPIRY_DAYS' not in compose_keys
|
||||
@@ -1,3 +1,6 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import sqlite3
|
||||
|
||||
from backend.app.database import DEFAULT_TAGS, apply_migrations, get_schema_version, seed_default_tags
|
||||
@@ -7,7 +10,7 @@ def test_database_migrations_are_versioned_and_idempotent():
|
||||
connection = sqlite3.connect(':memory:')
|
||||
|
||||
apply_migrations(connection)
|
||||
assert get_schema_version(connection) == 4
|
||||
assert get_schema_version(connection) == 17
|
||||
tables = {
|
||||
row[0]
|
||||
for row in connection.execute(
|
||||
@@ -24,6 +27,6 @@ def test_database_migrations_are_versioned_and_idempotent():
|
||||
assert set(DEFAULT_TAGS) <= seeded_tags
|
||||
|
||||
apply_migrations(connection)
|
||||
assert get_schema_version(connection) == 4
|
||||
assert get_schema_version(connection) == 17
|
||||
|
||||
connection.close()
|
||||
@@ -0,0 +1,90 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.app.services.email_service import send_password_reset_email, send_test_email, send_verification_email
|
||||
|
||||
|
||||
def test_send_verification_email_uses_smtp_settings(monkeypatch):
|
||||
from backend.app.core.config import settings
|
||||
|
||||
monkeypatch.setattr(settings, 'smtp_host', 'smtp.example.com')
|
||||
monkeypatch.setattr(settings, 'smtp_port', 587)
|
||||
monkeypatch.setattr(settings, 'smtp_from', 'LinkLog <no-reply@example.com>')
|
||||
monkeypatch.setattr(settings, 'smtp_username', 'mailer')
|
||||
monkeypatch.setattr(settings, 'smtp_password', 'secret')
|
||||
monkeypatch.setattr(settings, 'smtp_use_tls', True)
|
||||
monkeypatch.setattr(settings, 'public_url', 'https://linklog.example')
|
||||
|
||||
with patch('backend.app.services.email_service.SMTP') as smtp_class:
|
||||
smtp = smtp_class.return_value.__enter__.return_value
|
||||
send_verification_email('user@example.com', 'user', 'https://linklog.example/verify')
|
||||
|
||||
smtp_class.assert_called_once_with('smtp.example.com', 587, timeout=10)
|
||||
smtp.starttls.assert_called_once_with()
|
||||
smtp.login.assert_called_once_with('mailer', 'secret')
|
||||
message = smtp.send_message.call_args.args[0]
|
||||
assert message['To'] == 'user@example.com'
|
||||
assert 'https://linklog.example/verify' in message.get_body(preferencelist=('plain',)).get_content()
|
||||
html = message.get_body(preferencelist=('html',)).get_content()
|
||||
assert 'cid:linklog-logo' in html
|
||||
assert 'width="50" height="50"' in html
|
||||
assert 'font-family:\'Asset\',Georgia,serif' in html
|
||||
assert 'Hello, a message from' in html
|
||||
assert 'vertical-align:top' in html
|
||||
assert 'padding:20px 0 20px 12px' in html
|
||||
assert 'font-size:18px' in html
|
||||
assert 'href="https://linklog.example"' in html
|
||||
assert '>linklog.example</a>' in html
|
||||
assert any(
|
||||
part.get_content_type() == 'image/svg+xml'
|
||||
and part['Content-ID'] == '<linklog-logo>'
|
||||
for part in message.walk()
|
||||
)
|
||||
|
||||
|
||||
def test_send_test_email_uses_configured_recipient(monkeypatch):
|
||||
from backend.app.core.config import settings
|
||||
|
||||
monkeypatch.setattr(settings, 'smtp_host', 'smtp.example.com')
|
||||
monkeypatch.setattr(settings, 'smtp_from', 'LinkLog <no-reply@example.com>')
|
||||
with patch('backend.app.services.email_service.SMTP') as smtp_class:
|
||||
smtp = smtp_class.return_value.__enter__.return_value
|
||||
send_test_email('admin@example.com')
|
||||
|
||||
message = smtp.send_message.call_args.args[0]
|
||||
assert message['To'] == 'admin@example.com'
|
||||
assert message['Subject'] == 'LinkLog SMTP test'
|
||||
assert message.get_body(preferencelist=('html',)) is not None
|
||||
|
||||
|
||||
def test_password_reset_email_escapes_html_and_includes_logo(monkeypatch):
|
||||
from backend.app.core.config import settings
|
||||
|
||||
monkeypatch.setattr(settings, 'smtp_host', 'smtp.example.com')
|
||||
monkeypatch.setattr(settings, 'smtp_from', 'LinkLog <no-reply@example.com>')
|
||||
with patch('backend.app.services.email_service.SMTP') as smtp_class:
|
||||
smtp = smtp_class.return_value.__enter__.return_value
|
||||
send_password_reset_email('user@example.com', '<User>', 'https://linklog.example/reset?x=1&y=2')
|
||||
|
||||
message = smtp.send_message.call_args.args[0]
|
||||
html = message.get_body(preferencelist=('html',)).get_content()
|
||||
assert '<User>' in html
|
||||
assert 'x=1&y=2' in html
|
||||
assert 'cid:linklog-logo' in html
|
||||
|
||||
|
||||
def test_smtp_password_is_encrypted_at_rest():
|
||||
from backend.app.services.email_service import get_smtp_settings, save_smtp_settings
|
||||
from backend.app.database import get_connection
|
||||
|
||||
values = {
|
||||
'smtp_host': 'smtp.example.com', 'smtp_port': 587, 'smtp_username': 'mailer',
|
||||
'smtp_password': 'secret', 'smtp_from': 'LinkLog <no-reply@example.com>', 'smtp_use_tls': True,
|
||||
}
|
||||
save_smtp_settings(values)
|
||||
with get_connection() as conn:
|
||||
stored = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone()['value']
|
||||
assert 'secret' not in stored
|
||||
assert get_smtp_settings()['smtp_password'] == 'secret'
|
||||
@@ -0,0 +1,34 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from unittest.mock import patch
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.app.services.mastodon_security import open_no_redirect, validate_public_instance
|
||||
|
||||
|
||||
@pytest.mark.parametrize('instance', [
|
||||
'http://mastodon.example',
|
||||
'https://127.0.0.1',
|
||||
'https://[::ffff:127.0.0.1]',
|
||||
'https://user:password@mastodon.example',
|
||||
])
|
||||
def test_mastodon_instance_rejects_unsafe_urls(instance):
|
||||
with pytest.raises(ValueError):
|
||||
validate_public_instance(instance)
|
||||
|
||||
|
||||
def test_mastodon_instance_rejects_private_dns_result():
|
||||
with patch('backend.app.services.mastodon_security.socket.getaddrinfo', return_value=[(2, 1, 6, '', ('10.0.0.5', 443))]):
|
||||
with pytest.raises(ValueError, match='public IP'):
|
||||
validate_public_instance('https://mastodon.example')
|
||||
|
||||
|
||||
def test_mastodon_outbound_redirects_are_rejected():
|
||||
request = Request('https://mastodon.example/api/v1/statuses')
|
||||
with patch('backend.app.services.mastodon_security.NO_REDIRECT_OPENER.open', side_effect=HTTPError(request.full_url, 302, 'Redirects are not allowed', {}, None)):
|
||||
with pytest.raises(HTTPError, match='Redirects are not allowed'):
|
||||
open_no_redirect(request)
|
||||
@@ -1,6 +1,15 @@
|
||||
## Copyright © 2026 Olaf Kolkman
|
||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from PIL import Image
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.app.main import app
|
||||
from backend.app.database import get_connection
|
||||
from backend.app.services.otp_service import current_code
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
@@ -8,7 +17,7 @@ client = TestClient(app)
|
||||
|
||||
def test_user_config_api_and_profile_page():
|
||||
login = client.post('/api/auth/login', json={
|
||||
'username': 'alice',
|
||||
'email': 'alice@example.com',
|
||||
'password': 'secret123',
|
||||
}).json()
|
||||
headers = {'Authorization': f"Bearer {login['access_token']}"}
|
||||
@@ -34,15 +43,19 @@ def test_user_config_api_and_profile_page():
|
||||
assert 'name="avatar" type="file"' in page_response.text
|
||||
assert 'name="avatar_url"' not in page_response.text
|
||||
assert 'value="mastodon.social"' in page_response.text
|
||||
assert 'From my #LinkLog: "' in page_response.text
|
||||
assert 'value="From my #LinkLog: "' in page_response.text
|
||||
assert 'id="auth-menu" class="auth-menu hidden"' in page_response.text
|
||||
assert 'id="auth-home-link" href="/">Home</a>' in page_response.text
|
||||
assert 'id="auth-profile-link" class="hidden"' in page_response.text
|
||||
assert '<a id="auth-username" class="user-name" href="/">' in page_response.text
|
||||
assert 'id="auth-avatar"' not in page_response.text
|
||||
assert 'name="new_password_confirmation"' in page_response.text
|
||||
assert 'id="additional-email-form"' in page_response.text
|
||||
assert 'If you have not downloaded the plugin yet' in page_response.text
|
||||
assert 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi' in page_response.text
|
||||
|
||||
bob_login = client.post('/api/auth/login', json={
|
||||
'username': 'bob',
|
||||
'email': 'bob@example.com',
|
||||
'password': 'secret123',
|
||||
}).json()
|
||||
bob_headers = {'Authorization': f"Bearer {bob_login['access_token']}"}
|
||||
@@ -52,7 +65,7 @@ def test_user_config_api_and_profile_page():
|
||||
}, headers=bob_headers)
|
||||
assert password_response.status_code == 200
|
||||
assert client.post('/api/auth/login', json={
|
||||
'username': 'bob',
|
||||
'email': 'bob@example.com',
|
||||
'password': 'new-secret-123',
|
||||
}).status_code == 200
|
||||
assert client.put('/api/user/password', json={
|
||||
@@ -60,15 +73,117 @@ def test_user_config_api_and_profile_page():
|
||||
'new_password': 'secret123',
|
||||
}, headers=bob_headers).status_code == 200
|
||||
|
||||
image_buffer = BytesIO()
|
||||
Image.new('RGB', (2, 2), 'red').save(image_buffer, format='JPEG')
|
||||
upload_response = client.post(
|
||||
'/api/user/avatar',
|
||||
headers=headers,
|
||||
files={'avatar': ('avatar.png', b'fake-png-data', 'image/png')},
|
||||
files={'avatar': ('avatar.jpg', image_buffer.getvalue(), 'image/jpeg')},
|
||||
)
|
||||
assert upload_response.status_code == 200
|
||||
avatar_url = upload_response.json()['avatar_url']
|
||||
assert avatar_url.startswith('/media/user-1.png')
|
||||
assert client.get(avatar_url).content == b'fake-png-data'
|
||||
stored_avatar = client.get(avatar_url)
|
||||
assert stored_avatar.status_code == 200
|
||||
assert stored_avatar.headers['content-type'] == 'image/png'
|
||||
with Image.open(BytesIO(stored_avatar.content)) as image:
|
||||
assert image.format == 'PNG'
|
||||
assert image.size == (2, 2)
|
||||
|
||||
rejected_upload = client.post(
|
||||
'/api/user/avatar',
|
||||
headers=headers,
|
||||
files={'avatar': ('avatar.png', b'fake-png-data', 'image/png')},
|
||||
)
|
||||
assert rejected_upload.status_code == 415
|
||||
|
||||
updated_profile = client.get('/api/user/me', headers=headers).json()
|
||||
assert updated_profile['avatar_url'] == avatar_url
|
||||
|
||||
|
||||
def test_user_can_enable_and_use_otp():
|
||||
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
|
||||
headers = {'Authorization': f"Bearer {login['access_token']}"}
|
||||
setup = client.post('/api/user/otp/setup', headers=headers)
|
||||
assert setup.status_code == 200
|
||||
secret = setup.json()['secret']
|
||||
assert setup.json()['otpauth_url'].startswith('otpauth://totp/')
|
||||
recovery_codes = setup.json()['recovery_codes']
|
||||
assert len(recovery_codes) == 10
|
||||
|
||||
enabled = client.post('/api/user/otp', headers=headers, json={
|
||||
'action': 'enable', 'code': current_code(secret),
|
||||
})
|
||||
assert enabled.status_code == 200
|
||||
assert enabled.json()['enabled'] is True
|
||||
assert client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).status_code == 401
|
||||
|
||||
otp_login = client.post('/api/auth/login', json={
|
||||
'email': 'alice@example.com', 'password': 'secret123', 'otp': current_code(secret),
|
||||
})
|
||||
assert otp_login.status_code == 200
|
||||
|
||||
disabled = client.post('/api/user/otp', headers=headers, json={
|
||||
'action': 'disable', 'code': current_code(secret), 'current_password': 'secret123',
|
||||
})
|
||||
assert disabled.status_code == 200
|
||||
assert disabled.json()['enabled'] is False
|
||||
|
||||
|
||||
def test_otp_recovery_code_requires_password_and_is_single_use():
|
||||
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
|
||||
headers = {'Authorization': f"Bearer {login['access_token']}"}
|
||||
setup = client.post('/api/user/otp/setup', headers=headers)
|
||||
secret = setup.json()['secret']
|
||||
recovery_code = setup.json()['recovery_codes'][0]
|
||||
assert client.post('/api/user/otp', headers=headers, json={
|
||||
'action': 'enable', 'code': current_code(secret),
|
||||
}).status_code == 200
|
||||
|
||||
rejected = client.post('/api/user/otp/recover', headers=headers, json={
|
||||
'current_password': 'wrong-password', 'recovery_code': recovery_code,
|
||||
})
|
||||
assert rejected.status_code == 400
|
||||
recovered = client.post('/api/user/otp/recover', headers=headers, json={
|
||||
'current_password': 'secret123', 'recovery_code': recovery_code,
|
||||
})
|
||||
assert recovered.status_code == 200
|
||||
reused = client.post('/api/user/otp/recover', headers=headers, json={
|
||||
'current_password': 'secret123', 'recovery_code': recovery_code,
|
||||
})
|
||||
assert reused.status_code == 400
|
||||
|
||||
|
||||
def test_verified_alternative_can_become_primary():
|
||||
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
|
||||
headers = {'Authorization': f"Bearer {login['access_token']}"}
|
||||
with get_connection() as conn:
|
||||
address = conn.execute(
|
||||
'INSERT INTO user_email_addresses (id, user_id, email, verified) VALUES (?, ?, ?, 1) RETURNING id',
|
||||
('alternative-test', 'user-1', 'alice-alternative@example.com'),
|
||||
).fetchone()
|
||||
conn.commit()
|
||||
promoted = client.post(f"/api/user/emails/{address['id']}/make-primary", headers=headers)
|
||||
assert promoted.status_code == 200
|
||||
assert client.post('/api/auth/login', json={'email': 'alice-alternative@example.com', 'password': 'secret123'}).status_code == 200
|
||||
assert client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).status_code == 200
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM user_email_addresses WHERE email IN (?, ?)', ('alice@example.com', 'alice-alternative@example.com'))
|
||||
conn.execute('UPDATE users SET email = ?, email_verified = 1 WHERE id = ?', ('alice@example.com', 'user-1'))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def test_unverified_alternative_cannot_become_primary():
|
||||
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
|
||||
headers = {'Authorization': f"Bearer {login['access_token']}"}
|
||||
with get_connection() as conn:
|
||||
address = conn.execute(
|
||||
'INSERT INTO user_email_addresses (id, user_id, email, verified) VALUES (?, ?, ?, 0) RETURNING id',
|
||||
('unverified-alternative-test', 'user-1', 'alice-unverified@example.com'),
|
||||
).fetchone()
|
||||
conn.commit()
|
||||
rejected = client.post(f"/api/user/emails/{address['id']}/make-primary", headers=headers)
|
||||
assert rejected.status_code == 400
|
||||
with get_connection() as conn:
|
||||
conn.execute('DELETE FROM user_email_addresses WHERE id = ?', (address['id'],))
|
||||
conn.commit()
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# Use with an appropriate .env file
|
||||
|
||||
services:
|
||||
app:
|
||||
image: git.kolkman.org/olaf/link-log:development # or :latest or a version-tag
|
||||
container_name: ${APP_CONTAINER_NAME:-linklog-app}
|
||||
volumes:
|
||||
- ./linklog_data:/app/backend/data
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-production}
|
||||
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
|
||||
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
|
||||
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
|
||||
LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
|
||||
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
|
||||
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
|
||||
LINKLOG_SMTP_HOST: ${LINKLOG_SMTP_HOST:-smtp.example.com}
|
||||
LINKLOG_SMTP_PORT: ${LINKLOG_SMTP_PORT:-587}
|
||||
LINKLOG_SMTP_USERNAME: ${LINKLOG_SMTP_USERNAME:?Set LINKLOG_SMTP_USERNAME in .env}
|
||||
LINKLOG_SMTP_PASSWORD: ${LINKLOG_SMTP_PASSWORD:?Set LINKLOG_SMTP_PASSWORD in .env}
|
||||
LINKLOG_SMTP_FROM: ${LINKLOG_SMTP_FROM:-LinkLog <no-reply@example.com>}
|
||||
LINKLOG_SMTP_USE_TLS: ${LINKLOG_SMTP_USE_TLS:-true}
|
||||
LINKLOG_EMAIL_VERIFICATION_EXPIRY_HOURS: ${LINKLOG_EMAIL_VERIFICATION_EXPIRY_HOURS:-24}
|
||||
LINKLOG_PASSWORD_RESET_EXPIRY_HOURS: ${LINKLOG_PASSWORD_RESET_EXPIRY_HOURS:-1}
|
||||
LINKLOG_MASTODON_CLIENT_NAME: ${LINKLOG_MASTODON_CLIENT_NAME:-LinkLog}
|
||||
LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES: ${LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES:-10}
|
||||
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-INFO}
|
||||
LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
|
||||
restart: ${APP_RESTART_POLICY:-unless-stopped}
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "from urllib.request import urlopen; urlopen('http://127.0.0.1:8000/health', timeout=3)"]
|
||||
interval: ${APP_HEALTHCHECK_INTERVAL:-30s}
|
||||
timeout: ${APP_HEALTHCHECK_TIMEOUT:-5s}
|
||||
start_period: ${APP_HEALTHCHECK_START_PERIOD:-10s}
|
||||
retries: ${APP_HEALTHCHECK_RETRIES:-3}
|
||||
labels:
|
||||
traefik.enable: true
|
||||
traefik.http.middlewares.web-https-redirect.redirectscheme.scheme: https
|
||||
traefik.http.services.linklog.loadbalancer.server.port: 8000
|
||||
traefik.docker.network: linklog_traefik # network to be shared with traefik
|
||||
|
||||
|
||||
traefik.http.routers.linklog.entrypoints: web
|
||||
traefik.http.routers.linklog.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`) # Make sure to change
|
||||
traefik.http.routers.linklog.middlewares: web-https-redirect,servicests # these middlewares must exist
|
||||
traefik.http.routers.linklog-secure.entrypoints: websecure
|
||||
traefik.http.routers.linklog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`) #Make sure to change
|
||||
traefik.http.routers.linklog-secure.tls: true
|
||||
traefik.http.routers.linklog-secure.middlewares: servicests
|
||||
|
||||
traefik.http.routers.linklog-secure.tls.certresolver: myresolver # or your resovler, e.g certbot
|
||||
traefik.http.routers.linklog-secure.service: linklog
|
||||
@@ -0,0 +1,30 @@
|
||||
# Local development only. The production compose file intentionally does not publish port 8000.
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: ${APP_CONTAINER_NAME:-linklog-app-local}
|
||||
ports:
|
||||
- "${APP_PORT:-8000}:8000"
|
||||
volumes:
|
||||
- ./linklog_data:/app/backend/data
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-development}
|
||||
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
|
||||
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
|
||||
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
|
||||
LINKLOG_DATA_ENCRYPTION_KEY: ${LINKLOG_DATA_ENCRYPTION_KEY:?Set LINKLOG_DATA_ENCRYPTION_KEY in .env}
|
||||
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-http://localhost:8000}
|
||||
LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
|
||||
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
|
||||
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-DEBUG}
|
||||
LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
|
||||
restart: ${APP_RESTART_POLICY:-unless-stopped}
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "from urllib.request import urlopen; urlopen('http://127.0.0.1:8000/health', timeout=3)"]
|
||||
interval: ${APP_HEALTHCHECK_INTERVAL:-30s}
|
||||
timeout: ${APP_HEALTHCHECK_TIMEOUT:-5s}
|
||||
start_period: ${APP_HEALTHCHECK_START_PERIOD:-10s}
|
||||
retries: ${APP_HEALTHCHECK_RETRIES:-3}
|
||||
@@ -1,19 +1,24 @@
|
||||
# Copyright © 2026 Olaf Kolkman
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: ${APP_CONTAINER_NAME:-linklog-app}
|
||||
ports:
|
||||
- "${APP_PORT:-8000}:8000"
|
||||
volumes:
|
||||
- linklog_data:/app/backend/data
|
||||
- ./linklog_data:/app/backend/data
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-production}
|
||||
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
|
||||
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
|
||||
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
|
||||
LINKLOG_TOKEN_EXPIRY_DAYS: ${LINKLOG_TOKEN_EXPIRY_DAYS:-30}
|
||||
LINKLOG_DATA_ENCRYPTION_KEY: ${LINKLOG_DATA_ENCRYPTION_KEY:?Set LINKLOG_DATA_ENCRYPTION_KEY in .env}
|
||||
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
|
||||
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-INFO}
|
||||
LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
|
||||
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
|
||||
LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
|
||||
restart: ${APP_RESTART_POLICY:-unless-stopped}
|
||||
healthcheck:
|
||||
@@ -23,27 +28,31 @@ services:
|
||||
start_period: ${APP_HEALTHCHECK_START_PERIOD:-10s}
|
||||
retries: ${APP_HEALTHCHECK_RETRIES:-3}
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.linklog.rule=Host(`${TRAEFIK_HOST:-localhost}`)"
|
||||
- "traefik.http.routers.linklog.entrypoints=web"
|
||||
- "traefik.http.services.linklog.loadbalancer.server.port=8000"
|
||||
traefik.enable: true
|
||||
traefik.http.middlewares.web-https-redirect.redirectscheme.scheme: https
|
||||
traefik.http.services.linklog.loadbalancer.server.port: 8000
|
||||
traefik.docker.network: git_traefik
|
||||
|
||||
traefik:
|
||||
image: ${TRAEFIK_IMAGE:-traefik:v3.1}
|
||||
container_name: ${TRAEFIK_CONTAINER_NAME:-linklog-traefik}
|
||||
command:
|
||||
- --providers.docker=true
|
||||
- --entrypoints.web.address=:${TRAEFIK_HTTP_INTERNAL_PORT:-80}
|
||||
- --api.insecure=${TRAEFIK_API_INSECURE:-true}
|
||||
ports:
|
||||
- "${TRAEFIK_HTTP_PORT:-80}:${TRAEFIK_HTTP_INTERNAL_PORT:-80}"
|
||||
- "${TRAEFIK_DASHBOARD_BIND_ADDRESS:-127.0.0.1}:${TRAEFIK_DASHBOARD_PORT:-8080}:8080"
|
||||
restart: ${TRAEFIK_RESTART_POLICY:-unless-stopped}
|
||||
depends_on:
|
||||
app:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- "${DOCKER_SOCKET_PATH:-/var/run/docker.sock}:/var/run/docker.sock:ro"
|
||||
|
||||
volumes:
|
||||
linklog_data:
|
||||
traefik.http.routers.linklog.entrypoints: web
|
||||
traefik.http.routers.linklog.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
|
||||
traefik.http.routers.linklog.middlewares: web-https-redirect,servicests
|
||||
traefik.http.routers.linklog-secure.entrypoints: websecure
|
||||
traefik.http.routers.linklog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
|
||||
traefik.http.routers.linklog-secure.tls: true
|
||||
traefik.http.routers.linklog-secure.middlewares: servicests
|
||||
|
||||
|
||||
traefik.http.routers.linklog-secure.tls.certresolver: myresolver
|
||||
traefik.http.routers.linklog-secure.service: linklog
|
||||
|
||||
|
||||
|
||||
|
||||
networks:
|
||||
- linklog_traefik
|
||||
|
||||
networks:
|
||||
linklog_traefik:
|
||||
external: true
|
||||
name: linklog_traefik
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Copyright © 2026 Olaf Kolkman
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
set -eu
|
||||
|
||||
chown -R linklog:linklog /app/backend/data
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
(() => {
|
||||
const pluginList = document.querySelector('#plugin-list');
|
||||
const adminLabelList = document.querySelector('#admin-label-list');
|
||||
@@ -5,7 +8,16 @@ const userList = document.querySelector('#user-list');
|
||||
const userForm = document.querySelector('#user-form');
|
||||
const adminControls = document.querySelector('#admin-controls');
|
||||
const adminAuthNotice = document.querySelector('#admin-auth-notice');
|
||||
const smtpForm = document.querySelector('#smtp-form');
|
||||
const smtpTestButton = document.querySelector('#smtp-test-button');
|
||||
const smtpStatus = document.querySelector('#smtp-status');
|
||||
const themesForm = document.querySelector('#themes-form');
|
||||
const themeOptions = document.querySelector('#theme-options');
|
||||
const themeStatus = document.querySelector('#theme-status');
|
||||
let smtpNextAllowedAt = null;
|
||||
let smtpTimerHandle = null;
|
||||
const accessToken = localStorage.getItem('linklogAccessToken');
|
||||
let currentUserId = null;
|
||||
|
||||
function authHeaders(includeJson = false) {
|
||||
return {
|
||||
@@ -14,6 +26,15 @@ function authHeaders(includeJson = false) {
|
||||
};
|
||||
}
|
||||
|
||||
async function responseError(response, fallback) {
|
||||
try {
|
||||
const result = await response.json();
|
||||
return result.detail || result.message || fallback;
|
||||
} catch (error) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function renderPlugins(plugins) {
|
||||
pluginList.replaceChildren(...plugins.map((plugin) => {
|
||||
const row = document.createElement('div');
|
||||
@@ -57,6 +78,60 @@ async function loadLabels() {
|
||||
renderLabels(await response.json());
|
||||
}
|
||||
|
||||
function showSmtpStatus(message, isError = false) {
|
||||
smtpStatus.textContent = message;
|
||||
smtpStatus.style.color = isError ? '#f38ba8' : '#94e2d5';
|
||||
}
|
||||
|
||||
function updateSmtpTimer() {
|
||||
if (smtpTimerHandle) window.clearTimeout(smtpTimerHandle);
|
||||
if (!smtpNextAllowedAt) {
|
||||
smtpTestButton.disabled = false;
|
||||
return;
|
||||
}
|
||||
const seconds = Math.max(0, Math.ceil((smtpNextAllowedAt - Date.now()) / 1000));
|
||||
if (seconds === 0) {
|
||||
smtpNextAllowedAt = null;
|
||||
updateSmtpTimer();
|
||||
return;
|
||||
}
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
showSmtpStatus(`Next validation email available in ${minutes ? `${minutes}m ` : ''}${seconds % 60}s.`);
|
||||
smtpTestButton.disabled = true;
|
||||
smtpTimerHandle = window.setTimeout(updateSmtpTimer, 1000);
|
||||
}
|
||||
|
||||
async function loadSmtpSettings() {
|
||||
const response = await fetch('/api/admin/smtp', {headers: authHeaders()});
|
||||
if (!response.ok) throw new Error('Could not load SMTP settings');
|
||||
const settings = await response.json();
|
||||
for (const [name, value] of Object.entries(settings)) {
|
||||
const field = smtpForm.elements[name];
|
||||
if (!field || name === 'password_configured') continue;
|
||||
if (field.type === 'checkbox') {
|
||||
field.checked = value;
|
||||
} else {
|
||||
field.value = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loadThemes() {
|
||||
const response = await fetch('/api/admin/themes', {headers: authHeaders()});
|
||||
if (!response.ok) throw new Error('Could not load themes');
|
||||
const result = await response.json();
|
||||
themeOptions.replaceChildren(...Object.entries(result.themes).map(([id, theme]) => {
|
||||
const label = document.createElement('label');
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.name = 'theme';
|
||||
checkbox.value = id;
|
||||
checkbox.checked = result.enabled.includes(id);
|
||||
label.append(checkbox, document.createTextNode(` ${theme.label}`));
|
||||
return label;
|
||||
}));
|
||||
}
|
||||
|
||||
function renderUsers(users) {
|
||||
userList.replaceChildren(...users.map((user) => {
|
||||
const row = document.createElement('div');
|
||||
@@ -68,19 +143,52 @@ function renderUsers(users) {
|
||||
const privilegeCheckbox = document.createElement('input');
|
||||
privilegeCheckbox.type = 'checkbox';
|
||||
privilegeCheckbox.checked = user.is_admin;
|
||||
const isCurrentUser = user.id === currentUserId;
|
||||
privilegeCheckbox.disabled = isCurrentUser;
|
||||
privilegeCheckbox.setAttribute('aria-label', `Administrator rights for ${user.username}`);
|
||||
privilegeCheckbox.addEventListener('change', () => updateUserPrivilege(user, privilegeCheckbox));
|
||||
if (!isCurrentUser) {
|
||||
privilegeCheckbox.addEventListener('change', () => updateUserPrivilege(user, privilegeCheckbox));
|
||||
}
|
||||
privilegeLabel.append(privilegeCheckbox, document.createTextNode(' Administrator'));
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'danger-button';
|
||||
button.textContent = 'Remove';
|
||||
button.addEventListener('click', () => removeUser(user, button));
|
||||
row.append(label, privilegeLabel, button);
|
||||
row.append(label, privilegeLabel);
|
||||
if (!isCurrentUser) {
|
||||
const otpButton = document.createElement('button');
|
||||
otpButton.type = 'button';
|
||||
otpButton.textContent = 'Reset OTP';
|
||||
otpButton.addEventListener('click', () => resetUserOtp(user, otpButton));
|
||||
row.append(otpButton);
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'danger-button';
|
||||
button.textContent = 'Remove';
|
||||
button.addEventListener('click', () => removeUser(user, button));
|
||||
row.append(button);
|
||||
}
|
||||
return row;
|
||||
}));
|
||||
}
|
||||
|
||||
async function resetUserOtp(user, button) {
|
||||
if (!window.confirm(`Disable OTP for ${user.username}?`)) return;
|
||||
button.disabled = true;
|
||||
const status = document.querySelector('#user-status');
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(user.id)}/otp/reset`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(await responseError(response, `Request failed (${response.status})`));
|
||||
}
|
||||
status.textContent = `OTP disabled for ${user.username}.`;
|
||||
status.style.color = '#94e2d5';
|
||||
} catch (error) {
|
||||
status.textContent = `Could not reset OTP for ${user.username}: ${error.message}`;
|
||||
status.style.color = '#f38ba8';
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
const response = await fetch('/api/admin/users', {headers: authHeaders()});
|
||||
if (!response.ok) throw new Error('Could not load users');
|
||||
@@ -108,7 +216,7 @@ async function loadAdminState() {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionResponse = await fetch(`/api/auth/me?token=${encodeURIComponent(accessToken)}`);
|
||||
const sessionResponse = await fetch('/api/auth/me', {headers: authHeaders()});
|
||||
if (!sessionResponse.ok) {
|
||||
localStorage.removeItem('linklogAccessToken');
|
||||
showSignedOutState();
|
||||
@@ -116,12 +224,13 @@ async function loadAdminState() {
|
||||
}
|
||||
|
||||
const user = await sessionResponse.json();
|
||||
currentUserId = user.id;
|
||||
if (!user.is_admin) {
|
||||
showUnauthorizedState();
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all([loadUsers(), loadPlugins(), loadLabels()]);
|
||||
await Promise.all([loadUsers(), loadPlugins(), loadLabels(), loadSmtpSettings(), loadThemes()]);
|
||||
showAdminState(true);
|
||||
}
|
||||
|
||||
@@ -148,13 +257,22 @@ async function updatePlugin(plugin, button) {
|
||||
async function removeUser(user, button) {
|
||||
if (!window.confirm(`Remove ${user.username}?`)) return;
|
||||
button.disabled = true;
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(user.id)}`, {
|
||||
method: 'DELETE',
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (response.ok) {
|
||||
const status = document.querySelector('#user-status');
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(user.id)}`, {
|
||||
method: 'DELETE',
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const detail = await response.text();
|
||||
throw new Error(detail || `Request failed (${response.status})`);
|
||||
}
|
||||
await loadUsers();
|
||||
} else {
|
||||
status.textContent = `Removed ${user.username}.`;
|
||||
status.style.color = '#94e2d5';
|
||||
} catch (error) {
|
||||
status.textContent = `Could not remove ${user.username}: ${error.message}`;
|
||||
status.style.color = '#f38ba8';
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
@@ -178,20 +296,80 @@ userForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const values = Object.fromEntries(new FormData(userForm));
|
||||
values.is_admin = userForm.elements.is_admin.checked;
|
||||
const response = await fetch('/api/admin/users', {
|
||||
method: 'POST',
|
||||
headers: authHeaders(true),
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
const status = document.querySelector('#user-status');
|
||||
status.textContent = response.ok ? 'User added.' : 'Could not add user.';
|
||||
status.style.color = response.ok ? '#94e2d5' : '#f38ba8';
|
||||
if (response.ok) {
|
||||
userForm.reset();
|
||||
await loadUsers();
|
||||
try {
|
||||
const response = await fetch('/api/admin/users', {
|
||||
method: 'POST',
|
||||
headers: authHeaders(true),
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
status.textContent = response.ok ? 'User added.' : await responseError(response, 'Could not add user.');
|
||||
status.style.color = response.ok ? '#94e2d5' : '#f38ba8';
|
||||
if (response.ok) {
|
||||
userForm.reset();
|
||||
await loadUsers();
|
||||
}
|
||||
} catch (error) {
|
||||
status.textContent = `Could not add user: ${error.message}`;
|
||||
status.style.color = '#f38ba8';
|
||||
}
|
||||
});
|
||||
|
||||
smtpForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const values = Object.fromEntries(new FormData(smtpForm));
|
||||
values.smtp_port = Number(values.smtp_port);
|
||||
values.smtp_use_tls = smtpForm.elements.smtp_use_tls.checked;
|
||||
try {
|
||||
const response = await fetch('/api/admin/smtp', {
|
||||
method: 'PUT',
|
||||
headers: authHeaders(true),
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
showSmtpStatus(response.ok ? 'SMTP settings saved.' : await responseError(response, 'Could not save SMTP settings.'), !response.ok);
|
||||
if (response.ok) smtpForm.elements.smtp_password.value = '';
|
||||
} catch (error) {
|
||||
showSmtpStatus(`Could not save SMTP settings: ${error.message}`, true);
|
||||
}
|
||||
});
|
||||
|
||||
smtpTestButton.addEventListener('click', async () => {
|
||||
smtpTestButton.disabled = true;
|
||||
const values = Object.fromEntries(new FormData(smtpForm));
|
||||
values.smtp_port = Number(values.smtp_port);
|
||||
values.smtp_use_tls = smtpForm.elements.smtp_use_tls.checked;
|
||||
try {
|
||||
const response = await fetch('/api/admin/smtp/test', {
|
||||
method: 'POST',
|
||||
headers: authHeaders(true),
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
const result = response.ok ? await response.json() : {};
|
||||
showSmtpStatus(response.ok ? result.message : await responseError(response, 'SMTP validation failed.'), !response.ok);
|
||||
if (response.headers.get('Retry-After')) {
|
||||
smtpNextAllowedAt = Date.now() + Number(response.headers.get('Retry-After')) * 1000;
|
||||
} else if (result.next_allowed_at) {
|
||||
smtpNextAllowedAt = Date.parse(result.next_allowed_at);
|
||||
}
|
||||
} catch (error) {
|
||||
showSmtpStatus(`SMTP validation failed: ${error.message}`, true);
|
||||
}
|
||||
updateSmtpTimer();
|
||||
});
|
||||
|
||||
themesForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const themes = [...themesForm.querySelectorAll('input[name="theme"]:checked')].map((input) => input.value);
|
||||
const response = await fetch('/api/admin/themes', {
|
||||
method: 'PUT',
|
||||
headers: authHeaders(true),
|
||||
body: JSON.stringify({themes}),
|
||||
});
|
||||
const result = await response.json();
|
||||
themeStatus.textContent = response.ok ? 'Themes saved.' : (result.detail || 'Could not save themes.');
|
||||
themeStatus.style.color = response.ok ? '#94e2d5' : '#f38ba8';
|
||||
});
|
||||
|
||||
loadAdminState().catch((error) => {
|
||||
showAdminState(false);
|
||||
adminAuthNotice.textContent = accessToken
|
||||
@@ -201,5 +379,7 @@ loadAdminState().catch((error) => {
|
||||
userList.textContent = '';
|
||||
pluginList.textContent = '';
|
||||
adminLabelList.textContent = '';
|
||||
smtpForm.reset();
|
||||
themesForm.reset();
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
(() => {
|
||||
const loginButton = document.querySelector('#auth-login-button');
|
||||
const profileLink = document.querySelector('#auth-profile-link');
|
||||
@@ -44,7 +47,7 @@
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`/api/auth/me?token=${encodeURIComponent(token)}`)
|
||||
fetch('/api/auth/me', {headers: {Authorization: `Bearer ${token}`}})
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error('Session expired');
|
||||
return response.json();
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
const feedEl = document.getElementById('feed');
|
||||
const sortSelect = document.getElementById('sort-select');
|
||||
const userFilter = document.getElementById('user-filter');
|
||||
@@ -101,46 +104,99 @@ function renderFeed(items, showIdentity = true) {
|
||||
|
||||
const comment = document.createElement('div');
|
||||
comment.className = 'comment';
|
||||
comment.textContent = item.comment || 'No comment provided';
|
||||
comment.textContent = item.comment || '';
|
||||
|
||||
const entryMeta = document.createElement('div');
|
||||
entryMeta.className = 'entry-meta';
|
||||
|
||||
if (item.tags?.length) {
|
||||
const tags = document.createElement('div');
|
||||
tags.className = 'entry-tags';
|
||||
tags.textContent = item.tags.join(' ');
|
||||
article.appendChild(tags);
|
||||
tags.textContent = item.tags.join(' ');
|
||||
entryMeta.appendChild(tags);
|
||||
}
|
||||
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'meta';
|
||||
meta.textContent = formatDate(item.created_at);
|
||||
entryMeta.appendChild(meta);
|
||||
|
||||
if (item.is_owner) {
|
||||
if (item.is_owner && !showIdentity) {
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'entry-actions';
|
||||
const editButton = document.createElement('button');
|
||||
editButton.type = 'button';
|
||||
editButton.className = 'edit-button';
|
||||
editButton.textContent = 'Edit';
|
||||
editButton.addEventListener('click', () => showEditForm(article, item));
|
||||
article.appendChild(editButton);
|
||||
const deleteButton = document.createElement('button');
|
||||
deleteButton.type = 'button';
|
||||
deleteButton.className = 'delete-button';
|
||||
deleteButton.textContent = 'Delete';
|
||||
deleteButton.addEventListener('click', () => deleteEntry(item, deleteButton));
|
||||
const mastodonButton = document.createElement('button');
|
||||
mastodonButton.type = 'button';
|
||||
mastodonButton.className = `mastodon-button${item.mastodon_posted ? ' posted' : ''}`;
|
||||
const mastodonLogo = document.createElement('img');
|
||||
mastodonLogo.src = '/static/mastodon.svg';
|
||||
mastodonLogo.alt = '';
|
||||
mastodonButton.append(mastodonLogo, document.createTextNode(item.mastodon_posted ? 'Post again' : 'Post to Mastodon'));
|
||||
mastodonButton.addEventListener('click', () => postToMastodon(item, mastodonButton));
|
||||
actions.append(editButton, deleteButton);
|
||||
article.appendChild(actions);
|
||||
article.appendChild(mastodonButton);
|
||||
}
|
||||
|
||||
if (showIdentity) {
|
||||
const header = document.createElement('div');
|
||||
header.className = 'link-header';
|
||||
header.appendChild(createAvatar(item.user));
|
||||
|
||||
const username = item.user?.username || 'unknown';
|
||||
const profileLink = document.createElement('a');
|
||||
profileLink.className = 'user-link';
|
||||
profileLink.href = `/${encodeURIComponent(username)}/`;
|
||||
profileLink.setAttribute('aria-label', `View ${username}'s profile`);
|
||||
profileLink.appendChild(createAvatar(item.user));
|
||||
const userName = document.createElement('div');
|
||||
userName.className = 'user-name';
|
||||
userName.textContent = item.user?.username || 'unknown';
|
||||
header.appendChild(userName);
|
||||
userName.textContent = username;
|
||||
profileLink.appendChild(userName);
|
||||
header.appendChild(profileLink);
|
||||
article.appendChild(header);
|
||||
}
|
||||
article.appendChild(title);
|
||||
article.appendChild(comment);
|
||||
article.appendChild(meta);
|
||||
article.appendChild(entryMeta);
|
||||
feedEl.appendChild(article);
|
||||
});
|
||||
}
|
||||
|
||||
async function postToMastodon(item, button) {
|
||||
button.disabled = true;
|
||||
const response = await fetch(`/api/links/${encodeURIComponent(item.id)}/mastodon`, {
|
||||
method: 'POST',
|
||||
headers: {Authorization: `Bearer ${accessToken}`},
|
||||
});
|
||||
if (response.ok) {
|
||||
await loadFeed();
|
||||
} else {
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteEntry(item, button) {
|
||||
if (!window.confirm(`Delete this link?`)) return;
|
||||
button.disabled = true;
|
||||
const response = await fetch(`/api/links/${encodeURIComponent(item.id)}`, {
|
||||
method: 'DELETE',
|
||||
headers: {Authorization: `Bearer ${accessToken}`},
|
||||
});
|
||||
if (response.ok) {
|
||||
await loadFeed();
|
||||
} else {
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function showEditForm(article, item) {
|
||||
if (article.querySelector('.edit-form')) return;
|
||||
const form = document.createElement('form');
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
const form = document.querySelector('#login-form');
|
||||
const status = document.querySelector('#login-status');
|
||||
|
||||
@@ -9,11 +12,16 @@ form.addEventListener('submit', async (event) => {
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(Object.fromEntries(new FormData(form))),
|
||||
body: JSON.stringify({
|
||||
email: form.elements.email.value.trim(),
|
||||
password: form.elements.password.value,
|
||||
otp: form.elements.otp.value.trim() || null,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
status.textContent = 'Sign-in failed.';
|
||||
const result = await response.json().catch(() => ({}));
|
||||
status.textContent = result.detail || 'Sign-in failed.';
|
||||
status.style.color = '#b91c1c';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
|
||||
<g transform="matrix(1,0,0,1,-669.006,-255.89)">
|
||||
<g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)">
|
||||
<rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(24, 24, 37);"/>
|
||||
</g>
|
||||
<g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)">
|
||||
<path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/>
|
||||
</g>
|
||||
<g transform="matrix(0.135097,0,0,0.266653,668.366,1282.68)">
|
||||
<path d="M846.315,1802.1L846.315,1747.02C926.615,1744.29 989.248,1732.47 1034.22,1711.57C1079.18,1690.67 1110.8,1656.2 1129.07,1608.15C1147.34,1560.11 1156.47,1494.29 1156.47,1410.69C1156.47,1348.97 1150.95,1297.51 1139.91,1256.3C1128.87,1215.09 1110.5,1182.76 1084.81,1159.33C1067.94,1144.48 1048.07,1132.76 1025.18,1124.17C1002.3,1115.58 975.999,1109.52 946.288,1106.01C916.577,1102.49 883.253,1100.73 846.315,1100.73L846.315,1045.65L2092.36,1045.65L2092.36,1100.73C2037.36,1100.73 1990.18,1104.93 1950.83,1113.33C1911.49,1121.73 1879.47,1137.06 1854.78,1159.33C1830.08,1181.59 1811.92,1212.94 1800.27,1253.37C1788.63,1293.8 1782.81,1346.24 1782.81,1410.69L1782.81,1744.09C1860.7,1744.09 1935.18,1732.66 2006.24,1709.81C2077.31,1686.96 2140.34,1657.18 2195.35,1620.46C2250.35,1584.13 2294.21,1543.51 2326.94,1498.58C2359.66,1453.66 2377.83,1409.91 2381.44,1367.33L2444.68,1367.33C2444.68,1388.82 2444.07,1418.6 2442.87,1456.69C2441.66,1494.78 2439.86,1536.28 2437.45,1581.2C2434.64,1626.9 2431.33,1668.9 2427.51,1707.18C2423.7,1745.46 2419.18,1777.1 2413.96,1802.1L846.315,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M3043.37,1093.7C3001.22,1093.7 2961.37,1089.99 2923.83,1082.57C2886.29,1075.15 2853.66,1064.99 2825.96,1052.1C2797.86,1039.21 2775.67,1024.17 2759.41,1006.98C2743.15,989.794 2735.02,971.435 2735.02,951.904C2735.02,924.951 2748.97,900.732 2776.88,879.247C2804.78,857.763 2842.12,840.673 2888.9,827.978C2935.67,815.283 2987.16,808.935 3043.37,808.935C3101.59,808.935 3153.98,815.38 3200.56,828.271C3247.13,841.161 3284.07,858.447 3311.37,880.126C3338.67,901.806 3352.32,925.732 3352.32,951.904C3352.32,977.294 3338.67,1000.83 3311.37,1022.51C3284.07,1044.19 3247.13,1061.47 3200.56,1074.37C3153.98,1087.26 3101.59,1093.7 3043.37,1093.7ZM2498.94,1802.1L2498.94,1747.02C2608.95,1743.12 2686.24,1720.16 2730.81,1678.17C2775.37,1636.18 2797.66,1576.9 2797.66,1500.34C2797.66,1422.22 2776.08,1365.97 2732.91,1331.59C2689.75,1297.22 2618.39,1280.03 2518.82,1280.03L2518.82,1224.95L3327.03,1172.22L3327.03,1500.34C3327.03,1551.12 3333.76,1594.38 3347.2,1630.13C3360.66,1665.87 3386.05,1693.6 3423.39,1713.33C3460.73,1733.06 3515.53,1744.29 3587.8,1747.02L3587.8,1802.1L2498.94,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M3625.19,1802.1L3625.19,1747.02C3724.76,1743.12 3796.43,1721.83 3840.19,1683.15C3862.68,1663.62 3878.94,1639.6 3888.97,1611.08C3899.01,1582.57 3904.03,1549.17 3904.03,1510.89C3904.03,1447.22 3894.7,1399.37 3876.03,1367.33C3857.36,1335.3 3827.64,1313.72 3786.89,1302.59C3746.14,1291.45 3692.24,1285.89 3625.19,1285.89L3625.19,1230.81L4433.4,1178.08L4433.4,1274.76C4505.67,1243.51 4581.56,1216.94 4661.05,1195.07C4740.55,1173.19 4822.65,1162.26 4907.37,1162.26C4940.29,1162.26 4973.62,1164.31 5007.34,1168.41C5041.07,1172.51 5073.19,1183.93 5103.7,1202.68C5122.98,1214.79 5139.84,1231.2 5154.29,1251.9C5168.34,1273 5179.59,1299.17 5188.02,1330.42C5196.45,1361.67 5200.66,1399.37 5200.66,1443.51L5199.46,1488.62C5198.26,1504.25 5197.65,1521.24 5197.65,1539.6C5197.65,1573.97 5199.46,1604.15 5203.07,1630.13C5206.69,1656.1 5215.92,1677.68 5230.78,1694.87C5245.23,1712.06 5267.51,1725.05 5297.63,1733.84C5327.74,1742.63 5369.29,1747.02 5422.29,1747.02L5422.29,1802.1L4575.53,1802.1L4575.53,1757.57C4601.63,1741.16 4619.7,1713.62 4629.74,1674.95C4639.77,1636.28 4644.79,1583.35 4644.79,1516.16C4644.79,1457.96 4639.47,1415.09 4628.83,1387.55C4618.19,1360.01 4603.74,1342.14 4585.47,1333.93C4567.2,1325.73 4546.83,1321.63 4524.34,1321.63C4510.29,1321.63 4495.54,1323.1 4480.08,1326.03C4464.62,1328.95 4449.06,1332.96 4433.4,1338.04L4433.4,1526.71C4433.4,1595.07 4438.52,1646.53 4448.76,1681.1C4459,1715.67 4476.97,1741.16 4502.66,1757.57L4502.66,1802.1L3625.19,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M6760.3,1835.5C6693.65,1835.5 6638.55,1833.06 6594.99,1828.17C6551.42,1823.29 6518.2,1814.4 6495.32,1801.51C6481.26,1793.7 6469.62,1783.35 6460.39,1770.46C6451.55,1757.96 6444.73,1743.31 6439.91,1726.51C6435.09,1709.72 6430.67,1690.38 6426.66,1668.51C6422.64,1647.41 6416.92,1627.68 6409.49,1609.33C6402.07,1590.97 6387.21,1575.83 6364.93,1563.91C6342.65,1552 6306.81,1545.85 6257.43,1545.46C6258.23,1615.38 6265.66,1666.45 6279.71,1698.68C6293.76,1730.91 6320.86,1747.02 6361.01,1747.02L6361.01,1802.1L5449.21,1802.1L5449.21,1747.02C5485.35,1745.85 5517.27,1742.92 5544.97,1738.23C5600.78,1728.86 5642.33,1707.96 5669.64,1675.54C5683.69,1658.35 5695.13,1636.87 5703.96,1611.08C5712.4,1585.3 5718.52,1554.15 5722.33,1517.63C5726.15,1481.1 5728.05,1438.43 5728.05,1389.6C5728.05,1315.38 5722.84,1255.22 5712.4,1209.13C5701.96,1163.04 5685.49,1127.1 5663.01,1101.32C5640.53,1075.93 5611.72,1058.74 5576.59,1049.76C5541.46,1040.77 5499,1036.28 5449.21,1036.28L5449.21,981.786L6257.43,929.052L6257.43,1462.84C6286.74,1442.92 6314.84,1422.12 6341.74,1400.44C6368.64,1378.76 6392.33,1358.54 6412.81,1339.79C6457.78,1298.39 6480.26,1272.8 6480.26,1263.04C6480.26,1255.22 6471.63,1250.15 6454.36,1247.8C6437.1,1245.46 6413.61,1244.29 6383.9,1244.29L6383.9,1189.21L7053.6,1189.21L7053.6,1244.29C7005.82,1244.29 6953.42,1249.76 6896.41,1260.69C6839.4,1271.63 6778.97,1288.04 6715.14,1309.91C6650.9,1331.79 6583.85,1359.33 6513.99,1392.53C6444.12,1425.73 6372.46,1464.6 6298.98,1509.13C6373.66,1497.41 6449.04,1488.13 6525.13,1481.3C6601.21,1474.46 6668.36,1471.04 6726.58,1471.04C6810.89,1471.04 6875.33,1480.42 6919.9,1499.17C6965.67,1518.7 6994.58,1550.34 7006.62,1594.09C7013.85,1619.87 7023.18,1641.94 7034.63,1660.3C7046.07,1678.66 7058.21,1693.9 7071.06,1706.01C7083.91,1718.12 7096.86,1727.2 7109.91,1733.25C7122.96,1739.31 7134.3,1742.92 7143.93,1744.09L7143.93,1805.62C7133.49,1808.74 7116.23,1811.96 7092.14,1815.28C7068.05,1818.6 7039.14,1821.83 7005.42,1824.95C6971.29,1828.08 6933.35,1830.62 6891.59,1832.57C6849.84,1834.52 6806.07,1835.5 6760.3,1835.5Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M7746.18,1802.1L7746.18,1747.02C7826.48,1744.29 7889.11,1732.47 7934.08,1711.57C7979.05,1690.67 8010.67,1656.2 8028.93,1608.15C8047.2,1560.11 8056.34,1494.29 8056.34,1410.69C8056.34,1348.97 8050.82,1297.51 8039.77,1256.3C8028.73,1215.09 8010.36,1182.76 7984.67,1159.33C7967.81,1144.48 7947.93,1132.76 7925.05,1124.17C7902.16,1115.58 7875.86,1109.52 7846.15,1106.01C7816.44,1102.49 7783.12,1100.73 7746.18,1100.73L7746.18,1045.65L8992.23,1045.65L8992.23,1100.73C8937.22,1100.73 8890.05,1104.93 8850.7,1113.33C8811.35,1121.73 8779.33,1137.06 8754.64,1159.33C8729.95,1181.59 8711.78,1212.94 8700.14,1253.37C8688.49,1293.8 8682.67,1346.24 8682.67,1410.69L8682.67,1744.09C8760.56,1744.09 8835.04,1732.66 8906.1,1709.81C8977.17,1686.96 9040.2,1657.18 9095.21,1620.46C9150.22,1584.13 9194.08,1543.51 9226.8,1498.58C9259.52,1453.66 9277.69,1409.91 9281.3,1367.33L9344.54,1367.33C9344.54,1388.82 9343.94,1418.6 9342.73,1456.69C9341.53,1494.78 9339.72,1536.28 9337.31,1581.2C9334.5,1626.9 9331.19,1668.9 9327.38,1707.18C9323.56,1745.46 9319.05,1777.1 9313.83,1802.1L7746.18,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M10190.6,1828.47C10046.1,1828.47 9919.52,1816.36 9810.91,1792.14C9702.31,1767.92 9617.89,1731.2 9557.67,1681.98C9497.44,1632.76 9467.33,1570.65 9467.33,1495.65C9467.33,1439.01 9484.69,1389.6 9519.43,1347.41C9554.15,1305.22 9603.24,1270.46 9666.67,1243.12C9730.11,1215.38 9806.19,1194.87 9894.93,1181.59C9983.66,1168.31 10082.2,1161.67 10190.6,1161.67C10298.6,1161.67 10397.2,1168.31 10486.3,1181.59C10575.5,1194.87 10651.5,1215.38 10714.6,1243.12C10778,1270.46 10827,1305.22 10861.5,1347.41C10896.1,1389.6 10913.3,1439.01 10913.3,1495.65C10913.3,1551.9 10896.1,1600.83 10861.5,1642.43C10827,1684.03 10778,1718.7 10714.6,1746.43C10651.5,1773.78 10575.5,1794.29 10486.3,1807.96C10397.2,1821.63 10298.6,1828.47 10190.6,1828.47ZM10190.6,1766.94C10209.5,1766.94 10226.5,1759.62 10241.5,1744.97C10256.6,1730.32 10269.5,1710.5 10280.4,1685.5C10302,1634.72 10312.9,1571.43 10312.9,1495.65C10312.9,1419.09 10302,1355.22 10280.4,1304.05C10269.5,1279.05 10256.6,1259.13 10241.5,1244.29C10226.5,1229.44 10209.5,1222.02 10190.6,1222.02C10171.4,1222.02 10154.2,1229.44 10139.1,1244.29C10124.1,1259.13 10111.3,1279.05 10100.9,1304.05C10090.1,1329.05 10081.8,1358.06 10076.2,1391.06C10070.6,1424.07 10067.8,1458.93 10067.8,1495.65C10067.8,1531.98 10070.6,1566.55 10076.2,1599.37C10081.8,1632.18 10090.1,1660.89 10100.9,1685.5C10111.3,1710.5 10124.1,1730.32 10139.1,1744.97C10154.2,1759.62 10171.4,1766.94 10190.6,1766.94Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M11680.5,2098C11591.8,2098 11505.8,2096.73 11422.7,2094.19C11339.6,2091.65 11261.9,2085.5 11189.7,2075.73C11166.4,2072.61 11144.8,2069.09 11124.9,2065.18C11105,2061.28 11086.5,2056.79 11069.2,2051.71C11035.1,2041.55 11008.3,2029.35 10988.8,2015.09C10969.3,2000.83 10959.6,1983.54 10959.6,1963.23C10959.6,1947.22 10967.4,1932.86 10983.1,1920.16C10998.7,1907.47 11020,1896.43 11046.9,1887.06C11073.4,1877.68 11104.1,1869.58 11139.1,1862.74C11174,1855.91 11210.7,1850.34 11249.3,1846.04C11216.4,1832.37 11189.8,1815.87 11169.5,1796.53C11149.2,1777.2 11139.1,1755.22 11139.1,1730.62C11139.1,1713.43 11144.3,1697.51 11154.7,1682.86C11165.2,1668.21 11179.4,1654.83 11197.5,1642.72C11233.2,1618.51 11279.6,1600.34 11336.6,1588.23C11278.4,1578.86 11227.2,1565.77 11183,1548.97C11138.9,1532.18 11104.2,1511.18 11079.1,1485.99C11054.1,1460.79 11041.5,1431.01 11041.5,1396.63C11041.5,1355.62 11059.5,1319.97 11095.4,1289.7C11131.3,1259.42 11179,1235.11 11238.4,1216.75C11297.5,1198.39 11365.3,1184.72 11442,1175.73C11518.7,1166.75 11599.2,1162.26 11683.5,1162.26C11753.4,1162.26 11820.9,1165.28 11886.2,1171.34C11951.4,1177.39 12011.7,1187.06 12067.1,1200.34C12080.8,1169.48 12099,1145.46 12121.9,1128.27C12144.8,1111.08 12170.6,1098.68 12199.3,1091.06C12228,1083.45 12257.7,1078.76 12288.5,1077C12319.2,1075.24 12349.2,1074.37 12378.5,1074.37C12397.4,1074.37 12418.1,1074.56 12440.8,1074.95C12463.5,1075.34 12488.3,1076.32 12515.2,1077.88C12512.8,1088.82 12510.6,1103.86 12508.6,1123C12506.6,1142.14 12501.5,1159.13 12493.5,1173.97C12484.7,1190.38 12467.6,1201.71 12442.3,1207.96C12417,1214.21 12393.1,1217.33 12370.7,1217.33L12230.9,1217.33C12215.7,1217.33 12200.9,1217.63 12186.7,1218.21C12172.4,1218.8 12159.1,1220.46 12146.6,1223.19C12200.4,1241.55 12243.7,1265.09 12276.4,1293.8C12309.1,1322.51 12325.5,1356.79 12325.5,1396.63C12325.5,1438.04 12307.6,1472.7 12271.9,1500.63C12236.2,1528.56 12188.6,1550.54 12129.2,1566.55C12069.3,1582.57 12001.4,1594.09 11925.3,1601.12C11849.2,1608.15 11768.6,1611.67 11683.5,1611.67C11638.5,1611.67 11594.4,1610.79 11551,1609.03C11507.6,1607.28 11465.7,1604.25 11425.1,1599.95L11425.7,1602.88C11413.7,1602.88 11402.2,1606.4 11391.4,1613.43C11380.6,1620.46 11375.1,1629.25 11375.1,1639.79C11375.1,1649.17 11380.5,1657.18 11391.1,1663.82C11401.7,1670.46 11415.7,1675.73 11433,1679.64C11450.6,1683.54 11470.8,1686.38 11493.5,1688.13C11516.2,1689.89 11540,1690.77 11564.9,1690.77L11884,1690.77C11957.1,1690.77 12026.9,1691.06 12093.3,1691.65C12159.8,1692.24 12222.1,1697.61 12280.3,1707.76C12334.1,1716.75 12377.9,1733.25 12411.6,1757.28C12445.3,1781.3 12462.2,1815.58 12462.2,1860.11C12462.2,1897.61 12450.8,1929.44 12427.9,1955.62C12405,1981.79 12373.6,2003.56 12333.6,2020.95C12293.7,2038.33 12247.8,2052.29 12196,2062.84C12145,2073 12090.1,2080.62 12031.3,2085.69C11972.5,2090.77 11913.1,2094.09 11853,2095.65C11793,2097.22 11735.5,2098 11680.5,2098ZM11682.9,1547.22C11712.2,1547.22 11735.9,1539.79 11754,1524.95C11772,1510.11 11785.2,1490.58 11793.4,1466.36C11801.6,1442.14 11805.8,1415.77 11805.8,1387.26C11805.8,1341.94 11796.3,1303.76 11777.4,1272.7C11758.6,1241.65 11727.1,1226.12 11682.9,1226.12C11639.1,1226.12 11607.9,1241.65 11589.2,1272.7C11570.6,1303.76 11561.2,1341.94 11561.2,1387.26C11561.2,1415.38 11565.4,1441.65 11573.6,1466.06C11581.8,1490.48 11594.9,1510.11 11612.7,1524.95C11630.6,1539.79 11654,1547.22 11682.9,1547.22ZM11708.2,2035.3C11747.1,2035.3 11786.1,2034.62 11825,2033.25C11864,2031.88 11899.5,2028.66 11931.6,2023.58C11964.1,2018.9 11990.8,2011.87 12011.7,2002.49C12032.6,1993.12 12043,1980.62 12043,1964.99C12043,1947.02 12029.1,1933.25 12001.2,1923.68C11973.3,1914.11 11935.4,1906.98 11887.7,1902.29C11839.5,1897.61 11782.4,1894.78 11716.3,1893.8C11650.3,1892.82 11579.1,1892.33 11502.8,1892.33C11490.8,1892.33 11478.6,1891.94 11466.4,1891.16C11454.1,1890.38 11442,1889.4 11430,1888.23C11404.3,1905.81 11391.4,1929.44 11391.4,1959.13C11391.4,1974.76 11398.9,1987.55 11414,1997.51C11429,2007.47 11450.4,2015.18 11478.1,2020.65C11505.8,2026.12 11539.2,2029.93 11578.1,2032.08C11617.1,2034.23 11660.4,2035.3 11708.2,2035.3Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 14 KiB |
@@ -1,3 +1,6 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
(() => {
|
||||
const logoutButton = document.querySelector('#logout-button');
|
||||
|
||||
@@ -9,8 +12,7 @@ logoutButton.addEventListener('click', async () => {
|
||||
if (token) {
|
||||
await fetch('/api/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({token}),
|
||||
headers: {Authorization: `Bearer ${token}`},
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img" aria-label="Mastodon">
|
||||
<path fill="currentColor" d="M21.6 8.2c0-4.1-2.7-5.3-2.7-5.3C17.5 2.3 14.8 2 12 2h-.1c-2.8 0-5.5.3-6.9.9 0 0-2.7 1.2-2.7 5.3 0 .9 0 2 0 3.1 0 4.2.3 8.3 1.8 9.4 1.7 1.3 4.1 1.6 6.1 1.7 1.9.1 3.6-.4 3.6-.4l-.1-1.8s-1.6.5-3.5.4c-1.8-.1-3.6-.2-3.9-2.1-.1-.5-.1-1-.1-1.5 0 0 1.7.4 3.9.5 1.3.1 2.6.1 3.9-.1 2.5-.3 4.7-.8 4.7-.8v-1.8c0-1.4 0-2.8 0-3.1 0-4.1-2.7-5.3-2.7-5.3-1.4-.6-3.8-.9-6-.9h-.1c-2.2 0-4.6.3-6 .9 0 0-2.7 1.2-2.7 5.3v.1h3.3v-.1c0-1.7.7-2.1.7-2.1.4-.2 1.1-.3 1.8-.3.7 0 1.4.2 1.8.4.7.4 1.1 1.2 1.1 2.3v.5c-1.1-.3-2.3-.4-3.5-.4-2.2 0-3.3.8-3.3.8v3.2h3.3v-1.5c.4-.2 1.1-.3 1.9-.3.8 0 1.5.1 1.9.3v1.5h3.3V9.5c0-1.1.4-1.9 1.1-2.3.4-.2 1.1-.4 1.8-.4.7 0 1.4.1 1.8.3 0 0 .7.4.7 2.1v.1h3.3V8.2z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 803 B |
@@ -1,11 +1,28 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
(() => {
|
||||
const profileForm = document.querySelector('#profile-form');
|
||||
const passwordForm = document.querySelector('#password-form');
|
||||
const mastodonForm = document.querySelector('#mastodon-form');
|
||||
const profileLogoutButton = document.querySelector('#logout-button');
|
||||
const accessToken = localStorage.getItem('linklogAccessToken');
|
||||
const defaultMastodonInstance = 'mastodon.social';
|
||||
const defaultPostPrefix = 'From my #LinkLog: "';
|
||||
const defaultPostPrefix = 'From my #LinkLog: ';
|
||||
const mastodonConnectButton = document.querySelector('#mastodon-connect');
|
||||
const otpSetupButton = document.querySelector('#otp-setup');
|
||||
const otpEnableButton = document.querySelector('#otp-enable');
|
||||
const otpDisableButton = document.querySelector('#otp-disable');
|
||||
const otpRecoverButton = document.querySelector('#otp-recover');
|
||||
const otpProvisioning = document.querySelector('#otp-provisioning');
|
||||
const otpDisabled = document.querySelector('#otp-disabled');
|
||||
const otpEnabled = document.querySelector('#otp-enabled');
|
||||
const otpSecret = document.querySelector('#otp-secret');
|
||||
const otpUri = document.querySelector('#otp-uri');
|
||||
const otpRecoveryCodes = document.querySelector('#otp-recovery-codes');
|
||||
const otpStatus = document.querySelector('#otp-status');
|
||||
const emailAddressList = document.querySelector('#email-address-list');
|
||||
const additionalEmailForm = document.querySelector('#additional-email-form');
|
||||
const emailAddressStatus = document.querySelector('#email-address-status');
|
||||
|
||||
function authHeaders(includeJson = false) {
|
||||
return {
|
||||
@@ -20,12 +37,164 @@ function setStatus(selector, message, isError = false) {
|
||||
status.style.color = isError ? '#b91c1c' : '#166534';
|
||||
}
|
||||
|
||||
function setOtpStatus(message, isError = false) {
|
||||
otpStatus.textContent = message;
|
||||
otpStatus.style.color = isError ? '#b91c1c' : '#166534';
|
||||
}
|
||||
|
||||
function setEmailAddressStatus(message, isError = false) {
|
||||
emailAddressStatus.textContent = message;
|
||||
emailAddressStatus.style.color = isError ? '#b91c1c' : '#166534';
|
||||
}
|
||||
|
||||
function renderEmailAddresses(addresses) {
|
||||
emailAddressList.replaceChildren(...addresses.map((address) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'email-address-row';
|
||||
const label = document.createElement('span');
|
||||
label.textContent = `${address.email} - ${address.verified ? 'validated' : 'not validated'}${address.primary ? ' (primary)' : ''}`;
|
||||
row.appendChild(label);
|
||||
if (!address.primary) {
|
||||
if (!address.verified) {
|
||||
const resend = document.createElement('button');
|
||||
resend.type = 'button';
|
||||
resend.textContent = 'Resend validation';
|
||||
resend.addEventListener('click', async () => {
|
||||
resend.disabled = true;
|
||||
const response = await fetch(`/api/user/emails/${encodeURIComponent(address.id)}/resend`, {method: 'POST', headers: authHeaders()});
|
||||
const result = await response.json();
|
||||
setEmailAddressStatus(response.ok ? result.message : (result.detail || 'Could not send validation email.'), !response.ok);
|
||||
if (response.ok && result.next_allowed_at) window.setTimeout(() => { resend.disabled = false; }, Math.max(0, Date.parse(result.next_allowed_at) - Date.now()));
|
||||
else if (!response.ok) resend.disabled = false;
|
||||
});
|
||||
row.appendChild(resend);
|
||||
}
|
||||
if (address.verified && address.can_be_primary) {
|
||||
const makePrimary = document.createElement('button');
|
||||
makePrimary.type = 'button';
|
||||
makePrimary.textContent = 'Make primary';
|
||||
makePrimary.addEventListener('click', async () => {
|
||||
const response = await fetch(`/api/user/emails/${encodeURIComponent(address.id)}/make-primary`, {method: 'POST', headers: authHeaders()});
|
||||
const result = await response.json();
|
||||
setEmailAddressStatus(response.ok ? `${result.email} is now the primary email address.` : (result.detail || 'Could not change primary email.'), !response.ok);
|
||||
if (response.ok) {
|
||||
await loadEmailAddresses();
|
||||
}
|
||||
});
|
||||
row.appendChild(makePrimary);
|
||||
}
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.textContent = 'Remove';
|
||||
remove.addEventListener('click', async () => {
|
||||
const response = await fetch(`/api/user/emails/${encodeURIComponent(address.id)}`, {method: 'DELETE', headers: authHeaders()});
|
||||
if (response.ok) loadEmailAddresses();
|
||||
else setEmailAddressStatus('Could not remove email address.', true);
|
||||
});
|
||||
row.appendChild(remove);
|
||||
}
|
||||
return row;
|
||||
}));
|
||||
}
|
||||
|
||||
async function loadEmailAddresses() {
|
||||
const response = await fetch('/api/user/emails', {headers: authHeaders()});
|
||||
if (!response.ok) throw new Error('Could not load email addresses');
|
||||
renderEmailAddresses(await response.json());
|
||||
}
|
||||
|
||||
additionalEmailForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const response = await fetch('/api/user/emails', {
|
||||
method: 'POST', headers: authHeaders(true), body: JSON.stringify({email: additionalEmailForm.elements.email.value.trim()}),
|
||||
});
|
||||
const result = await response.json();
|
||||
setEmailAddressStatus(response.ok ? 'Email address added. Check your inbox to validate it.' : (result.detail || 'Could not add email address.'), !response.ok);
|
||||
if (response.ok) {
|
||||
additionalEmailForm.reset();
|
||||
loadEmailAddresses();
|
||||
}
|
||||
});
|
||||
|
||||
async function loadOtp() {
|
||||
const response = await fetch('/api/user/otp', {headers: authHeaders()});
|
||||
if (!response.ok) throw new Error('Could not load one-time password settings');
|
||||
const result = await response.json();
|
||||
otpDisabled.classList.toggle('hidden', result.enabled);
|
||||
otpEnabled.classList.toggle('hidden', !result.enabled);
|
||||
}
|
||||
|
||||
otpSetupButton.addEventListener('click', async () => {
|
||||
const response = await fetch('/api/user/otp/setup', {method: 'POST', headers: authHeaders()});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
setOtpStatus(result.detail || 'Could not start one-time password setup.', true);
|
||||
return;
|
||||
}
|
||||
otpSecret.textContent = result.secret;
|
||||
otpUri.href = result.otpauth_url;
|
||||
otpRecoveryCodes.textContent = result.recovery_codes.join('\n');
|
||||
otpProvisioning.classList.remove('hidden');
|
||||
setOtpStatus('Enter a code from your authenticator app to confirm setup.');
|
||||
});
|
||||
|
||||
otpEnableButton.addEventListener('click', async () => {
|
||||
const code = document.querySelector('#otp-setup-code').value.trim();
|
||||
const response = await fetch('/api/user/otp', {
|
||||
method: 'POST', headers: authHeaders(true), body: JSON.stringify({action: 'enable', code}),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
setOtpStatus(result.detail || 'Could not enable one-time password.', true);
|
||||
return;
|
||||
}
|
||||
otpDisabled.classList.add('hidden');
|
||||
otpEnabled.classList.remove('hidden');
|
||||
otpProvisioning.classList.add('hidden');
|
||||
setOtpStatus('One-time password enabled.');
|
||||
});
|
||||
|
||||
otpDisableButton.addEventListener('click', async () => {
|
||||
const code = document.querySelector('#otp-disable-code').value.trim();
|
||||
const currentPassword = document.querySelector('#otp-current-password').value;
|
||||
const response = await fetch('/api/user/otp', {
|
||||
method: 'POST', headers: authHeaders(true), body: JSON.stringify({action: 'disable', code, current_password: currentPassword}),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
setOtpStatus(result.detail || 'Could not disable one-time password.', true);
|
||||
return;
|
||||
}
|
||||
otpDisabled.classList.remove('hidden');
|
||||
otpEnabled.classList.add('hidden');
|
||||
document.querySelector('#otp-disable-code').value = '';
|
||||
setOtpStatus('One-time password disabled.');
|
||||
});
|
||||
|
||||
otpRecoverButton.addEventListener('click', async () => {
|
||||
const currentPassword = document.querySelector('#otp-current-password').value;
|
||||
const recoveryCode = document.querySelector('#otp-recovery-code').value.trim();
|
||||
const response = await fetch('/api/user/otp/recover', {
|
||||
method: 'POST', headers: authHeaders(true), body: JSON.stringify({current_password: currentPassword, recovery_code: recoveryCode}),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
setOtpStatus(result.detail || 'Could not recover one-time password access.', true);
|
||||
return;
|
||||
}
|
||||
otpDisabled.classList.remove('hidden');
|
||||
otpEnabled.classList.add('hidden');
|
||||
document.querySelector('#otp-current-password').value = '';
|
||||
document.querySelector('#otp-recovery-code').value = '';
|
||||
setOtpStatus('One-time password access recovered.');
|
||||
});
|
||||
|
||||
async function loadProfile() {
|
||||
const response = await fetch('/api/user/me', {headers: authHeaders()});
|
||||
if (!response.ok) throw new Error('Could not load profile');
|
||||
const profile = await response.json();
|
||||
document.querySelector('#username').textContent = profile.username || '';
|
||||
document.querySelector('#email').value = profile.email || '';
|
||||
document.querySelector('#email').textContent = profile.email || '';
|
||||
document.querySelector('#bio').value = profile.bio || '';
|
||||
const avatarPreview = document.querySelector('#avatar-preview');
|
||||
if (profile.avatar_url) {
|
||||
@@ -33,7 +202,7 @@ async function loadProfile() {
|
||||
avatarPreview.classList.remove('hidden');
|
||||
}
|
||||
if (profile.is_admin) {
|
||||
document.querySelector('#admin-link').classList.remove('hidden');
|
||||
document.querySelector('#auth-admin-link')?.classList.remove('hidden');
|
||||
}
|
||||
profileLogoutButton.classList.remove('hidden');
|
||||
}
|
||||
@@ -42,8 +211,7 @@ async function loadMastodonConfig() {
|
||||
const response = await fetch('/api/user/plugins/mastodon', {headers: authHeaders()});
|
||||
if (!response.ok) throw new Error('Could not load Mastodon settings');
|
||||
const config = await response.json();
|
||||
document.querySelector('#mastodon-instance').value = config.instance || defaultMastodonInstance;
|
||||
document.querySelector('#mastodon-access-token').value = config.access_token || '';
|
||||
document.querySelector('#mastodon-instance').value = config.instance || 'mastodon.social';
|
||||
document.querySelector('#mastodon-post-prefix').value = config.post_prefix || defaultPostPrefix;
|
||||
}
|
||||
|
||||
@@ -91,8 +259,46 @@ mastodonForm.addEventListener('submit', async (event) => {
|
||||
setStatus('#mastodon-status', response.ok ? 'Mastodon settings saved.' : 'Could not save Mastodon settings.', !response.ok);
|
||||
});
|
||||
|
||||
mastodonConnectButton.addEventListener('click', async () => {
|
||||
mastodonConnectButton.disabled = true;
|
||||
const instance = document.querySelector('#mastodon-instance').value.trim();
|
||||
if (!instance) {
|
||||
setStatus('#mastodon-status', 'Enter the Mastodon server you want to use.', true);
|
||||
mastodonConnectButton.disabled = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const settingsResponse = await fetch('/api/user/plugins/mastodon', {
|
||||
method: 'PUT',
|
||||
headers: authHeaders(true),
|
||||
body: JSON.stringify({instance}),
|
||||
});
|
||||
if (!settingsResponse.ok) throw new Error('Could not save the Mastodon server.');
|
||||
setStatus('#mastodon-status', `Authorizing with ${instance}...`);
|
||||
const response = await fetch(`/api/mastodon/oauth/start?instance=${encodeURIComponent(instance)}`, {headers: authHeaders()});
|
||||
const result = await response.json();
|
||||
if (!response.ok || !result.authorization_url) throw new Error(result.detail || result.error || 'Could not start Mastodon authorization.');
|
||||
window.location.assign(result.authorization_url);
|
||||
} catch (error) {
|
||||
setStatus('#mastodon-status', error.message, true);
|
||||
mastodonConnectButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
const mastodonParams = new URLSearchParams(window.location.search);
|
||||
if (mastodonParams.get('mastodon') === 'connected') setStatus('#mastodon-status', 'Mastodon connected.');
|
||||
if (mastodonParams.get('mastodon_error')) setStatus('#mastodon-status', mastodonParams.get('mastodon_error'), true);
|
||||
|
||||
passwordForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const password = passwordForm.elements.new_password.value;
|
||||
const confirmation = passwordForm.elements.new_password_confirmation.value;
|
||||
if (password !== confirmation) {
|
||||
const status = document.querySelector('#password-status');
|
||||
status.textContent = 'New passwords do not match.';
|
||||
status.style.color = '#f38ba8';
|
||||
return;
|
||||
}
|
||||
const response = await fetch('/api/user/password', {
|
||||
method: 'PUT',
|
||||
headers: authHeaders(true),
|
||||
@@ -104,7 +310,7 @@ passwordForm.addEventListener('submit', async (event) => {
|
||||
if (response.ok) passwordForm.reset();
|
||||
});
|
||||
|
||||
Promise.all([loadProfile(), loadMastodonConfig()]).catch((error) => {
|
||||
Promise.all([loadProfile(), loadMastodonConfig(), loadOtp(), loadEmailAddresses()]).catch((error) => {
|
||||
setStatus('#profile-status', accessToken ? error.message : 'Please sign in first.', true);
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
const resetForm = document.querySelector('#reset-password-form');
|
||||
const resetStatus = document.querySelector('#reset-password-status');
|
||||
const resetToken = new URLSearchParams(window.location.search).get('token');
|
||||
|
||||
resetForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const response = await fetch('/api/auth/reset-password', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({token: resetToken, password: new FormData(resetForm).get('password')}),
|
||||
});
|
||||
const result = await response.json();
|
||||
resetStatus.textContent = response.ok ? `${result.message} Redirecting...` : (result.detail || 'Reset failed.');
|
||||
resetStatus.style.color = response.ok ? '#166534' : '#b91c1c';
|
||||
if (response.ok) window.setTimeout(() => window.location.assign('/login'), 1000);
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
const setupForm = document.querySelector('#setup-form');
|
||||
const testMailButton = document.querySelector('#test-mail-button');
|
||||
const completeSetupButton = document.querySelector('#complete-setup-button');
|
||||
const setupStatus = document.querySelector('#setup-status');
|
||||
const setupTimer = document.querySelector('#setup-timer');
|
||||
let nextAllowedAt = null;
|
||||
let timerHandle = null;
|
||||
|
||||
function updateTimer() {
|
||||
if (timerHandle) window.clearTimeout(timerHandle);
|
||||
if (!nextAllowedAt) {
|
||||
setupTimer.textContent = '';
|
||||
testMailButton.disabled = !setupForm.dataset.saved;
|
||||
return;
|
||||
}
|
||||
const seconds = Math.max(0, Math.ceil((nextAllowedAt - Date.now()) / 1000));
|
||||
if (seconds === 0) {
|
||||
nextAllowedAt = null;
|
||||
updateTimer();
|
||||
return;
|
||||
}
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
setupTimer.textContent = `Next test mail available in ${minutes ? `${minutes}m ` : ''}${seconds % 60}s.`;
|
||||
testMailButton.disabled = true;
|
||||
timerHandle = window.setTimeout(updateTimer, 1000);
|
||||
}
|
||||
|
||||
function applyStatus(result) {
|
||||
setupForm.dataset.saved = result.pending ? 'true' : '';
|
||||
testMailButton.disabled = !result.pending;
|
||||
const smtpDefaults = result.smtp_defaults || {};
|
||||
for (const [name, value] of Object.entries(smtpDefaults)) {
|
||||
const field = setupForm.elements[name];
|
||||
if (!field || field.value || field.type === 'checkbox') continue;
|
||||
field.value = value;
|
||||
}
|
||||
if (typeof smtpDefaults.smtp_use_tls === 'boolean') {
|
||||
setupForm.elements.smtp_use_tls.checked = smtpDefaults.smtp_use_tls;
|
||||
}
|
||||
if (result.next_allowed_at) nextAllowedAt = Date.parse(result.next_allowed_at);
|
||||
updateTimer();
|
||||
}
|
||||
|
||||
async function loadSetupStatus() {
|
||||
const response = await fetch('/api/setup/status');
|
||||
if (!response.ok) return;
|
||||
applyStatus(await response.json());
|
||||
}
|
||||
|
||||
setupForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const values = Object.fromEntries(new FormData(form));
|
||||
values.smtp_port = Number(values.smtp_port);
|
||||
values.smtp_use_tls = form.elements.smtp_use_tls.checked;
|
||||
try {
|
||||
const response = await fetch('/api/setup/configuration', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.detail || 'Setup failed');
|
||||
setupStatus.textContent = result.message;
|
||||
setupStatus.style.color = '#94e2d5';
|
||||
form.dataset.saved = 'true';
|
||||
testMailButton.disabled = false;
|
||||
} catch (error) {
|
||||
setupStatus.textContent = error.message;
|
||||
setupStatus.style.color = '#f38ba8';
|
||||
}
|
||||
});
|
||||
|
||||
testMailButton.addEventListener('click', async () => {
|
||||
testMailButton.disabled = true;
|
||||
try {
|
||||
const response = await fetch('/api/setup/test-mail', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({email: setupForm.elements.email.value}),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
if (response.status === 429 && response.headers.get('Retry-After')) {
|
||||
nextAllowedAt = Date.now() + Number(response.headers.get('Retry-After')) * 1000;
|
||||
updateTimer();
|
||||
}
|
||||
throw new Error(result.detail || 'Test mail failed');
|
||||
}
|
||||
setupStatus.textContent = `${result.message} ${result.sends_remaining} sends remaining.`;
|
||||
setupStatus.style.color = '#94e2d5';
|
||||
if (result.next_allowed_at) nextAllowedAt = Date.parse(result.next_allowed_at);
|
||||
updateTimer();
|
||||
completeSetupButton.hidden = false;
|
||||
} catch (error) {
|
||||
setupStatus.textContent = error.message;
|
||||
setupStatus.style.color = '#f38ba8';
|
||||
if (!nextAllowedAt) testMailButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
completeSetupButton.addEventListener('click', async () => {
|
||||
const response = await fetch('/api/setup/complete', {method: 'POST'});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
setupStatus.textContent = result.detail || 'Could not complete setup.';
|
||||
setupStatus.style.color = '#f38ba8';
|
||||
return;
|
||||
}
|
||||
setupStatus.style.color = '#94e2d5';
|
||||
setupStatus.textContent = '';
|
||||
setupStatus.append(document.createTextNode(`${result.message} `));
|
||||
const homeLink = document.createElement('a');
|
||||
homeLink.href = '/';
|
||||
homeLink.textContent = 'Home';
|
||||
setupStatus.append(homeLink);
|
||||
setupForm.replaceChildren(setupStatus);
|
||||
});
|
||||
|
||||
loadSetupStatus();
|
||||
@@ -1,4 +1,7 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap');
|
||||
/* Copyright © 2026 Olaf Kolkman */
|
||||
/* 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');
|
||||
|
||||
:root {
|
||||
--base: #1e1e2e;
|
||||
@@ -20,6 +23,78 @@
|
||||
--shadow: 0 18px 50px rgba(17, 17, 27, 0.28);
|
||||
}
|
||||
|
||||
:root[data-theme='plain-day'] {
|
||||
--base: #f4f1ea; --mantle: #e8e3d8; --crust: #d7d0c2;
|
||||
--surface-0: #fffdf8; --surface-1: #e5ded1; --surface-2: #c8beae;
|
||||
--text: #2f2b27; --subtext: #514a42; --muted: #6b6258;
|
||||
--mauve: #7a3d6e; --lavender: #5d4b84; --blue: #315c78;
|
||||
--teal: #397c72; --peach: #a15d3d; --red: #a44250;
|
||||
--border: rgba(47, 43, 39, 0.16); --shadow: 0 18px 50px rgba(47, 43, 39, 0.16);
|
||||
}
|
||||
|
||||
:root[data-theme='plain-night'] {
|
||||
--base: #181818; --mantle: #111111; --crust: #090909;
|
||||
--surface-0: #262626; --surface-1: #353535; --surface-2: #4b4b4b;
|
||||
--text: #eeeeee; --subtext: #c1c1c1; --muted: #929292;
|
||||
--mauve: #d59acb; --lavender: #b9b4e8; --blue: #8ebbd8;
|
||||
--teal: #8bc9bd; --peach: #e2ae88; --red: #ec929f;
|
||||
--border: rgba(238, 238, 238, 0.14); --shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
:root[data-theme='latte'] {
|
||||
--base: #eff1f5; --mantle: #e6e9ef; --crust: #dce0e8;
|
||||
--surface-0: #ccd0da; --surface-1: #bcc0cc; --surface-2: #acb0be;
|
||||
--text: #3d4058; --subtext: #51546b; --muted: #65687c;
|
||||
--mauve: #7627c7; --lavender: #5946b2; --blue: #1854c7;
|
||||
--teal: #179299; --peach: #fe640b; --red: #d20f39;
|
||||
--border: rgba(76, 79, 105, 0.16); --shadow: 0 18px 50px rgba(76, 79, 105, 0.16);
|
||||
}
|
||||
|
||||
:root[data-theme='frappe'] {
|
||||
--base: #303446; --mantle: #292c3c; --crust: #232634;
|
||||
--surface-0: #414559; --surface-1: #51576d; --surface-2: #626880;
|
||||
--text: #c6d0f5; --subtext: #b5bfe2; --muted: #838ba7;
|
||||
--mauve: #ca9ee6; --lavender: #babbf1; --blue: #8caaee;
|
||||
--teal: #81c8be; --peach: #ef9f76; --red: #e78284;
|
||||
--border: rgba(198, 208, 245, 0.12); --shadow: 0 18px 50px rgba(35, 38, 52, 0.3);
|
||||
}
|
||||
|
||||
:root[data-theme='macchiato'] {
|
||||
--base: #24273a; --mantle: #1e2030; --crust: #181926;
|
||||
--surface-0: #363a4f; --surface-1: #494d64; --surface-2: #5b6078;
|
||||
--text: #cad3f5; --subtext: #b8c0e0; --muted: #8087a2;
|
||||
--mauve: #c6a0f6; --lavender: #b7bdf8; --blue: #8aadf4;
|
||||
--teal: #8bd5ca; --peach: #f5a97f; --red: #ed8796;
|
||||
--border: rgba(202, 211, 245, 0.12); --shadow: 0 18px 50px rgba(24, 25, 38, 0.34);
|
||||
}
|
||||
|
||||
:root[data-theme='dracula'] {
|
||||
--base: #282a36; --mantle: #21222c; --crust: #191a21;
|
||||
--surface-0: #44475a; --surface-1: #6272a4; --surface-2: #7886b5;
|
||||
--text: #f8f8f2; --subtext: #d6d6d0; --muted: #a7a7a0;
|
||||
--mauve: #ff79c6; --lavender: #bd93f9; --blue: #8be9fd;
|
||||
--teal: #50fa7b; --peach: #ffb86c; --red: #ff5555;
|
||||
--border: rgba(248, 248, 242, 0.14); --shadow: 0 18px 50px rgba(25, 26, 33, 0.35);
|
||||
}
|
||||
|
||||
:root[data-theme='nord'] {
|
||||
--base: #2e3440; --mantle: #272c36; --crust: #242933;
|
||||
--surface-0: #3b4252; --surface-1: #434c5e; --surface-2: #4c566a;
|
||||
--text: #eceff4; --subtext: #d8dee9; --muted: #aeb8c8;
|
||||
--mauve: #b48ead; --lavender: #d8dee9; --blue: #88c0d0;
|
||||
--teal: #a3be8c; --peach: #d08770; --red: #bf616a;
|
||||
--border: rgba(236, 239, 244, 0.14); --shadow: 0 18px 50px rgba(36, 41, 51, 0.35);
|
||||
}
|
||||
|
||||
:root[data-theme='solarized'] {
|
||||
--base: #fdf6e3; --mantle: #eee8d5; --crust: #e3ddc9;
|
||||
--surface-0: #eee8d5; --surface-1: #ddd6c1; --surface-2: #c9c1aa;
|
||||
--text: #073642; --subtext: #586e75; --muted: #657b83;
|
||||
--mauve: #6c71c4; --lavender: #268bd2; --blue: #268bd2;
|
||||
--teal: #2aa198; --peach: #cb4b16; --red: #dc322f;
|
||||
--border: rgba(7, 54, 66, 0.18); --shadow: 0 18px 50px rgba(7, 54, 66, 0.14);
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
@@ -49,13 +124,14 @@ body::selection {
|
||||
padding: 0 24px;
|
||||
}
|
||||
|
||||
|
||||
.site-header {
|
||||
position: relative;
|
||||
z-index: 20;
|
||||
padding: 56px 0 48px;
|
||||
padding: 6px 0 8px;
|
||||
background:
|
||||
linear-gradient(115deg, rgba(203, 166, 247, 0.18), transparent 45%),
|
||||
var(--mantle);
|
||||
linear-gradient(115deg, var(--mantle), transparent 45%),
|
||||
rgba(203, 166, 247, 0.18);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
@@ -84,6 +160,20 @@ body::selection {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.site-logo {
|
||||
display: block;
|
||||
width: min(260px, 70vw);
|
||||
height: 80px;
|
||||
margin-bottom: 12px;
|
||||
object-fit: contain;
|
||||
object-position: left center;
|
||||
}
|
||||
|
||||
.site-header .site-logo + h1,
|
||||
.feed-link {
|
||||
font-family: 'Asset', 'Space Grotesk', sans-serif;
|
||||
}
|
||||
|
||||
.site-header p {
|
||||
max-width: 34rem;
|
||||
margin: 14px 0 0;
|
||||
@@ -95,7 +185,34 @@ body::selection {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.header-tools {
|
||||
display: grid;
|
||||
flex: 1 1 auto;
|
||||
justify-items: end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.header-tools .toolbar {
|
||||
width: min(100%, 560px);
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.header-tools .toolbar label {
|
||||
min-width: 0;
|
||||
flex: 1 1 110px;
|
||||
font-size: 0.68rem;
|
||||
}
|
||||
|
||||
.header-tools .toolbar select {
|
||||
min-width: 0;
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
@@ -106,6 +223,17 @@ body::selection {
|
||||
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 {
|
||||
min-width: 0;
|
||||
padding: 10px 13px;
|
||||
@@ -193,17 +321,42 @@ main.container {
|
||||
padding-bottom: 64px;
|
||||
}
|
||||
|
||||
.site-footer {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 0 24px 24px;
|
||||
color: var(--muted);
|
||||
font-size: 0.72rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.site-footer a {
|
||||
color: inherit;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.site-footer a:hover,
|
||||
.site-footer a:focus-visible,
|
||||
.site-footer a:active {
|
||||
color: var(--lavender);
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 14px;
|
||||
margin: 0 0 24px;
|
||||
padding: 16px;
|
||||
background: rgba(24, 24, 37, 0.72);
|
||||
background: var(--surface-0);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.site-header .toolbar {
|
||||
margin-top: 18px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.toolbar label,
|
||||
.settings-panel label {
|
||||
display: grid;
|
||||
@@ -237,7 +390,7 @@ textarea,
|
||||
button {
|
||||
max-width: 100%;
|
||||
min-width: 180px;
|
||||
padding: 11px 13px;
|
||||
padding: 2px 2px;
|
||||
border: 1px solid var(--surface-1);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-0);
|
||||
@@ -264,6 +417,40 @@ button:focus-visible {
|
||||
max-width: 560px;
|
||||
}
|
||||
|
||||
.theme-options {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin: 14px 0;
|
||||
}
|
||||
|
||||
.theme-options label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.email-address-list {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.email-address-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.email-address-row button {
|
||||
min-width: 0;
|
||||
padding: 5px 9px;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.settings-panel textarea {
|
||||
min-height: 110px;
|
||||
resize: vertical;
|
||||
@@ -336,7 +523,7 @@ button:disabled {
|
||||
.plugin-list,
|
||||
.feed {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.plugin-row {
|
||||
@@ -344,7 +531,7 @@ button:disabled {
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 14px 0;
|
||||
padding: 4px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
@@ -354,7 +541,7 @@ button:disabled {
|
||||
|
||||
.plugin-row button {
|
||||
min-width: 0;
|
||||
padding: 8px 12px;
|
||||
padding: 5px 5px;
|
||||
background: var(--surface-1);
|
||||
border-color: var(--surface-2);
|
||||
color: var(--text);
|
||||
@@ -383,11 +570,56 @@ button:disabled {
|
||||
|
||||
.edit-button {
|
||||
min-width: 0;
|
||||
margin-top: 14px;
|
||||
padding: 8px 12px;
|
||||
padding: 5px 9px;
|
||||
border-radius: 6px;
|
||||
background: var(--surface-1);
|
||||
border-color: var(--surface-2);
|
||||
color: var(--text);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.entry-actions {
|
||||
display: flex;
|
||||
float: right;
|
||||
gap: 8px;
|
||||
margin: 0 0 8px 16px;
|
||||
}
|
||||
|
||||
.delete-button {
|
||||
min-width: 0;
|
||||
padding: 5px 9px;
|
||||
border-radius: 6px;
|
||||
border-color: rgba(243, 139, 168, 0.45);
|
||||
background: transparent;
|
||||
color: var(--red);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.mastodon-button {
|
||||
clear: right;
|
||||
float: right;
|
||||
margin: 0 0 8px 16px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
padding: 5px 9px;
|
||||
border-radius: 6px;
|
||||
background: var(--surface-1);
|
||||
border-color: var(--surface-2);
|
||||
color: var(--text);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.mastodon-button.posted {
|
||||
background: var(--teal);
|
||||
border-color: var(--teal);
|
||||
color: var(--crust);
|
||||
}
|
||||
|
||||
.mastodon-button img {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
}
|
||||
|
||||
.edit-form {
|
||||
@@ -438,17 +670,22 @@ button:disabled {
|
||||
}
|
||||
|
||||
.link-item {
|
||||
padding: 22px;
|
||||
background: rgba(49, 50, 68, 0.84);
|
||||
padding: 11px;
|
||||
background: var(--surface-0);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.about-content {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.link-item h2 {
|
||||
margin: 0 0 8px;
|
||||
color: var(--text);
|
||||
font-size: 1.2rem;
|
||||
font-size: 1rem;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
@@ -457,7 +694,13 @@ button:disabled {
|
||||
align-items: center;
|
||||
float: right;
|
||||
gap: 12px;
|
||||
margin: 0 0 12px 18px;
|
||||
margin: 0 0 2px 8px;
|
||||
}
|
||||
|
||||
.user-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
@@ -504,18 +747,27 @@ button:disabled {
|
||||
}
|
||||
|
||||
.meta {
|
||||
margin-top: 14px;
|
||||
margin-left: auto;
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.entry-tags {
|
||||
margin-top: 12px;
|
||||
color: var(--mauve);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.entry-meta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
clear: both;
|
||||
gap: 16px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.container {
|
||||
padding: 0 14px;
|
||||
@@ -529,11 +781,27 @@ button:disabled {
|
||||
font-size: 2.35rem;
|
||||
}
|
||||
|
||||
.site-logo {
|
||||
width: min(220px, 68vw);
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
.header-row {
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.header-tools {
|
||||
order: 3;
|
||||
flex-basis: 100%;
|
||||
justify-items: stretch;
|
||||
}
|
||||
|
||||
.header-tools .header-actions {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
align-items: flex-end;
|
||||
}
|
||||
@@ -555,11 +823,25 @@ button:disabled {
|
||||
padding-top: 18px;
|
||||
}
|
||||
|
||||
.site-footer {
|
||||
padding: 0 14px 18px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
gap: 12px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.entry-meta {
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
}
|
||||
|
||||
.meta {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.toolbar label,
|
||||
select,
|
||||
input,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
const themePreference = 'linklog-theme';
|
||||
|
||||
async function loadAvailableThemes() {
|
||||
const response = await fetch('/api/public/themes');
|
||||
if (!response.ok) return;
|
||||
const themes = await response.json();
|
||||
const selected = themes.some((theme) => theme.id === localStorage.getItem(themePreference))
|
||||
? localStorage.getItem(themePreference)
|
||||
: themes[0]?.id;
|
||||
if (selected) document.documentElement.dataset.theme = selected;
|
||||
const headerActions = document.querySelector('.header-actions');
|
||||
if (!headerActions || !themes.length) return;
|
||||
const picker = document.createElement('select');
|
||||
picker.className = 'theme-picker';
|
||||
picker.setAttribute('aria-label', 'Theme');
|
||||
picker.replaceChildren(...themes.map((theme) => new Option(theme.label, theme.id)));
|
||||
picker.value = selected || themes[0].id;
|
||||
picker.addEventListener('change', () => {
|
||||
localStorage.setItem(themePreference, picker.value);
|
||||
document.documentElement.dataset.theme = picker.value;
|
||||
});
|
||||
headerActions.prepend(picker);
|
||||
}
|
||||
|
||||
loadAvailableThemes();
|
||||
@@ -0,0 +1,67 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>About LinkLog</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="stylesheet" href="/static/style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="container">
|
||||
<div class="header-row">
|
||||
<div>
|
||||
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
||||
<h1>About</h1>
|
||||
<p>A quiet place for the links worth keeping.</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<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>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container about-content">
|
||||
<section class="link-item">
|
||||
<h2>Save the good stuff</h2>
|
||||
<p>LinkLog captures the page title, cleaned URL, comment, and timestamp when you save a page from the Firefox extension.</p>
|
||||
</section>
|
||||
<section class="link-item">
|
||||
<h2>Make it yours</h2>
|
||||
<p>Organize links with up to ten tags, browse the public feed, filter by user or tag, and edit the links you own.</p>
|
||||
</section>
|
||||
<section class="link-item">
|
||||
<h2>Share selectively</h2>
|
||||
<p>LinkLog stores the feed in SQLite and can publish new links to Mastodon when that plugin is configured.</p>
|
||||
</section>
|
||||
<section class="link-item">
|
||||
<h2>Open source</h2>
|
||||
<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>
|
||||
</section>
|
||||
<section class="link-item">
|
||||
<h2>Plugin</h2>
|
||||
<p>Install the Firefox plugin to save links directly from your browser. <a
|
||||
href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi"
|
||||
download>Download and install the Plugin</a>.</p>
|
||||
</section>
|
||||
</main>
|
||||
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||
<script src="/static/auth-header.js?v=3"></script>
|
||||
<script src="/static/logout.js?v=3"></script>
|
||||
<script src="/static/theme.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,4 +1,6 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
@@ -11,13 +13,15 @@
|
||||
<div class="container">
|
||||
<div class="header-row">
|
||||
<div>
|
||||
<h1>LinkLog Admin</h1>
|
||||
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
||||
<h1>Admin</h1>
|
||||
<p>Manage users and plugin configuration</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<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>
|
||||
@@ -68,10 +72,53 @@
|
||||
<h2>Labels</h2>
|
||||
<div id="admin-label-list" class="plugin-list" aria-live="polite">Loading labels...</div>
|
||||
</section>
|
||||
<section class="link-item settings-panel">
|
||||
<h2>SMTP settings</h2>
|
||||
<form id="smtp-form">
|
||||
<label>
|
||||
SMTP host
|
||||
<input name="smtp_host" type="text" required />
|
||||
</label>
|
||||
<label>
|
||||
SMTP port
|
||||
<input name="smtp_port" type="number" min="1" max="65535" required />
|
||||
</label>
|
||||
<label>
|
||||
SMTP username
|
||||
<input name="smtp_username" type="text" autocomplete="off" />
|
||||
</label>
|
||||
<label>
|
||||
SMTP password
|
||||
<input name="smtp_password" type="password" autocomplete="new-password" />
|
||||
</label>
|
||||
<label>
|
||||
From address
|
||||
<input name="smtp_from" type="text" required />
|
||||
</label>
|
||||
<label class="checkbox-label">
|
||||
<input name="smtp_use_tls" type="checkbox" /> Use STARTTLS
|
||||
</label>
|
||||
<button type="submit">Save SMTP settings</button>
|
||||
<button id="smtp-test-button" type="button">Send validation email</button>
|
||||
<p id="smtp-status" class="status" role="status"></p>
|
||||
|
||||
</form>
|
||||
</section>
|
||||
<section class="link-item settings-panel">
|
||||
<h2>Available themes</h2>
|
||||
<p>Choose the themes visitors may use.</p>
|
||||
<form id="themes-form">
|
||||
<div id="theme-options" class="theme-options" aria-live="polite">Loading themes...</div>
|
||||
<button type="submit">Save themes</button>
|
||||
<p id="theme-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||
<script src="/static/auth-header.js?v=3"></script>
|
||||
<script src="/static/logout.js?v=2"></script>
|
||||
<script src="/static/admin.js?v=3"></script>
|
||||
<script src="/static/theme.js?v=1"></script>
|
||||
<script src="/static/admin.js?v=5"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
@@ -11,13 +13,15 @@
|
||||
<div class="container">
|
||||
<div class="header-row">
|
||||
<div>
|
||||
<h1>LinkLog</h1>
|
||||
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
||||
<p>Public link feed</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<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">
|
||||
<div class="header-tools">
|
||||
<div class="header-actions">
|
||||
<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>
|
||||
@@ -26,7 +30,29 @@
|
||||
<a id="auth-username" class="user-name" href="/"></a>
|
||||
</div>
|
||||
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
|
||||
</nav>
|
||||
</nav>
|
||||
</div>
|
||||
<section class="toolbar">
|
||||
<label>
|
||||
Sort
|
||||
<select id="sort-select">
|
||||
<option value="newest">Newest first</option>
|
||||
<option value="oldest">Oldest first</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
User filter
|
||||
<select id="user-filter">
|
||||
<option value="">All users</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Tag filter
|
||||
<select id="tag-filter">
|
||||
<option value="">All tags</option>
|
||||
</select>
|
||||
</label>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -48,33 +74,13 @@
|
||||
<p>{{ profile.bio or 'No profile information provided.' }}</p>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="toolbar">
|
||||
<label>
|
||||
Sort
|
||||
<select id="sort-select">
|
||||
<option value="newest">Newest first</option>
|
||||
<option value="oldest">Oldest first</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
User filter
|
||||
<select id="user-filter">
|
||||
<option value="">All users</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Tag filter
|
||||
<select id="tag-filter">
|
||||
<option value="">All tags</option>
|
||||
</select>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<section id="feed" class="feed" aria-live="polite"></section>
|
||||
</main>
|
||||
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||
|
||||
<script src="/static/auth-header.js?v=3"></script>
|
||||
<script src="/static/logout.js?v=3"></script>
|
||||
<script src="/static/feed.js?v=7"></script>
|
||||
<script src="/static/theme.js?v=1"></script>
|
||||
<script src="/static/feed.js?v=9"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
@@ -11,6 +13,7 @@
|
||||
<div class="container">
|
||||
<div class="header-row">
|
||||
<div>
|
||||
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
||||
<h1>Labels</h1>
|
||||
<p>Manage your link labels</p>
|
||||
</div>
|
||||
@@ -18,6 +21,7 @@
|
||||
<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>
|
||||
@@ -40,8 +44,10 @@
|
||||
<div id="label-list" class="plugin-list"></div>
|
||||
</section>
|
||||
</main>
|
||||
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||
<script src="/static/auth-header.js?v=3"></script>
|
||||
<script src="/static/logout.js?v=3"></script>
|
||||
<script src="/static/theme.js?v=1"></script>
|
||||
<script src="/static/labels.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
@@ -11,13 +13,14 @@
|
||||
<div class="container">
|
||||
<div class="header-row">
|
||||
<div>
|
||||
<h1>Sign in</h1>
|
||||
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
||||
<p>Access your LinkLog settings</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<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>
|
||||
@@ -35,20 +38,27 @@
|
||||
<section class="link-item settings-panel">
|
||||
<form id="login-form">
|
||||
<label>
|
||||
Username
|
||||
<input id="username" name="username" type="text" autocomplete="username" required />
|
||||
Email address
|
||||
<input id="email" name="email" type="email" autocomplete="username" required />
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" required />
|
||||
</label>
|
||||
<label>
|
||||
One-time password (when configured)
|
||||
<input id="otp" name="otp" type="text" inputmode="numeric" autocomplete="one-time-code" placeholder="123456" />
|
||||
</label>
|
||||
<button type="submit">Sign in</button>
|
||||
<p id="login-status" class="status" role="status"></p>
|
||||
<p><small>A mistyped password sends a reset link to your verified email address.</small></p>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||
<script src="/static/auth-header.js?v=3"></script>
|
||||
<script src="/static/logout.js?v=3"></script>
|
||||
<script src="/static/theme.js?v=1"></script>
|
||||
<script src="/static/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Reset password - LinkLog</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="stylesheet" href="/static/style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="container">
|
||||
<section class="link-item settings-panel">
|
||||
<h1>Reset password</h1>
|
||||
<form id="reset-password-form">
|
||||
<label>New password<input name="password" type="password" minlength="8" autocomplete="new-password" required /></label>
|
||||
<button type="submit">Reset password</button>
|
||||
<p id="reset-password-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
<script src="/static/theme.js?v=1"></script>
|
||||
<script src="/static/reset-password.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,49 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Configure LinkLog</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="stylesheet" href="/static/style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="container">
|
||||
<div class="header-row">
|
||||
<div>
|
||||
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
||||
<h1>Configure LinkLog</h1>
|
||||
<p>Create the first administrator and test email delivery.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main class="container">
|
||||
<section class="link-item settings-panel">
|
||||
<form id="setup-form">
|
||||
<h2>Administrator</h2>
|
||||
<label>Username<input name="username" type="text" autocomplete="username" required /></label>
|
||||
<label>Email address<input name="email" type="email" autocomplete="email" required /></label>
|
||||
<label>Password<input name="password" type="password" autocomplete="new-password" minlength="8" required /></label>
|
||||
<h2>SMTP</h2>
|
||||
<label>SMTP host<input name="smtp_host" type="text" required /></label>
|
||||
<label>SMTP port<input name="smtp_port" type="number" min="1" max="65535" required /></label>
|
||||
<label>SMTP username<input name="smtp_username" type="text" autocomplete="off" /></label>
|
||||
<label>SMTP password<input name="smtp_password" type="password" autocomplete="new-password" /></label>
|
||||
<label>From address<input name="smtp_from" type="text" required /></label>
|
||||
<label class="checkbox-label"><input name="smtp_use_tls" type="checkbox" /> Use STARTTLS</label>
|
||||
<button type="submit">Save configuration</button>
|
||||
<button id="test-mail-button" type="button" disabled>Send test mail</button>
|
||||
<button id="complete-setup-button" type="button" hidden>Complete setup</button>
|
||||
<p id="setup-status" class="status" role="status"></p>
|
||||
<p id="setup-timer" class="status" role="timer" aria-live="polite"></p>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman</footer>
|
||||
<script src="/static/theme.js?v=1"></script>
|
||||
<script src="/static/setup.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,98 +1,156 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>LinkLog Profile</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">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>LinkLog Profile</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="stylesheet" href="/static/style.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="container">
|
||||
<div class="header-row">
|
||||
<div>
|
||||
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
||||
<h1>Profile</h1>
|
||||
<div class="header-actions">
|
||||
<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-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>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<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>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container">
|
||||
<section class="link-item settings-panel">
|
||||
<h2>Profile Settings</h2>
|
||||
<form id="profile-form">
|
||||
<label>
|
||||
Username
|
||||
<output id="username" class="readonly-value">Loading...</output>
|
||||
</label>
|
||||
<label>
|
||||
Email
|
||||
<input id="email" name="email" type="email" required />
|
||||
</label>
|
||||
<label>
|
||||
Bio
|
||||
<textarea id="bio" name="bio" rows="4"></textarea>
|
||||
</label>
|
||||
<label>
|
||||
Avatar image
|
||||
<input id="avatar-file" name="avatar" type="file" accept="image/png,image/jpeg,image/gif,image/webp" />
|
||||
</label>
|
||||
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" />
|
||||
<button type="submit">Save profile</button>
|
||||
<p id="profile-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
<main class="container">
|
||||
<section class="link-item settings-panel">
|
||||
<h2>Profile Settings</h2>
|
||||
<form id="profile-form">
|
||||
<label>
|
||||
Username
|
||||
<output id="username" class="readonly-value">Loading...</output>
|
||||
</label>
|
||||
<label>
|
||||
Email
|
||||
<output id="email" class="readonly-value">Loading...</output>
|
||||
</label>
|
||||
<label>
|
||||
Bio
|
||||
<textarea id="bio" name="bio" rows="4"></textarea>
|
||||
</label>
|
||||
<label>
|
||||
Avatar image
|
||||
<input id="avatar-file" name="avatar" type="file" accept="image/png,image/jpeg,image/gif,image/webp" />
|
||||
</label>
|
||||
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" />
|
||||
<button type="submit">Save profile</button>
|
||||
<p>If you have not downloaded the plugin yet, <a href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi" download>find it here</a>.</p>
|
||||
<p id="profile-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="link-item settings-panel">
|
||||
<h2>Password</h2>
|
||||
<form id="password-form">
|
||||
<label>
|
||||
Current password
|
||||
<input name="current_password" type="password" autocomplete="current-password" required />
|
||||
</label>
|
||||
<label>
|
||||
New password
|
||||
<input name="new_password" type="password" minlength="8" autocomplete="new-password" required />
|
||||
</label>
|
||||
<button type="submit">Change password</button>
|
||||
<p id="password-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
<section class="link-item settings-panel">
|
||||
<h2>Email addresses</h2>
|
||||
<div id="email-address-list" class="email-address-list" aria-live="polite">Loading email addresses...</div>
|
||||
<form id="additional-email-form">
|
||||
<label>
|
||||
Additional email address
|
||||
<input name="email" type="email" required />
|
||||
</label>
|
||||
<button type="submit">Add email address</button>
|
||||
<p id="email-address-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="link-item settings-panel">
|
||||
<h2>Password</h2>
|
||||
<form id="password-form">
|
||||
<label>
|
||||
Current password
|
||||
<input name="current_password" type="password" autocomplete="current-password" required />
|
||||
</label>
|
||||
<label>
|
||||
New password
|
||||
<input name="new_password" type="password" minlength="8" autocomplete="new-password" required />
|
||||
</label>
|
||||
<label>
|
||||
Confirm new password
|
||||
<input name="new_password_confirmation" type="password" minlength="8" autocomplete="new-password" required />
|
||||
</label>
|
||||
<button type="submit">Change password</button>
|
||||
<p id="password-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="link-item settings-panel">
|
||||
<h2>One-time password</h2>
|
||||
<p>Use an authenticator app to add a second sign-in step.</p>
|
||||
<div id="otp-disabled">
|
||||
<button id="otp-setup" type="button">Set up one-time password</button>
|
||||
<div id="otp-provisioning" class="hidden">
|
||||
<p>Scan this QR code or enter the secret in your authenticator app:</p>
|
||||
<code id="otp-secret"></code>
|
||||
<p><a id="otp-uri" href="" target="_blank" rel="noopener noreferrer">Open authenticator link</a></p>
|
||||
<label>Verification code <input id="otp-setup-code" inputmode="numeric"
|
||||
autocomplete="one-time-code" /></label>
|
||||
<button id="otp-enable" type="button">Enable one-time password</button>
|
||||
<p>Save these recovery codes in a secure place. They are shown only once:</p>
|
||||
<code id="otp-recovery-codes"></code>
|
||||
</div>
|
||||
</div>
|
||||
<div id="otp-enabled" class="hidden">
|
||||
<p>One-time password is enabled.</p>
|
||||
<label>Current password <input id="otp-current-password" type="password" autocomplete="current-password" /></label>
|
||||
<label>Verification code <input id="otp-disable-code" inputmode="numeric"
|
||||
autocomplete="one-time-code" /></label>
|
||||
<button id="otp-disable" type="button">Disable one-time password</button>
|
||||
<p>Lost access to your authenticator? Use a saved recovery code.</p>
|
||||
<label>Recovery code <input id="otp-recovery-code" type="text" autocomplete="one-time-code" /></label>
|
||||
<button id="otp-recover" type="button">Recover and disable one-time password</button>
|
||||
</div>
|
||||
<p id="otp-status" class="status" role="status"></p>
|
||||
</section>
|
||||
|
||||
<section class="link-item settings-panel">
|
||||
<h2>Mastodon</h2>
|
||||
<form id="mastodon-form">
|
||||
<label>
|
||||
Mastodon server
|
||||
<input id="mastodon-instance" name="instance" type="text" value="mastodon.social"
|
||||
placeholder="mastodon.social" required />
|
||||
</label>
|
||||
<button id="mastodon-connect" type="button">Authenticate with this server</button>
|
||||
|
||||
<label>
|
||||
Post prefix
|
||||
<input id="mastodon-post-prefix" name="post_prefix" type="text" value="From my #LinkLog: " />
|
||||
</label>
|
||||
<button type="submit">Save Mastodon settings</button>
|
||||
<p id="mastodon-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a
|
||||
href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||
<script src="/static/auth-header.js?v=3"></script>
|
||||
<script src="/static/logout.js?v=2"></script>
|
||||
<script src="/static/theme.js?v=1"></script>
|
||||
<script src="/static/profile.js?v=5"></script>
|
||||
</body>
|
||||
|
||||
<section class="link-item settings-panel">
|
||||
<h2>Mastodon</h2>
|
||||
<form id="mastodon-form">
|
||||
<label>
|
||||
Instance
|
||||
<input id="mastodon-instance" name="instance" type="text" value="mastodon.social" placeholder="mastodon.social" />
|
||||
</label>
|
||||
<label>
|
||||
Access token
|
||||
<input id="mastodon-access-token" name="access_token" type="password" autocomplete="off" />
|
||||
</label>
|
||||
<label>
|
||||
Post prefix
|
||||
<input id="mastodon-post-prefix" name="post_prefix" type="text" value="From my #LinkLog: "" />
|
||||
</label>
|
||||
<button type="submit">Save Mastodon settings</button>
|
||||
<p id="mastodon-status" class="status" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
<script src="/static/auth-header.js?v=3"></script>
|
||||
<script src="/static/logout.js?v=2"></script>
|
||||
<script src="/static/profile.js?v=2"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "0.1.0"
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.9 MiB |
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the version and checked-in artifacts for a LinkLog release."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SETTINGS_PATH = ROOT / 'backend' / 'app' / 'core' / 'config.py'
|
||||
SIGNED_DIR = ROOT / 'XPI' / 'signed'
|
||||
VERSION_RE = re.compile(r'\d+\.\d+\.\d+')
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
raise SystemExit(f'release validation failed: {message}')
|
||||
|
||||
|
||||
def version_key(version: str) -> tuple[int, int, int]:
|
||||
return tuple(int(part) for part in version.split('.'))
|
||||
|
||||
|
||||
def find_latest_signed_xpi() -> tuple[str, Path]:
|
||||
candidates = []
|
||||
for xpi_path in SIGNED_DIR.glob('LinkLog-*.xpi'):
|
||||
match = re.fullmatch(r'LinkLog-(\d+\.\d+\.\d+)\.xpi', xpi_path.name)
|
||||
if match:
|
||||
candidates.append((match.group(1), xpi_path))
|
||||
if not candidates:
|
||||
fail(f'no signed plugin artifacts found in {SIGNED_DIR.relative_to(ROOT)}')
|
||||
return max(candidates, key=lambda candidate: version_key(candidate[0]))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
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 not VERSION_RE.fullmatch(backend_version):
|
||||
fail(f'backend version {backend_version} is not a valid three-part version')
|
||||
|
||||
extension_version, xpi_path = find_latest_signed_xpi()
|
||||
with zipfile.ZipFile(xpi_path) as archive:
|
||||
try:
|
||||
packaged_manifest = json.loads(archive.read('manifest.json'))
|
||||
except KeyError:
|
||||
fail('signed XPI does not contain manifest.json')
|
||||
if packaged_manifest.get('version') != extension_version:
|
||||
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:
|
||||
fail('signed XPI contains a corrupt member')
|
||||
|
||||
signed_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__':
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate an unsigned LinkLog XPI produced by the Makefile."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
REQUIRED_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',
|
||||
}
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
raise SystemExit(f'XPI validation failed: {message}')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) != 3:
|
||||
fail('usage: validate_xpi.py <xpi> <source-manifest>')
|
||||
|
||||
xpi_path = Path(sys.argv[1])
|
||||
source_manifest_path = Path(sys.argv[2])
|
||||
try:
|
||||
source_manifest = json.loads(source_manifest_path.read_text())
|
||||
with zipfile.ZipFile(xpi_path) as archive:
|
||||
names = set(archive.namelist())
|
||||
corrupt_member = archive.testzip()
|
||||
if corrupt_member is not None:
|
||||
fail(f'corrupt archive member: {corrupt_member}')
|
||||
if 'manifest.json' not in names:
|
||||
fail('manifest.json is missing')
|
||||
packaged_manifest = json.loads(archive.read('manifest.json'))
|
||||
except (OSError, zipfile.BadZipFile, json.JSONDecodeError) as error:
|
||||
fail(str(error))
|
||||
|
||||
missing_files = REQUIRED_FILES - names
|
||||
if missing_files:
|
||||
fail(f'missing required files: {", ".join(sorted(missing_files))}')
|
||||
unexpected_files = names - REQUIRED_FILES
|
||||
if any(name.startswith('__MACOSX/') or name == '.DS_Store' for name in unexpected_files):
|
||||
fail('archive contains macOS metadata')
|
||||
if packaged_manifest != source_manifest:
|
||||
fail('packaged manifest does not match webextension/manifest.json')
|
||||
|
||||
print(f'validated unsigned XPI {xpi_path}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"extensionName": {"message": "LinkLog"},
|
||||
"extensionDescription": {"message": "Webseiten-Links erfassen und an LinkLog senden."},
|
||||
"settingsTitle": {"message": "LinkLog-Einstellungen"},
|
||||
"titleLabel": {"message": "Titel"},
|
||||
"urlLabel": {"message": "URL"},
|
||||
"commentLabel": {"message": "Kommentar"},
|
||||
"commentPlaceholder": {"message": "Dein Kommentar"},
|
||||
"tagsLabel": {"message": "Tags"},
|
||||
"loadingTags": {"message": "Tags werden geladen..."},
|
||||
"newTagsPlaceholder": {"message": "#neuer-tag, #anderer-tag"},
|
||||
"saveLink": {"message": "Link speichern"},
|
||||
"settings": {"message": "Einstellungen"},
|
||||
"authRequired": {"message": "Melde dich an, um LinkLog zu verwenden."},
|
||||
"openSettings": {"message": "Einstellungen öffnen"},
|
||||
"signOut": {"message": "Abmelden"},
|
||||
"backendUrlLabel": {"message": "Backend-URL"},
|
||||
"emailLabel": {"message": "E-Mail"},
|
||||
"emailPlaceholder": {"message": "alice@example.com"},
|
||||
"usernameLabel": {"message": "Benutzername"},
|
||||
"usernamePlaceholder": {"message": "alice"},
|
||||
"passwordLabel": {"message": "Passwort"},
|
||||
"otpLabel": {"message": "Einmalpasswort (falls konfiguriert)"},
|
||||
"otpPlaceholder": {"message": "123456"},
|
||||
"saveAndLogIn": {"message": "Speichern und anmelden"},
|
||||
"thisPlugin": {"message": "Dieses Add-on"},
|
||||
"pluginDescription": {"message": "Dieses Add-on protokolliert Links auf einem LinkLog-Server, der sie auf einer Website und je nach Konfiguration der Add-ons möglicherweise auch in einem Fediverse-Dienst oder an anderen Orten veröffentlicht."},
|
||||
"accountRequirement": {"message": "Nutzer dieses Add-ons benötigen ein Konto auf einem LinkLog-Server"},
|
||||
"privacy": {"message": "Datenschutz"},
|
||||
"privacyDescription": {"message": "Dieses Add-on respektiert deine Privatsphäre und erhebt keine personenbezogenen Daten über das hinaus, was zum Protokollieren von Links auf deinem LinkLog-Server erforderlich ist."},
|
||||
"storedData": {"message": "Die URL, nach einem bestmöglichen Versuch, Tracking-Parameter zu entfernen, der Seitentitel, ein möglicher Kommentar und der Besuchszeitpunkt werden auf dem Server gespeichert und zusammen mit dem dort registrierten Nutzerprofil veröffentlicht."},
|
||||
"backendHeading": {"message": "LinkLog-Backend"},
|
||||
"backendDescription": {"message": "Die Backend-URL gehört zu einer selbst gehosteten LinkLog-Anwendung. Ihr"},
|
||||
"backendSource": {"message": "Quellcode ist im Repository verfügbar."},
|
||||
"copyright": {"message": "Copyright © 2026 Olaf Kolkman"},
|
||||
"repository": {"message": "Repository"},
|
||||
"signInToSelectTags": {"message": "Melde dich an, um vorhandene Tags auszuwählen."},
|
||||
"loadTagsFailed": {"message": "Vorhandene Tags konnten nicht geladen werden."},
|
||||
"submitting": {"message": "Wird gesendet..."},
|
||||
"configureAndLogIn": {"message": "Konfiguriere die Backend-URL und melde dich zuerst an."},
|
||||
"sessionExpired": {"message": "Sitzung abgelaufen. Authentifiziere dich in den Einstellungen erneut."},
|
||||
"submissionFailed": {"message": "Senden fehlgeschlagen"},
|
||||
"linkSaved": {"message": "Link auf $URL$ gespeichert.", "placeholders": {"url": {"content": "$1"}}},
|
||||
"linkAlreadyExists": {"message": "Dieser Link existiert bereits. Kommentar und Tags wurden aktualisiert und die Veröffentlichung erneut ausgelöst."},
|
||||
"duplicateLinkWarning": {"message": "Dieser Link existiert bereits. Kommentar und Tags können aktualisiert werden; beim Absenden wird die Veröffentlichung erneut ausgelöst."},
|
||||
"publishingErrors": {"message": "Fehler bei der Veröffentlichung: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
|
||||
"submissionFailedConnection": {"message": "Senden fehlgeschlagen. Überprüfe die Verbindung zum Backend."},
|
||||
"loggedInAt": {"message": "$USERNAME$ ist bei $BACKEND$ angemeldet", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||
"fillAllFields": {"message": "Fülle alle Felder aus"},
|
||||
"loginFailed": {"message": "Anmeldung fehlgeschlagen"},
|
||||
"loggedInSuccessfully": {"message": "Erfolgreich angemeldet"},
|
||||
"unableToLogIn": {"message": "Anmeldung nicht möglich. Überprüfe Backend-URL und Zugangsdaten."},
|
||||
"signedOut": {"message": "Abgemeldet"}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
{
|
||||
"extensionName": {
|
||||
"message": "LinkLog"
|
||||
},
|
||||
"extensionDescription": {
|
||||
"message": "Capture and submit page links to LinkLog."
|
||||
},
|
||||
"settingsTitle": {
|
||||
"message": "LinkLog Settings"
|
||||
},
|
||||
"titleLabel": {
|
||||
"message": "Title"
|
||||
},
|
||||
"urlLabel": {
|
||||
"message": "URL"
|
||||
},
|
||||
"commentLabel": {
|
||||
"message": "Comment"
|
||||
},
|
||||
"commentPlaceholder": {
|
||||
"message": "Your comment"
|
||||
},
|
||||
"tagsLabel": {
|
||||
"message": "Tags"
|
||||
},
|
||||
"loadingTags": {
|
||||
"message": "Loading tags..."
|
||||
},
|
||||
"newTagsPlaceholder": {
|
||||
"message": "#new-tag, #another-tag"
|
||||
},
|
||||
"saveLink": {
|
||||
"message": "Save link"
|
||||
},
|
||||
"settings": {
|
||||
"message": "Settings"
|
||||
},
|
||||
"authRequired": {
|
||||
"message": "Please sign in to use LinkLog."
|
||||
},
|
||||
"openSettings": {
|
||||
"message": "Open settings"
|
||||
},
|
||||
"signOut": {
|
||||
"message": "Sign out"
|
||||
},
|
||||
"backendUrlLabel": {
|
||||
"message": "Backend URL"
|
||||
},
|
||||
"emailLabel": {
|
||||
"message": "Email"
|
||||
},
|
||||
"emailPlaceholder": {
|
||||
"message": "alice@example.com"
|
||||
},
|
||||
"usernameLabel": {
|
||||
"message": "Username"
|
||||
},
|
||||
"usernamePlaceholder": {
|
||||
"message": "alice"
|
||||
},
|
||||
"passwordLabel": {
|
||||
"message": "Password"
|
||||
},
|
||||
"otpLabel": {
|
||||
"message": "One-time password (when configured)"
|
||||
},
|
||||
"otpPlaceholder": {
|
||||
"message": "123456"
|
||||
},
|
||||
"saveAndLogIn": {
|
||||
"message": "Save and log in"
|
||||
},
|
||||
"thisPlugin": {
|
||||
"message": "This Plugin"
|
||||
},
|
||||
"pluginDescription": {
|
||||
"message": "This plugin will log links to a backend LinkLog server which will publish them on a website and potentially as an entry on a fediverse service or other locations, depending on the plugins configured."
|
||||
},
|
||||
"accountRequirement": {
|
||||
"message": "Users of this plugin will need an account on a LinkLog server"
|
||||
},
|
||||
"privacy": {
|
||||
"message": "Privacy"
|
||||
},
|
||||
"privacyDescription": {
|
||||
"message": "This plugin respects your privacy and does not collect any personal data beyond what is necessary to log links to your LinkLog server."
|
||||
},
|
||||
"storedData": {
|
||||
"message": "The URL - after a best effort try to remove tracking parameters -, the title of the webpage, a possible comment, and a timestamp of visit will be stored on the backend server, and will be made public in combination with the user's profile as registered on the backend server."
|
||||
},
|
||||
"backendHeading": {
|
||||
"message": "LinkLog Backend"
|
||||
},
|
||||
"backendDescription": {
|
||||
"message": "The backend URL is a selfhosted linklog application. See its"
|
||||
},
|
||||
"backendSource": {
|
||||
"message": "for its source."
|
||||
},
|
||||
"copyright": {
|
||||
"message": "Copyright © 2026 Olaf Kolkman"
|
||||
},
|
||||
"repository": {
|
||||
"message": "Repository"
|
||||
},
|
||||
"signInToSelectTags": {
|
||||
"message": "Sign in to select existing tags."
|
||||
},
|
||||
"loadTagsFailed": {
|
||||
"message": "Could not load existing tags."
|
||||
},
|
||||
"submitting": {
|
||||
"message": "Submitting..."
|
||||
},
|
||||
"configureAndLogIn": {
|
||||
"message": "Please configure the backend URL and log in first."
|
||||
},
|
||||
"sessionExpired": {
|
||||
"message": "Session expired. Re-authenticate in settings."
|
||||
},
|
||||
"submissionFailed": {
|
||||
"message": "Submission failed"
|
||||
},
|
||||
"linkSaved": {
|
||||
"message": "Link saved to $URL$.",
|
||||
"placeholders": {
|
||||
"url": {
|
||||
"content": "$1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"linkAlreadyExists": {
|
||||
"message": "This link already exists. Comment and tags were updated, and publishing was retriggered."
|
||||
},
|
||||
"duplicateLinkWarning": {
|
||||
"message": "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered."
|
||||
},
|
||||
"publishingErrors": {
|
||||
"message": "Publishing errors: $ERRORS$",
|
||||
"placeholders": {
|
||||
"errors": {
|
||||
"content": "$1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"submissionFailedConnection": {
|
||||
"message": "Submission failed. Check your backend connection."
|
||||
},
|
||||
"loggedInAt": {
|
||||
"message": "$USERNAME$ logged in at $BACKEND$",
|
||||
"placeholders": {
|
||||
"username": {
|
||||
"content": "$1"
|
||||
},
|
||||
"backend": {
|
||||
"content": "$2"
|
||||
}
|
||||
}
|
||||
},
|
||||
"fillAllFields": {
|
||||
"message": "Please fill in all fields"
|
||||
},
|
||||
"loginFailed": {
|
||||
"message": "Login failed"
|
||||
},
|
||||
"loggedInSuccessfully": {
|
||||
"message": "Logged in successfully"
|
||||
},
|
||||
"unableToLogIn": {
|
||||
"message": "Unable to log in. Check backend URL and credentials."
|
||||
},
|
||||
"signedOut": {
|
||||
"message": "Signed out"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"extensionName": {"message": "LinkLog"},
|
||||
"extensionDescription": {"message": "Captura y envía enlaces de páginas a LinkLog."},
|
||||
"settingsTitle": {"message": "Configuración de LinkLog"},
|
||||
"titleLabel": {"message": "Título"},
|
||||
"urlLabel": {"message": "URL"},
|
||||
"commentLabel": {"message": "Comentario"},
|
||||
"commentPlaceholder": {"message": "Tu comentario"},
|
||||
"tagsLabel": {"message": "Etiquetas"},
|
||||
"loadingTags": {"message": "Cargando etiquetas..."},
|
||||
"newTagsPlaceholder": {"message": "#nueva-etiqueta, #otra-etiqueta"},
|
||||
"saveLink": {"message": "Guardar enlace"},
|
||||
"settings": {"message": "Configuración"},
|
||||
"authRequired": {"message": "Inicia sesión para usar LinkLog."},
|
||||
"openSettings": {"message": "Abrir configuración"},
|
||||
"signOut": {"message": "Cerrar sesión"},
|
||||
"backendUrlLabel": {"message": "URL del servidor"},
|
||||
"emailLabel": {"message": "Correo electrónico"},
|
||||
"emailPlaceholder": {"message": "alice@example.com"},
|
||||
"usernameLabel": {"message": "Nombre de usuario"},
|
||||
"usernamePlaceholder": {"message": "alice"},
|
||||
"passwordLabel": {"message": "Contraseña"},
|
||||
"otpLabel": {"message": "Contraseña de un solo uso (cuando está configurada)"},
|
||||
"otpPlaceholder": {"message": "123456"},
|
||||
"saveAndLogIn": {"message": "Guardar e iniciar sesión"},
|
||||
"thisPlugin": {"message": "Este complemento"},
|
||||
"pluginDescription": {"message": "Este complemento registra enlaces en un servidor LinkLog, que los publicará en un sitio web y posiblemente en un servicio fediverso u otros destinos, según los complementos configurados."},
|
||||
"accountRequirement": {"message": "Los usuarios de este complemento necesitan una cuenta en un servidor LinkLog"},
|
||||
"privacy": {"message": "Privacidad"},
|
||||
"privacyDescription": {"message": "Este complemento respeta tu privacidad y no recopila datos personales más allá de lo necesario para registrar enlaces en tu servidor LinkLog."},
|
||||
"storedData": {"message": "La URL, tras intentar eliminar los parámetros de seguimiento, el título de la página, un posible comentario y la hora de visita se guardarán en el servidor y se harán públicos junto con el perfil del usuario registrado en el servidor."},
|
||||
"backendHeading": {"message": "Servidor LinkLog"},
|
||||
"backendDescription": {"message": "La URL del servidor es una aplicación LinkLog autoalojada. Consulta su"},
|
||||
"backendSource": {"message": "para ver el código fuente."},
|
||||
"copyright": {"message": "Copyright © 2026 Olaf Kolkman"},
|
||||
"repository": {"message": "Repositorio"},
|
||||
"signInToSelectTags": {"message": "Inicia sesión para seleccionar etiquetas existentes."},
|
||||
"loadTagsFailed": {"message": "No se pudieron cargar las etiquetas existentes."},
|
||||
"submitting": {"message": "Enviando..."},
|
||||
"configureAndLogIn": {"message": "Configura la URL del servidor e inicia sesión primero."},
|
||||
"sessionExpired": {"message": "La sesión ha caducado. Vuelve a autenticarte en la configuración."},
|
||||
"submissionFailed": {"message": "Error al enviar"},
|
||||
"linkSaved": {"message": "Enlace guardado en $URL$.", "placeholders": {"url": {"content": "$1"}}},
|
||||
"linkAlreadyExists": {"message": "Este enlace ya existe. Se actualizaron el comentario y las etiquetas, y se volvió a activar la publicación."},
|
||||
"duplicateLinkWarning": {"message": "Este enlace ya existe. Puedes actualizar el comentario y las etiquetas; al enviarlo se volverá a activar la publicación."},
|
||||
"publishingErrors": {"message": "Errores de publicación: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
|
||||
"submissionFailedConnection": {"message": "Error al enviar. Comprueba la conexión con el servidor."},
|
||||
"loggedInAt": {"message": "$USERNAME$ ha iniciado sesión en $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||
"fillAllFields": {"message": "Rellena todos los campos"},
|
||||
"loginFailed": {"message": "Error de inicio de sesión"},
|
||||
"loggedInSuccessfully": {"message": "Sesión iniciada correctamente"},
|
||||
"unableToLogIn": {"message": "No se pudo iniciar sesión. Comprueba la URL y las credenciales."},
|
||||
"signedOut": {"message": "Sesión cerrada"}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"extensionName": {"message": "LinkLog"},
|
||||
"extensionDescription": {"message": "Capturer et envoyer des liens de pages à LinkLog."},
|
||||
"settingsTitle": {"message": "Paramètres de LinkLog"},
|
||||
"titleLabel": {"message": "Titre"},
|
||||
"urlLabel": {"message": "URL"},
|
||||
"commentLabel": {"message": "Commentaire"},
|
||||
"commentPlaceholder": {"message": "Votre commentaire"},
|
||||
"tagsLabel": {"message": "Étiquettes"},
|
||||
"loadingTags": {"message": "Chargement des étiquettes..."},
|
||||
"newTagsPlaceholder": {"message": "#nouvelle-étiquette, #autre-étiquette"},
|
||||
"saveLink": {"message": "Enregistrer le lien"},
|
||||
"settings": {"message": "Paramètres"},
|
||||
"authRequired": {"message": "Connectez-vous pour utiliser LinkLog."},
|
||||
"openSettings": {"message": "Ouvrir les paramètres"},
|
||||
"signOut": {"message": "Se déconnecter"},
|
||||
"backendUrlLabel": {"message": "URL du serveur"},
|
||||
"emailLabel": {"message": "E-mail"},
|
||||
"emailPlaceholder": {"message": "alice@example.com"},
|
||||
"usernameLabel": {"message": "Nom d’utilisateur"},
|
||||
"usernamePlaceholder": {"message": "alice"},
|
||||
"passwordLabel": {"message": "Mot de passe"},
|
||||
"otpLabel": {"message": "Mot de passe à usage unique (si configuré)"},
|
||||
"otpPlaceholder": {"message": "123456"},
|
||||
"saveAndLogIn": {"message": "Enregistrer et se connecter"},
|
||||
"thisPlugin": {"message": "Cette extension"},
|
||||
"pluginDescription": {"message": "Cette extension enregistre les liens sur un serveur LinkLog, qui les publiera sur un site web et éventuellement sur un service du fédivers ou ailleurs, selon les extensions configurées."},
|
||||
"accountRequirement": {"message": "Les utilisateurs de cette extension doivent avoir un compte sur un serveur LinkLog"},
|
||||
"privacy": {"message": "Confidentialité"},
|
||||
"privacyDescription": {"message": "Cette extension respecte votre vie privée et ne recueille aucune donnée personnelle au-delà de ce qui est nécessaire pour enregistrer des liens sur votre serveur LinkLog."},
|
||||
"storedData": {"message": "L’URL, après une tentative de suppression des paramètres de suivi, le titre de la page, un éventuel commentaire et l’heure de la visite seront enregistrés sur le serveur et rendus publics avec le profil de l’utilisateur qui y est inscrit."},
|
||||
"backendHeading": {"message": "Serveur LinkLog"},
|
||||
"backendDescription": {"message": "L’URL du serveur correspond à une application LinkLog auto-hébergée. Consultez son"},
|
||||
"backendSource": {"message": "pour voir le code source."},
|
||||
"copyright": {"message": "Copyright © 2026 Olaf Kolkman"},
|
||||
"repository": {"message": "Dépôt"},
|
||||
"signInToSelectTags": {"message": "Connectez-vous pour sélectionner des étiquettes existantes."},
|
||||
"loadTagsFailed": {"message": "Impossible de charger les étiquettes existantes."},
|
||||
"submitting": {"message": "Envoi..."},
|
||||
"configureAndLogIn": {"message": "Configurez l’URL du serveur et connectez-vous d’abord."},
|
||||
"sessionExpired": {"message": "Session expirée. Reconnectez-vous dans les paramètres."},
|
||||
"submissionFailed": {"message": "Échec de l’envoi"},
|
||||
"linkSaved": {"message": "Lien enregistré sur $URL$.", "placeholders": {"url": {"content": "$1"}}},
|
||||
"linkAlreadyExists": {"message": "Ce lien existe déjà. Le commentaire et les étiquettes ont été mis à jour et la publication a été relancée."},
|
||||
"duplicateLinkWarning": {"message": "Ce lien existe déjà. Le commentaire et les étiquettes peuvent être mis à jour ; l’envoi relancera la publication."},
|
||||
"publishingErrors": {"message": "Erreurs de publication : $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
|
||||
"submissionFailedConnection": {"message": "Échec de l’envoi. Vérifiez la connexion au serveur."},
|
||||
"loggedInAt": {"message": "$USERNAME$ est connecté à $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||
"fillAllFields": {"message": "Veuillez remplir tous les champs"},
|
||||
"loginFailed": {"message": "Échec de la connexion"},
|
||||
"loggedInSuccessfully": {"message": "Connexion réussie"},
|
||||
"unableToLogIn": {"message": "Connexion impossible. Vérifiez l’URL du serveur et vos identifiants."},
|
||||
"signedOut": {"message": "Déconnecté"}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"extensionName": {"message": "LinkLog"},
|
||||
"extensionDescription": {"message": "Paginakoppelingen vastleggen en naar LinkLog verzenden."},
|
||||
"settingsTitle": {"message": "LinkLog-instellingen"},
|
||||
"titleLabel": {"message": "Titel"},
|
||||
"urlLabel": {"message": "URL"},
|
||||
"commentLabel": {"message": "Opmerking"},
|
||||
"commentPlaceholder": {"message": "Je opmerking"},
|
||||
"tagsLabel": {"message": "Tags"},
|
||||
"loadingTags": {"message": "Tags worden geladen..."},
|
||||
"newTagsPlaceholder": {"message": "#nieuwe-tag, #andere-tag"},
|
||||
"saveLink": {"message": "Koppeling opslaan"},
|
||||
"settings": {"message": "Instellingen"},
|
||||
"authRequired": {"message": "Log in om LinkLog te gebruiken."},
|
||||
"openSettings": {"message": "Instellingen openen"},
|
||||
"signOut": {"message": "Uitloggen"},
|
||||
"backendUrlLabel": {"message": "Backend-URL"},
|
||||
"emailLabel": {"message": "E-mail"},
|
||||
"emailPlaceholder": {"message": "alice@example.com"},
|
||||
"usernameLabel": {"message": "Gebruikersnaam"},
|
||||
"usernamePlaceholder": {"message": "alice"},
|
||||
"passwordLabel": {"message": "Wachtwoord"},
|
||||
"otpLabel": {"message": "Eenmalig wachtwoord (indien geconfigureerd)"},
|
||||
"otpPlaceholder": {"message": "123456"},
|
||||
"saveAndLogIn": {"message": "Opslaan en inloggen"},
|
||||
"thisPlugin": {"message": "Deze plug-in"},
|
||||
"pluginDescription": {"message": "Deze plug-in legt koppelingen vast op een LinkLog-server, die ze publiceert op een website en mogelijk op een fediverse-dienst of andere locaties, afhankelijk van de geconfigureerde plug-ins."},
|
||||
"accountRequirement": {"message": "Gebruikers van deze plug-in hebben een account op een LinkLog-server nodig"},
|
||||
"privacy": {"message": "Privacy"},
|
||||
"privacyDescription": {"message": "Deze plug-in respecteert je privacy en verzamelt geen persoonsgegevens buiten wat nodig is om koppelingen op je LinkLog-server vast te leggen."},
|
||||
"storedData": {"message": "De URL, na een poging om trackingparameters te verwijderen, de paginatitel, een eventuele opmerking en het tijdstip van bezoek worden op de backendserver opgeslagen en samen met het profiel van de geregistreerde gebruiker openbaar gemaakt."},
|
||||
"backendHeading": {"message": "LinkLog-backend"},
|
||||
"backendDescription": {"message": "De backend-URL is een zelfgehoste LinkLog-toepassing. Bekijk de"},
|
||||
"backendSource": {"message": "voor de broncode."},
|
||||
"copyright": {"message": "Copyright © 2026 Olaf Kolkman"},
|
||||
"repository": {"message": "Repository"},
|
||||
"signInToSelectTags": {"message": "Log in om bestaande tags te selecteren."},
|
||||
"loadTagsFailed": {"message": "Bestaande tags konden niet worden geladen."},
|
||||
"submitting": {"message": "Verzenden..."},
|
||||
"configureAndLogIn": {"message": "Configureer de backend-URL en log eerst in."},
|
||||
"sessionExpired": {"message": "Sessie verlopen. Verifieer opnieuw in de instellingen."},
|
||||
"submissionFailed": {"message": "Verzenden mislukt"},
|
||||
"linkSaved": {"message": "Koppeling opgeslagen op $URL$.", "placeholders": {"url": {"content": "$1"}}},
|
||||
"linkAlreadyExists": {"message": "Deze koppeling bestaat al. De opmerking en tags zijn bijgewerkt en publiceren is opnieuw gestart."},
|
||||
"duplicateLinkWarning": {"message": "Deze koppeling bestaat al. De opmerking en tags kunnen worden bijgewerkt; na verzenden wordt publiceren opnieuw gestart."},
|
||||
"publishingErrors": {"message": "Publicatiefouten: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
|
||||
"submissionFailedConnection": {"message": "Verzenden mislukt. Controleer de verbinding met de backend."},
|
||||
"loggedInAt": {"message": "$USERNAME$ is ingelogd op $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||
"fillAllFields": {"message": "Vul alle velden in"},
|
||||
"loginFailed": {"message": "Inloggen mislukt"},
|
||||
"loggedInSuccessfully": {"message": "Succesvol ingelogd"},
|
||||
"unableToLogIn": {"message": "Inloggen mislukt. Controleer de backend-URL en inloggegevens."},
|
||||
"signedOut": {"message": "Uitgelogd"}
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 5.9 KiB |
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,21 @@
|
||||
// Copyright © 2026 Olaf Kolkman
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
function getLocalizedMessage(messageId, substitutions = []) {
|
||||
const message = browser.i18n.getMessage(messageId, substitutions);
|
||||
return message || messageId;
|
||||
}
|
||||
|
||||
window.linklogI18n = getLocalizedMessage;
|
||||
|
||||
document.querySelectorAll('[data-i18n]').forEach((element) => {
|
||||
element.textContent = getLocalizedMessage(element.dataset.i18n);
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-i18n-placeholder]').forEach((element) => {
|
||||
element.placeholder = getLocalizedMessage(element.dataset.i18nPlaceholder);
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-i18n-alt]').forEach((element) => {
|
||||
element.alt = getLocalizedMessage(element.dataset.i18nAlt);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
|
||||
<g transform="matrix(1,0,0,1,-669.006,-255.89)">
|
||||
<g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)">
|
||||
<rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(24, 24, 37);"/>
|
||||
</g>
|
||||
<g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)">
|
||||
<path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/>
|
||||
</g>
|
||||
<g transform="matrix(0.135097,0,0,0.266653,668.366,1282.68)">
|
||||
<path d="M846.315,1802.1L846.315,1747.02C926.615,1744.29 989.248,1732.47 1034.22,1711.57C1079.18,1690.67 1110.8,1656.2 1129.07,1608.15C1147.34,1560.11 1156.47,1494.29 1156.47,1410.69C1156.47,1348.97 1150.95,1297.51 1139.91,1256.3C1128.87,1215.09 1110.5,1182.76 1084.81,1159.33C1067.94,1144.48 1048.07,1132.76 1025.18,1124.17C1002.3,1115.58 975.999,1109.52 946.288,1106.01C916.577,1102.49 883.253,1100.73 846.315,1100.73L846.315,1045.65L2092.36,1045.65L2092.36,1100.73C2037.36,1100.73 1990.18,1104.93 1950.83,1113.33C1911.49,1121.73 1879.47,1137.06 1854.78,1159.33C1830.08,1181.59 1811.92,1212.94 1800.27,1253.37C1788.63,1293.8 1782.81,1346.24 1782.81,1410.69L1782.81,1744.09C1860.7,1744.09 1935.18,1732.66 2006.24,1709.81C2077.31,1686.96 2140.34,1657.18 2195.35,1620.46C2250.35,1584.13 2294.21,1543.51 2326.94,1498.58C2359.66,1453.66 2377.83,1409.91 2381.44,1367.33L2444.68,1367.33C2444.68,1388.82 2444.07,1418.6 2442.87,1456.69C2441.66,1494.78 2439.86,1536.28 2437.45,1581.2C2434.64,1626.9 2431.33,1668.9 2427.51,1707.18C2423.7,1745.46 2419.18,1777.1 2413.96,1802.1L846.315,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M3043.37,1093.7C3001.22,1093.7 2961.37,1089.99 2923.83,1082.57C2886.29,1075.15 2853.66,1064.99 2825.96,1052.1C2797.86,1039.21 2775.67,1024.17 2759.41,1006.98C2743.15,989.794 2735.02,971.435 2735.02,951.904C2735.02,924.951 2748.97,900.732 2776.88,879.247C2804.78,857.763 2842.12,840.673 2888.9,827.978C2935.67,815.283 2987.16,808.935 3043.37,808.935C3101.59,808.935 3153.98,815.38 3200.56,828.271C3247.13,841.161 3284.07,858.447 3311.37,880.126C3338.67,901.806 3352.32,925.732 3352.32,951.904C3352.32,977.294 3338.67,1000.83 3311.37,1022.51C3284.07,1044.19 3247.13,1061.47 3200.56,1074.37C3153.98,1087.26 3101.59,1093.7 3043.37,1093.7ZM2498.94,1802.1L2498.94,1747.02C2608.95,1743.12 2686.24,1720.16 2730.81,1678.17C2775.37,1636.18 2797.66,1576.9 2797.66,1500.34C2797.66,1422.22 2776.08,1365.97 2732.91,1331.59C2689.75,1297.22 2618.39,1280.03 2518.82,1280.03L2518.82,1224.95L3327.03,1172.22L3327.03,1500.34C3327.03,1551.12 3333.76,1594.38 3347.2,1630.13C3360.66,1665.87 3386.05,1693.6 3423.39,1713.33C3460.73,1733.06 3515.53,1744.29 3587.8,1747.02L3587.8,1802.1L2498.94,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M3625.19,1802.1L3625.19,1747.02C3724.76,1743.12 3796.43,1721.83 3840.19,1683.15C3862.68,1663.62 3878.94,1639.6 3888.97,1611.08C3899.01,1582.57 3904.03,1549.17 3904.03,1510.89C3904.03,1447.22 3894.7,1399.37 3876.03,1367.33C3857.36,1335.3 3827.64,1313.72 3786.89,1302.59C3746.14,1291.45 3692.24,1285.89 3625.19,1285.89L3625.19,1230.81L4433.4,1178.08L4433.4,1274.76C4505.67,1243.51 4581.56,1216.94 4661.05,1195.07C4740.55,1173.19 4822.65,1162.26 4907.37,1162.26C4940.29,1162.26 4973.62,1164.31 5007.34,1168.41C5041.07,1172.51 5073.19,1183.93 5103.7,1202.68C5122.98,1214.79 5139.84,1231.2 5154.29,1251.9C5168.34,1273 5179.59,1299.17 5188.02,1330.42C5196.45,1361.67 5200.66,1399.37 5200.66,1443.51L5199.46,1488.62C5198.26,1504.25 5197.65,1521.24 5197.65,1539.6C5197.65,1573.97 5199.46,1604.15 5203.07,1630.13C5206.69,1656.1 5215.92,1677.68 5230.78,1694.87C5245.23,1712.06 5267.51,1725.05 5297.63,1733.84C5327.74,1742.63 5369.29,1747.02 5422.29,1747.02L5422.29,1802.1L4575.53,1802.1L4575.53,1757.57C4601.63,1741.16 4619.7,1713.62 4629.74,1674.95C4639.77,1636.28 4644.79,1583.35 4644.79,1516.16C4644.79,1457.96 4639.47,1415.09 4628.83,1387.55C4618.19,1360.01 4603.74,1342.14 4585.47,1333.93C4567.2,1325.73 4546.83,1321.63 4524.34,1321.63C4510.29,1321.63 4495.54,1323.1 4480.08,1326.03C4464.62,1328.95 4449.06,1332.96 4433.4,1338.04L4433.4,1526.71C4433.4,1595.07 4438.52,1646.53 4448.76,1681.1C4459,1715.67 4476.97,1741.16 4502.66,1757.57L4502.66,1802.1L3625.19,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M6760.3,1835.5C6693.65,1835.5 6638.55,1833.06 6594.99,1828.17C6551.42,1823.29 6518.2,1814.4 6495.32,1801.51C6481.26,1793.7 6469.62,1783.35 6460.39,1770.46C6451.55,1757.96 6444.73,1743.31 6439.91,1726.51C6435.09,1709.72 6430.67,1690.38 6426.66,1668.51C6422.64,1647.41 6416.92,1627.68 6409.49,1609.33C6402.07,1590.97 6387.21,1575.83 6364.93,1563.91C6342.65,1552 6306.81,1545.85 6257.43,1545.46C6258.23,1615.38 6265.66,1666.45 6279.71,1698.68C6293.76,1730.91 6320.86,1747.02 6361.01,1747.02L6361.01,1802.1L5449.21,1802.1L5449.21,1747.02C5485.35,1745.85 5517.27,1742.92 5544.97,1738.23C5600.78,1728.86 5642.33,1707.96 5669.64,1675.54C5683.69,1658.35 5695.13,1636.87 5703.96,1611.08C5712.4,1585.3 5718.52,1554.15 5722.33,1517.63C5726.15,1481.1 5728.05,1438.43 5728.05,1389.6C5728.05,1315.38 5722.84,1255.22 5712.4,1209.13C5701.96,1163.04 5685.49,1127.1 5663.01,1101.32C5640.53,1075.93 5611.72,1058.74 5576.59,1049.76C5541.46,1040.77 5499,1036.28 5449.21,1036.28L5449.21,981.786L6257.43,929.052L6257.43,1462.84C6286.74,1442.92 6314.84,1422.12 6341.74,1400.44C6368.64,1378.76 6392.33,1358.54 6412.81,1339.79C6457.78,1298.39 6480.26,1272.8 6480.26,1263.04C6480.26,1255.22 6471.63,1250.15 6454.36,1247.8C6437.1,1245.46 6413.61,1244.29 6383.9,1244.29L6383.9,1189.21L7053.6,1189.21L7053.6,1244.29C7005.82,1244.29 6953.42,1249.76 6896.41,1260.69C6839.4,1271.63 6778.97,1288.04 6715.14,1309.91C6650.9,1331.79 6583.85,1359.33 6513.99,1392.53C6444.12,1425.73 6372.46,1464.6 6298.98,1509.13C6373.66,1497.41 6449.04,1488.13 6525.13,1481.3C6601.21,1474.46 6668.36,1471.04 6726.58,1471.04C6810.89,1471.04 6875.33,1480.42 6919.9,1499.17C6965.67,1518.7 6994.58,1550.34 7006.62,1594.09C7013.85,1619.87 7023.18,1641.94 7034.63,1660.3C7046.07,1678.66 7058.21,1693.9 7071.06,1706.01C7083.91,1718.12 7096.86,1727.2 7109.91,1733.25C7122.96,1739.31 7134.3,1742.92 7143.93,1744.09L7143.93,1805.62C7133.49,1808.74 7116.23,1811.96 7092.14,1815.28C7068.05,1818.6 7039.14,1821.83 7005.42,1824.95C6971.29,1828.08 6933.35,1830.62 6891.59,1832.57C6849.84,1834.52 6806.07,1835.5 6760.3,1835.5Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M7746.18,1802.1L7746.18,1747.02C7826.48,1744.29 7889.11,1732.47 7934.08,1711.57C7979.05,1690.67 8010.67,1656.2 8028.93,1608.15C8047.2,1560.11 8056.34,1494.29 8056.34,1410.69C8056.34,1348.97 8050.82,1297.51 8039.77,1256.3C8028.73,1215.09 8010.36,1182.76 7984.67,1159.33C7967.81,1144.48 7947.93,1132.76 7925.05,1124.17C7902.16,1115.58 7875.86,1109.52 7846.15,1106.01C7816.44,1102.49 7783.12,1100.73 7746.18,1100.73L7746.18,1045.65L8992.23,1045.65L8992.23,1100.73C8937.22,1100.73 8890.05,1104.93 8850.7,1113.33C8811.35,1121.73 8779.33,1137.06 8754.64,1159.33C8729.95,1181.59 8711.78,1212.94 8700.14,1253.37C8688.49,1293.8 8682.67,1346.24 8682.67,1410.69L8682.67,1744.09C8760.56,1744.09 8835.04,1732.66 8906.1,1709.81C8977.17,1686.96 9040.2,1657.18 9095.21,1620.46C9150.22,1584.13 9194.08,1543.51 9226.8,1498.58C9259.52,1453.66 9277.69,1409.91 9281.3,1367.33L9344.54,1367.33C9344.54,1388.82 9343.94,1418.6 9342.73,1456.69C9341.53,1494.78 9339.72,1536.28 9337.31,1581.2C9334.5,1626.9 9331.19,1668.9 9327.38,1707.18C9323.56,1745.46 9319.05,1777.1 9313.83,1802.1L7746.18,1802.1Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M10190.6,1828.47C10046.1,1828.47 9919.52,1816.36 9810.91,1792.14C9702.31,1767.92 9617.89,1731.2 9557.67,1681.98C9497.44,1632.76 9467.33,1570.65 9467.33,1495.65C9467.33,1439.01 9484.69,1389.6 9519.43,1347.41C9554.15,1305.22 9603.24,1270.46 9666.67,1243.12C9730.11,1215.38 9806.19,1194.87 9894.93,1181.59C9983.66,1168.31 10082.2,1161.67 10190.6,1161.67C10298.6,1161.67 10397.2,1168.31 10486.3,1181.59C10575.5,1194.87 10651.5,1215.38 10714.6,1243.12C10778,1270.46 10827,1305.22 10861.5,1347.41C10896.1,1389.6 10913.3,1439.01 10913.3,1495.65C10913.3,1551.9 10896.1,1600.83 10861.5,1642.43C10827,1684.03 10778,1718.7 10714.6,1746.43C10651.5,1773.78 10575.5,1794.29 10486.3,1807.96C10397.2,1821.63 10298.6,1828.47 10190.6,1828.47ZM10190.6,1766.94C10209.5,1766.94 10226.5,1759.62 10241.5,1744.97C10256.6,1730.32 10269.5,1710.5 10280.4,1685.5C10302,1634.72 10312.9,1571.43 10312.9,1495.65C10312.9,1419.09 10302,1355.22 10280.4,1304.05C10269.5,1279.05 10256.6,1259.13 10241.5,1244.29C10226.5,1229.44 10209.5,1222.02 10190.6,1222.02C10171.4,1222.02 10154.2,1229.44 10139.1,1244.29C10124.1,1259.13 10111.3,1279.05 10100.9,1304.05C10090.1,1329.05 10081.8,1358.06 10076.2,1391.06C10070.6,1424.07 10067.8,1458.93 10067.8,1495.65C10067.8,1531.98 10070.6,1566.55 10076.2,1599.37C10081.8,1632.18 10090.1,1660.89 10100.9,1685.5C10111.3,1710.5 10124.1,1730.32 10139.1,1744.97C10154.2,1759.62 10171.4,1766.94 10190.6,1766.94Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
<path d="M11680.5,2098C11591.8,2098 11505.8,2096.73 11422.7,2094.19C11339.6,2091.65 11261.9,2085.5 11189.7,2075.73C11166.4,2072.61 11144.8,2069.09 11124.9,2065.18C11105,2061.28 11086.5,2056.79 11069.2,2051.71C11035.1,2041.55 11008.3,2029.35 10988.8,2015.09C10969.3,2000.83 10959.6,1983.54 10959.6,1963.23C10959.6,1947.22 10967.4,1932.86 10983.1,1920.16C10998.7,1907.47 11020,1896.43 11046.9,1887.06C11073.4,1877.68 11104.1,1869.58 11139.1,1862.74C11174,1855.91 11210.7,1850.34 11249.3,1846.04C11216.4,1832.37 11189.8,1815.87 11169.5,1796.53C11149.2,1777.2 11139.1,1755.22 11139.1,1730.62C11139.1,1713.43 11144.3,1697.51 11154.7,1682.86C11165.2,1668.21 11179.4,1654.83 11197.5,1642.72C11233.2,1618.51 11279.6,1600.34 11336.6,1588.23C11278.4,1578.86 11227.2,1565.77 11183,1548.97C11138.9,1532.18 11104.2,1511.18 11079.1,1485.99C11054.1,1460.79 11041.5,1431.01 11041.5,1396.63C11041.5,1355.62 11059.5,1319.97 11095.4,1289.7C11131.3,1259.42 11179,1235.11 11238.4,1216.75C11297.5,1198.39 11365.3,1184.72 11442,1175.73C11518.7,1166.75 11599.2,1162.26 11683.5,1162.26C11753.4,1162.26 11820.9,1165.28 11886.2,1171.34C11951.4,1177.39 12011.7,1187.06 12067.1,1200.34C12080.8,1169.48 12099,1145.46 12121.9,1128.27C12144.8,1111.08 12170.6,1098.68 12199.3,1091.06C12228,1083.45 12257.7,1078.76 12288.5,1077C12319.2,1075.24 12349.2,1074.37 12378.5,1074.37C12397.4,1074.37 12418.1,1074.56 12440.8,1074.95C12463.5,1075.34 12488.3,1076.32 12515.2,1077.88C12512.8,1088.82 12510.6,1103.86 12508.6,1123C12506.6,1142.14 12501.5,1159.13 12493.5,1173.97C12484.7,1190.38 12467.6,1201.71 12442.3,1207.96C12417,1214.21 12393.1,1217.33 12370.7,1217.33L12230.9,1217.33C12215.7,1217.33 12200.9,1217.63 12186.7,1218.21C12172.4,1218.8 12159.1,1220.46 12146.6,1223.19C12200.4,1241.55 12243.7,1265.09 12276.4,1293.8C12309.1,1322.51 12325.5,1356.79 12325.5,1396.63C12325.5,1438.04 12307.6,1472.7 12271.9,1500.63C12236.2,1528.56 12188.6,1550.54 12129.2,1566.55C12069.3,1582.57 12001.4,1594.09 11925.3,1601.12C11849.2,1608.15 11768.6,1611.67 11683.5,1611.67C11638.5,1611.67 11594.4,1610.79 11551,1609.03C11507.6,1607.28 11465.7,1604.25 11425.1,1599.95L11425.7,1602.88C11413.7,1602.88 11402.2,1606.4 11391.4,1613.43C11380.6,1620.46 11375.1,1629.25 11375.1,1639.79C11375.1,1649.17 11380.5,1657.18 11391.1,1663.82C11401.7,1670.46 11415.7,1675.73 11433,1679.64C11450.6,1683.54 11470.8,1686.38 11493.5,1688.13C11516.2,1689.89 11540,1690.77 11564.9,1690.77L11884,1690.77C11957.1,1690.77 12026.9,1691.06 12093.3,1691.65C12159.8,1692.24 12222.1,1697.61 12280.3,1707.76C12334.1,1716.75 12377.9,1733.25 12411.6,1757.28C12445.3,1781.3 12462.2,1815.58 12462.2,1860.11C12462.2,1897.61 12450.8,1929.44 12427.9,1955.62C12405,1981.79 12373.6,2003.56 12333.6,2020.95C12293.7,2038.33 12247.8,2052.29 12196,2062.84C12145,2073 12090.1,2080.62 12031.3,2085.69C11972.5,2090.77 11913.1,2094.09 11853,2095.65C11793,2097.22 11735.5,2098 11680.5,2098ZM11682.9,1547.22C11712.2,1547.22 11735.9,1539.79 11754,1524.95C11772,1510.11 11785.2,1490.58 11793.4,1466.36C11801.6,1442.14 11805.8,1415.77 11805.8,1387.26C11805.8,1341.94 11796.3,1303.76 11777.4,1272.7C11758.6,1241.65 11727.1,1226.12 11682.9,1226.12C11639.1,1226.12 11607.9,1241.65 11589.2,1272.7C11570.6,1303.76 11561.2,1341.94 11561.2,1387.26C11561.2,1415.38 11565.4,1441.65 11573.6,1466.06C11581.8,1490.48 11594.9,1510.11 11612.7,1524.95C11630.6,1539.79 11654,1547.22 11682.9,1547.22ZM11708.2,2035.3C11747.1,2035.3 11786.1,2034.62 11825,2033.25C11864,2031.88 11899.5,2028.66 11931.6,2023.58C11964.1,2018.9 11990.8,2011.87 12011.7,2002.49C12032.6,1993.12 12043,1980.62 12043,1964.99C12043,1947.02 12029.1,1933.25 12001.2,1923.68C11973.3,1914.11 11935.4,1906.98 11887.7,1902.29C11839.5,1897.61 11782.4,1894.78 11716.3,1893.8C11650.3,1892.82 11579.1,1892.33 11502.8,1892.33C11490.8,1892.33 11478.6,1891.94 11466.4,1891.16C11454.1,1890.38 11442,1889.4 11430,1888.23C11404.3,1905.81 11391.4,1929.44 11391.4,1959.13C11391.4,1974.76 11398.9,1987.55 11414,1997.51C11429,2007.47 11450.4,2015.18 11478.1,2020.65C11505.8,2026.12 11539.2,2029.93 11578.1,2032.08C11617.1,2034.23 11660.4,2035.3 11708.2,2035.3Z" style="fill:rgb(203,166,247);fill-rule:nonzero;"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 14 KiB |
@@ -1,19 +1,42 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "LinkLog",
|
||||
"name": "__MSG_extensionName__",
|
||||
"version": "0.1.0",
|
||||
"description": "Capture and submit page links to LinkLog.",
|
||||
"description": "__MSG_extensionDescription__",
|
||||
"default_locale": "en-US",
|
||||
"permissions": [
|
||||
"activeTab",
|
||||
"storage",
|
||||
"tabs"
|
||||
"storage"
|
||||
],
|
||||
"host_permissions": [
|
||||
"<all_urls>"
|
||||
"optional_permissions": [
|
||||
"http://*/*",
|
||||
"https://*/*"
|
||||
],
|
||||
"content_security_policy": {
|
||||
"extension_pages": "script-src 'self'; object-src 'none'"
|
||||
},
|
||||
"action": {
|
||||
"default_title": "LinkLog",
|
||||
"default_popup": "popup.html"
|
||||
"default_title": "__MSG_extensionName__",
|
||||
"default_popup": "popup.html",
|
||||
"default_icon": {
|
||||
"16": "icon-16.png",
|
||||
"32": "icon-32.png"
|
||||
}
|
||||
},
|
||||
"icons": {
|
||||
"48": "icon-48.png",
|
||||
"96": "icon-96.png"
|
||||
},
|
||||
"browser_specific_settings": {
|
||||
"gecko": {
|
||||
"id": "linklog@kolkman.org",
|
||||
"strict_min_version": "142.0",
|
||||
"data_collection_permissions": {
|
||||
"required": ["websiteActivity"],
|
||||
"optional": []
|
||||
},
|
||||
"update_url": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json"
|
||||
}
|
||||
},
|
||||
"options_ui": {
|
||||
"page": "options.html",
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
/* Copyright © 2026 Olaf Kolkman */
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: sans-serif;
|
||||
@@ -18,6 +21,15 @@ h1 {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.extension-logo {
|
||||
display: block;
|
||||
width: 190px;
|
||||
height: 52px;
|
||||
margin-bottom: 8px;
|
||||
object-fit: contain;
|
||||
object-position: left center;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 16px;
|
||||
@@ -66,6 +78,43 @@ button {
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.logged-in {
|
||||
margin-bottom: 16px;
|
||||
padding: 14px;
|
||||
border: 1px solid #45475a;
|
||||
border-radius: 8px;
|
||||
background: #313244;
|
||||
color: #cdd6f4;
|
||||
}
|
||||
|
||||
.logged-in p {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.logged-in button {
|
||||
background: #f38ba8;
|
||||
color: #11111b;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.extension-footer {
|
||||
margin: 16px auto;
|
||||
color: #7f849c;
|
||||
font-size: 0.68rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.extension-footer a {
|
||||
color: inherit;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.extension-footer a:hover,
|
||||
.extension-footer a:focus-visible,
|
||||
.extension-footer a:active {
|
||||
color: #b4befe;
|
||||
}
|
||||
|
||||