Compare commits
29
Commits
079eb146f6
...
v0.1.0
| 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 |
+4
-2
@@ -10,8 +10,10 @@ APP_HEALTHCHECK_RETRIES=3
|
|||||||
LINKLOG_APP_NAME=LinkLog
|
LINKLOG_APP_NAME=LinkLog
|
||||||
LINKLOG_VERSION=0.1.0
|
LINKLOG_VERSION=0.1.0
|
||||||
LINKLOG_SECRET_KEY=replace-with-a-long-random-secret
|
LINKLOG_SECRET_KEY=replace-with-a-long-random-secret
|
||||||
LINKLOG_TOKEN_EXPIRY_DAYS=30
|
LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key
|
||||||
LINKLOG_PUBLIC_URL=localhost
|
LINKLOG_TOKEN_EXPIRY_MINUTES=15
|
||||||
|
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS=30
|
||||||
|
LINKLOG_PUBLIC_URL=linklog.example.com
|
||||||
LINKLOG_SMTP_HOST=
|
LINKLOG_SMTP_HOST=
|
||||||
LINKLOG_SMTP_PORT=587
|
LINKLOG_SMTP_PORT=587
|
||||||
LINKLOG_SMTP_USERNAME=
|
LINKLOG_SMTP_USERNAME=
|
||||||
|
|||||||
@@ -19,11 +19,10 @@ jobs:
|
|||||||
- name: Validate versions and signed XPI
|
- name: Validate versions and signed XPI
|
||||||
id: release
|
id: release
|
||||||
run: |
|
run: |
|
||||||
python3 scripts/release/validate_release.py
|
python3 scripts/release/validate_release.py --github-output "$GITHUB_OUTPUT"
|
||||||
version=$(python3 -c "import json; print(json.load(open('frontend/version.json'))['version'])")
|
backend_version=$(python3 -c "import re; text=open('backend/app/core/config.py').read(); print(re.search(r\"version: str = os\\.getenv\\('LINKLOG_VERSION', '([^']+)'\\)\", text).group(1))")
|
||||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
if [ "${GITHUB_REF_NAME#v}" != "$backend_version" ]; then
|
||||||
if [ "${GITHUB_REF_NAME#v}" != "$version" ]; then
|
echo "tag ${GITHUB_REF_NAME} does not match backend version $backend_version" >&2
|
||||||
echo "tag ${GITHUB_REF_NAME} does not match release version $version" >&2
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -40,51 +39,113 @@ jobs:
|
|||||||
context: .
|
context: .
|
||||||
push: true
|
push: true
|
||||||
tags: |
|
tags: |
|
||||||
${{ env.IMAGE_NAME }}:${{ steps.release.outputs.version }}
|
${{ env.IMAGE_NAME }}:${{ steps.release.outputs.backend_version }}
|
||||||
${{ env.IMAGE_NAME }}:latest
|
${{ env.IMAGE_NAME }}:latest
|
||||||
labels: |
|
labels: |
|
||||||
org.opencontainers.image.version=${{ steps.release.outputs.version }}
|
org.opencontainers.image.version=${{ steps.release.outputs.backend_version }}
|
||||||
org.opencontainers.image.source=https://git.kolkman.org/olaf/Link-Log
|
org.opencontainers.image.source=https://git.kolkman.org/olaf/Link-Log
|
||||||
|
|
||||||
|
- name: Generate release README
|
||||||
|
env:
|
||||||
|
BACKEND_VERSION: ${{ steps.release.outputs.backend_version }}
|
||||||
|
PLUGIN_VERSION: ${{ steps.release.outputs.plugin_version }}
|
||||||
|
SIGNED_XPI: ${{ steps.release.outputs.signed_xpi }}
|
||||||
|
run: |
|
||||||
|
cat > release-readme.md <<EOF
|
||||||
|
# LinkLog $BACKEND_VERSION
|
||||||
|
|
||||||
|
LinkLog is a Firefox extension and Python web service for saving links with a title, comment, timestamp, and tracking parameters removed. The service stores links in SQLite and can publish them through plugins, including Mastodon.
|
||||||
|
|
||||||
|
## Docker Container
|
||||||
|
|
||||||
|
The current backend/container version is $BACKEND_VERSION. Pull it from the Gitea container registry:
|
||||||
|
|
||||||
|
\`\`\`sh
|
||||||
|
docker pull $IMAGE_NAME:$BACKEND_VERSION
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
The same image is also published as:
|
||||||
|
|
||||||
|
\`\`\`sh
|
||||||
|
docker pull $IMAGE_NAME:latest
|
||||||
|
\`\`\`
|
||||||
|
The developer version of the backend is always published as $IMAGE_NAME:latest, which may be ahead of the current release version and may be unstable.
|
||||||
|
Additional information about the backend can be found in the [README](https://git.kolkman.org/olaf/Link-Log/src/branch/main/backend/README.md).
|
||||||
|
|
||||||
|
## Firefox Extension
|
||||||
|
|
||||||
|
The current signed Firefox plugin version, compatible with this version of the backend, is $PLUGIN_VERSION. Download it from the raw repository artifact:
|
||||||
|
|
||||||
|
https://git.kolkman.org/olaf/Link-Log/raw/branch/main/$SIGNED_XPI
|
||||||
|
EOF
|
||||||
|
|
||||||
- name: Create Gitea release
|
- name: Create Gitea release
|
||||||
id: gitea_release
|
id: gitea_release
|
||||||
env:
|
env:
|
||||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
VERSION: ${{ steps.release.outputs.version }}
|
VERSION: ${{ steps.release.outputs.backend_version }}
|
||||||
run: |
|
run: |
|
||||||
response=$(curl --fail-with-body --silent --show-error \
|
payload_file=$(mktemp)
|
||||||
|
python3 - <<'PY' > "$payload_file"
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
version = os.environ['VERSION']
|
||||||
|
print(json.dumps({
|
||||||
|
'tag_name': f'v{version}',
|
||||||
|
'name': f'LinkLog {version}',
|
||||||
|
'body': Path('release-readme.md').read_text(),
|
||||||
|
'draft': False,
|
||||||
|
'prerelease': False,
|
||||||
|
}))
|
||||||
|
PY
|
||||||
|
response_file=$(mktemp)
|
||||||
|
response_status=$(curl --silent --show-error -o "$response_file" -w '%{http_code}' \
|
||||||
-X POST \
|
-X POST \
|
||||||
-H "Authorization: token $RELEASE_TOKEN" \
|
-H "Authorization: token $RELEASE_TOKEN" \
|
||||||
-H 'Content-Type: application/json' \
|
-H 'Content-Type: application/json' \
|
||||||
-d "{\"tag_name\":\"v$VERSION\",\"name\":\"LinkLog $VERSION\",\"draft\":false,\"prerelease\":false}" \
|
--data-binary "@$payload_file" \
|
||||||
https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases)
|
https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases)
|
||||||
release_id=$(printf '%s' "$response" | jq -r '.id')
|
rm -f "$payload_file"
|
||||||
|
if [ "$response_status" = 409 ]; then
|
||||||
|
response_status=$(curl --silent --show-error -o "$response_file" -w '%{http_code}' \
|
||||||
|
-H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
"https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases/tags/v$VERSION")
|
||||||
|
fi
|
||||||
|
if [ "$response_status" -lt 200 ] || [ "$response_status" -ge 300 ]; then
|
||||||
|
cat "$response_file" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
response=$(cat "$response_file")
|
||||||
|
rm -f "$response_file"
|
||||||
|
release_id=$(printf '%s' "$response" | python3 -c 'import json, sys; print(json.load(sys.stdin)["id"])')
|
||||||
test "$release_id" != null
|
test "$release_id" != null
|
||||||
test "$release_id" != 0
|
test "$release_id" != 0
|
||||||
upload_url="https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases/$release_id/assets"
|
upload_url="https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases/$release_id/assets"
|
||||||
echo "upload_url=$upload_url" >> "$GITHUB_OUTPUT"
|
echo "upload_url=$upload_url" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Upload signed XPI and update manifest
|
- name: Upload release README
|
||||||
env:
|
env:
|
||||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
UPLOAD_URL: ${{ steps.gitea_release.outputs.upload_url }}
|
UPLOAD_URL: ${{ steps.gitea_release.outputs.upload_url }}
|
||||||
VERSION: ${{ steps.release.outputs.version }}
|
|
||||||
run: |
|
run: |
|
||||||
curl --fail-with-body --silent --show-error \
|
response_status=$(curl --silent --show-error -o /tmp/linklog-readme-upload-response -w '%{http_code}' \
|
||||||
-X POST -H "Authorization: token $RELEASE_TOKEN" \
|
-X POST -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
-H 'Content-Type: application/x-xpinstall' \
|
-H 'Content-Type: text/markdown' \
|
||||||
--data-binary "@XPI/signed/LinkLog-$VERSION.xpi" \
|
--data-binary @release-readme.md \
|
||||||
"$UPLOAD_URL?name=LinkLog-$VERSION.xpi"
|
"$UPLOAD_URL?name=README.md")
|
||||||
curl --fail-with-body --silent --show-error \
|
if [ "$response_status" -lt 200 ] || [ "$response_status" -ge 300 ]; then
|
||||||
-X POST -H "Authorization: token $RELEASE_TOKEN" \
|
cat /tmp/linklog-readme-upload-response >&2
|
||||||
-H 'Content-Type: application/json' \
|
exit 1
|
||||||
--data-binary @webextension/updates.json \
|
fi
|
||||||
"$UPLOAD_URL?name=updates.json"
|
|
||||||
|
|
||||||
- name: Publish release links
|
- name: Publish release links
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ steps.release.outputs.version }}
|
BACKEND_VERSION: ${{ steps.release.outputs.backend_version }}
|
||||||
|
PLUGIN_VERSION: ${{ steps.release.outputs.plugin_version }}
|
||||||
|
SIGNED_XPI: ${{ steps.release.outputs.signed_xpi }}
|
||||||
run: |
|
run: |
|
||||||
echo "Docker image: $IMAGE_NAME:$VERSION"
|
echo "Docker image: $IMAGE_NAME:$BACKEND_VERSION"
|
||||||
echo "Signed XPI: https://git.kolkman.org/olaf/Link-Log/releases/download/v$VERSION/LinkLog-$VERSION.xpi"
|
echo "Signed XPI: https://git.kolkman.org/olaf/Link-Log/raw/branch/main/$SIGNED_XPI (version $PLUGIN_VERSION)"
|
||||||
echo "Firefox update manifest: https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json"
|
echo "Release README: README.md"
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ frontend/ Jinja templates and browser-side assets
|
|||||||
webextension/ Firefox Manifest V3 extension
|
webextension/ Firefox Manifest V3 extension
|
||||||
Logo.svg Source logo artwork used by the web and extension interfaces
|
Logo.svg Source logo artwork used by the web and extension interfaces
|
||||||
Dockerfile Backend container image
|
Dockerfile Backend container image
|
||||||
docker-compose.yml App with traefik reverse proxy hooks
|
docker-compose.yml Production app with Traefik reverse proxy hooks
|
||||||
|
docker-compose.local.yml Local development app with direct port access
|
||||||
REQUIREMENTS.md Product requirements
|
REQUIREMENTS.md Product requirements
|
||||||
VIBE/ Conversation and prompt logs
|
VIBE/ Conversation and prompt logs
|
||||||
```
|
```
|
||||||
@@ -68,6 +69,7 @@ Open these URLs:
|
|||||||
- About: <http://localhost:8000/about>
|
- About: <http://localhost:8000/about>
|
||||||
- Admin page: <http://localhost:8000/admin>
|
- Admin page: <http://localhost:8000/admin>
|
||||||
- Web login: <http://localhost:8000/login>
|
- Web login: <http://localhost:8000/login>
|
||||||
|
- Token refresh: `POST http://localhost:8000/api/auth/refresh`
|
||||||
- Health check: <http://localhost:8000/health>
|
- Health check: <http://localhost:8000/health>
|
||||||
- OpenAPI documentation: <http://localhost:8000/docs>
|
- OpenAPI documentation: <http://localhost:8000/docs>
|
||||||
|
|
||||||
@@ -94,13 +96,25 @@ make xpi
|
|||||||
|
|
||||||
This creates `XPI/unsigned/LinkLog-0.1.0.xpi` from the `webextension/` package and excludes macOS metadata and minified artifacts. The version is read from `webextension/manifest.json`. The `XPI/signed/` directory is reserved for signed release bundles.
|
This creates `XPI/unsigned/LinkLog-0.1.0.xpi` from the `webextension/` package and excludes macOS metadata and minified artifacts. The version is read from `webextension/manifest.json`. The `XPI/signed/` directory is reserved for signed release bundles.
|
||||||
|
|
||||||
|
## Docker Deployment
|
||||||
|
|
||||||
|
The main `docker-compose.yml` is the production deployment. It does not publish port 8000 on the host; the application is reachable through Traefik on the external `linklog_traefik` network. Set `LINKLOG_PUBLIC_URL` to the DNS hostname served by Traefik. The default is the documentation hostname `linklog.example.com`, which must be replaced for a real deployment.
|
||||||
|
|
||||||
|
For local development with direct access, use the separate file:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose -f docker-compose.local.yml up --build
|
||||||
|
```
|
||||||
|
|
||||||
|
This publishes `${APP_PORT:-8000}` and defaults the application URL to `http://localhost:8000`. Do not use the local file for an Internet-facing deployment.
|
||||||
|
|
||||||
## Releases
|
## Releases
|
||||||
|
|
||||||
Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `frontend/version.json`; the Firefox plugin version comes from `webextension/manifest.json`. CI also requires both to match `LINKLOG_VERSION`'s default in `backend/app/core/config.py`.
|
Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `LINKLOG_VERSION`'s default in `backend/app/core/config.py`; the tag must match that backend version. The Firefox plugin version is independent and comes from the most recent signed `XPI/signed/LinkLog-<version>.xpi` checked into the repository.
|
||||||
|
|
||||||
The signed XPI is produced manually and must be checked into `XPI/signed/LinkLog-<version>.xpi` before creating the tag. The workflow validates the embedded manifest, publishes the XPI and `webextension/updates.json` as Gitea release assets, and publishes Docker images to `git.kolkman.org/olaf/link-log:<version>` and `:latest`.
|
The signed XPI is produced manually and should be checked into `XPI/signed/LinkLog-<version>.xpi`. The workflow validates the latest signed XPI's embedded manifest, publishes Docker images to `git.kolkman.org/olaf/link-log:<backend-version>` and `:latest`, and creates a release README that describes the project, the current backend/container version, and the raw signed XPI download URL with the plugin version.
|
||||||
|
|
||||||
The extension's `update_url` points at the stable raw repository URL `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json`. Update `webextension/updates.json` with each signed XPI version and commit it together with the XPI. The release page provides a direct install link at `https://git.kolkman.org/olaf/Link-Log/releases/download/v<version>/LinkLog-<version>.xpi`.
|
The extension's `update_url` points at the stable raw repository URL `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json`. Update `webextension/updates.json` with each signed XPI version and commit it together with the XPI. Release READMEs point to the raw signed XPI at `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-<version>.xpi`.
|
||||||
|
|
||||||
The workflow requires Gitea Actions secrets named `REGISTRY_USERNAME`, `REGISTRY_TOKEN`, and `RELEASE_TOKEN`. `REGISTRY_TOKEN` is a Gitea access token with permission to push packages; `RELEASE_TOKEN` needs permission to create releases and upload release assets.
|
The workflow requires Gitea Actions secrets named `REGISTRY_USERNAME`, `REGISTRY_TOKEN`, and `RELEASE_TOKEN`. `REGISTRY_TOKEN` is a Gitea access token with permission to push packages; `RELEASE_TOKEN` needs permission to create releases and upload release assets.
|
||||||
|
|
||||||
@@ -108,12 +122,16 @@ Every push to `main` also runs `.gitea/workflows/development.yml` and publishes
|
|||||||
|
|
||||||
Appending a username to the root URL, such as `/alice`, opens that user's public feed and profile information.
|
Appending a username to the root URL, such as `/alice`, opens that user's public feed and profile information.
|
||||||
|
|
||||||
Configuration APIs require a bearer token returned by the login endpoint. 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.
|
Configuration APIs require a bearer token returned by the login endpoint. Send it in the `Authorization: Bearer ...` header; query-string tokens are not accepted. Users authenticate with their email address; the username remains the public presentation identity used in profiles and feed URLs. User configuration uses the identity in that token. Plugin administration additionally requires an administrator account.
|
||||||
|
|
||||||
|
Login failures are throttled per client IP and email. Five failures within 15 minutes trigger a two-minute lockout, including invalid OTP attempts; successful authentication clears the failure counter.
|
||||||
|
|
||||||
Users can change their password from the profile page. The current password is required, new passwords must contain at least 8 characters, and the endpoint is `PUT /api/user/password`.
|
Users can change their password from the profile page. The current password is required, new passwords must contain at least 8 characters, and the endpoint is `PUT /api/user/password`.
|
||||||
|
|
||||||
Users can configure a time-based one-time password from the profile page using an authenticator app. The profile displays a provisioning secret and authenticator URI during setup, then requires a current six-digit code to enable or disable OTP. When OTP is enabled, both the web login and Firefox extension settings login require the code. The TOTP secret is never returned by the profile API after setup.
|
Users can configure a time-based one-time password from the profile page using an authenticator app. The profile displays a provisioning secret and authenticator URI during setup, then requires a current six-digit code to enable or disable OTP. When OTP is enabled, both the web login and Firefox extension settings login require the code. The TOTP secret is never returned by the profile API after setup.
|
||||||
|
|
||||||
|
Users can add up to five additional email addresses from the profile page. Each additional address must be validated through a verification email before it can be used for authentication. A verified alternative can be promoted to primary; the previous primary remains as a verified alternative. The profile displays validation status and offers resend controls subject to the same 20-second interval, five-send limit, and two-minute cooldown used during initial setup.
|
||||||
|
|
||||||
On the profile page, the authenticated username is displayed as read-only. Users can upload a PNG, JPEG, GIF, or WebP avatar up to 2 MB; uploaded files are stored in the persistent data volume and served by the application. Bio and email fields remain empty until the user provides values. Mastodon settings default to the `mastodon.social` instance and the `From my #LinkLog: ` post prefix.
|
On the profile page, the authenticated username is displayed as read-only. Users can upload a PNG, JPEG, GIF, or WebP avatar up to 2 MB; uploaded files are stored in the persistent data volume and served by the application. Bio and email fields remain empty until the user provides values. Mastodon settings default to the `mastodon.social` instance and the `From my #LinkLog: ` post prefix.
|
||||||
|
|
||||||
## Run Tests
|
## Run Tests
|
||||||
@@ -138,15 +156,16 @@ The manifest includes stable Firefox extension metadata and references the packa
|
|||||||
1. Start the backend locally.
|
1. Start the backend locally.
|
||||||
2. Open Firefox and visit `about:debugging#/runtime/this-firefox`.
|
2. Open Firefox and visit `about:debugging#/runtime/this-firefox`.
|
||||||
3. Select **Load Temporary Add-on**.
|
3. Select **Load Temporary Add-on**.
|
||||||
4. Choose `webextension/manifest.json`.
|
4. Choose `webextension/manifest.json` (Firefox 142 or newer is required).
|
||||||
5. Open the LinkLog extension options and enter:
|
5. Open the LinkLog extension options and enter:
|
||||||
- Backend URL: the URL of your LinkLog server, such as `http://localhost:8000`
|
- Backend URL: the URL of your LinkLog server, such as `http://localhost:8000`
|
||||||
- Username: `alice`
|
- Email: `alice@example.com`
|
||||||
- Password: `secret123`
|
- Password: `secret123`
|
||||||
|
- One-time password: enter it when OTP is enabled
|
||||||
6. Save the settings and login.
|
6. Save the settings and login.
|
||||||
7. Open a webpage, select the LinkLog toolbar button, review the title and URL, add a comment, and submit it.
|
7. Open a webpage, select the LinkLog toolbar button, review the title and URL, add a comment, and submit it.
|
||||||
|
|
||||||
When the extension settings page has a valid session, it shows `<username> logged in at <backend URL>` and a **Sign out** button instead of the login form. Signing out revokes the token and returns the form.
|
When the extension settings page has a valid session, it shows `<username> logged in at <backend URL>` and a **Sign out** button instead of the login form. Access and refresh credentials are kept in Firefox session storage, so a browser restart requires login again. Signing out revokes the token family and returns the form.
|
||||||
|
|
||||||
Temporary extensions are removed when Firefox restarts. Reload the extension from `about:debugging` after changing its files.
|
Temporary extensions are removed when Firefox restarts. Reload the extension from `about:debugging` after changing its files.
|
||||||
|
|
||||||
@@ -160,14 +179,18 @@ cp .env.example .env
|
|||||||
|
|
||||||
Edit `.env` and replace `LINKLOG_SECRET_KEY` with a long random value. Docker Compose automatically reads `.env` from the repository root. The committed `.env.example` contains safe defaults and placeholders; the real `.env` is ignored by Git.
|
Edit `.env` and replace `LINKLOG_SECRET_KEY` with a long random value. Docker Compose automatically reads `.env` from the repository root. The committed `.env.example` contains safe defaults and placeholders; the real `.env` is ignored by Git.
|
||||||
|
|
||||||
|
When `APP_ENV=production`, application startup fails closed unless `LINKLOG_SECRET_KEY` is a non-default high-entropy value of at least 32 characters and `LINKLOG_DATA_ENCRYPTION_KEY` is a valid Fernet key. Development mode may use local defaults, but production secrets should come from a protected secret mechanism.
|
||||||
|
|
||||||
The main configurable values are:
|
The main configurable values are:
|
||||||
|
|
||||||
| Variable | Purpose | Default |
|
| Variable | Purpose | Default |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `LINKLOG_SECRET_KEY` | token signing/security secret | required in Docker |
|
| `LINKLOG_SECRET_KEY` | token signing/security secret | required in Docker |
|
||||||
|
| `LINKLOG_DATA_ENCRYPTION_KEY` | Fernet key for encrypting SMTP, Mastodon, and OTP secrets at rest | required in Docker |
|
||||||
| `LINKLOG_DATABASE_PATH` | SQLite file path inside the container | `/app/backend/data/linklog.db` |
|
| `LINKLOG_DATABASE_PATH` | SQLite file path inside the container | `/app/backend/data/linklog.db` |
|
||||||
| `LINKLOG_TOKEN_EXPIRY_DAYS` | access-token lifetime | `30` |
|
| `LINKLOG_TOKEN_EXPIRY_MINUTES` | access-token lifetime | `15` |
|
||||||
| `LINKLOG_PUBLIC_URL` | Public hostname used by Traefik and expanded to a callback URL by the backend | `localhost` |
|
| `LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS` | refresh-token lifetime | `30` |
|
||||||
|
| `LINKLOG_PUBLIC_URL` | Public hostname used by Traefik and expanded to a callback URL by the backend | `linklog.example.com` |
|
||||||
| `LINKLOG_SMTP_HOST` | SMTP server hostname; empty disables delivery in local development | empty |
|
| `LINKLOG_SMTP_HOST` | SMTP server hostname; empty disables delivery in local development | empty |
|
||||||
| `LINKLOG_SMTP_PORT` | SMTP server port | `587` |
|
| `LINKLOG_SMTP_PORT` | SMTP server port | `587` |
|
||||||
| `LINKLOG_SMTP_USERNAME` | SMTP login username | empty |
|
| `LINKLOG_SMTP_USERNAME` | SMTP login username | empty |
|
||||||
@@ -187,6 +210,8 @@ When a verified user enters the wrong password, LinkLog keeps the response gener
|
|||||||
|
|
||||||
The full set of supported variables is listed in `.env.example`. Application variables are passed into the container by Compose; Docker and Traefik variables are used by Compose itself.
|
The full set of supported variables is listed in `.env.example`. Application variables are passed into the container by Compose; Docker and Traefik variables are used by Compose itself.
|
||||||
|
|
||||||
|
`LINKLOG_DATA_ENCRYPTION_KEY` must be a Fernet key kept outside the database. Generate one with a Python environment that has `cryptography` installed, for example `python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"`, then store it in `.env` or a protected deployment secret. Losing this key makes encrypted SMTP, Mastodon, and OTP values unrecoverable. Existing plaintext values from earlier versions should be rotated by saving them again after configuring the key.
|
||||||
|
|
||||||
Build and start the application:
|
Build and start the application:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -226,6 +251,8 @@ After logging in, open <http://localhost:8000/profile>, enter the Mastodon insta
|
|||||||
|
|
||||||
LinkLog caches the OAuth application credentials per Mastodon server in the persistent SQLite `app_settings` table, so subsequent connections do not register a new application on every attempt. If the server rate-limits application registration, the profile page reports the upstream `429` response and the user can retry after the server's cooldown.
|
LinkLog caches the OAuth application credentials per Mastodon server in the persistent SQLite `app_settings` table, so subsequent connections do not register a new application on every attempt. If the server rate-limits application registration, the profile page reports the upstream `429` response and the user can retry after the server's cooldown.
|
||||||
|
|
||||||
|
Mastodon instances must be HTTPS hostname-only URLs that resolve to public IP addresses. Loopback, private, link-local, multicast, unspecified, reserved, and IPv4-mapped IPv6 destinations are rejected, and outbound redirects are refused.
|
||||||
|
|
||||||
Enable the plugin from the admin API or the admin page. New links are saved first and then posted to the configured instance at `/api/v1/statuses`. A Mastodon network failure does not undo the saved link.
|
Enable the plugin from the admin API or the admin page. New links are saved first and then posted to the configured instance at `/api/v1/statuses`. A Mastodon network failure does not undo the saved link.
|
||||||
|
|
||||||
## Useful API Calls
|
## Useful API Calls
|
||||||
@@ -238,6 +265,25 @@ curl -X POST http://localhost:8000/api/auth/login \\
|
|||||||
-d '{"email":"alice@example.com","password":"secret123"}'
|
-d '{"email":"alice@example.com","password":"secret123"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The login response contains a 15-minute access token, a device-bound refresh token, its expiry time, and a `device_id`. Each successful refresh rotates the refresh token.
|
||||||
|
|
||||||
|
Refresh an access token:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -X POST http://localhost:8000/api/auth/refresh \\
|
||||||
|
-H 'Content-Type: application/json' \\
|
||||||
|
-d '{"refresh_token":"YOUR_REFRESH_TOKEN","device_id":"YOUR_DEVICE_ID"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Refresh-token reuse or a mismatched device ID returns `401` and revokes the token family. Signing out revokes the token family, while changing the password or completing a password reset revokes all sessions for the user.
|
||||||
|
|
||||||
|
Sign out with the access token in the bearer header:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -X POST http://localhost:8000/api/auth/logout \\
|
||||||
|
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
|
||||||
|
```
|
||||||
|
|
||||||
Submit a link using the returned access token:
|
Submit a link using the returned access token:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
+105
-196
@@ -2,255 +2,164 @@
|
|||||||
|
|
||||||
**Assessment date:** 2026-08-26
|
**Assessment date:** 2026-08-26
|
||||||
**Scope:** Current LinkLog backend, web frontend, Firefox extension, SQLite persistence, SMTP and Mastodon integrations, Docker/Traefik deployment files, and automated tests.
|
**Scope:** Current LinkLog backend, web frontend, Firefox extension, SQLite persistence, SMTP and Mastodon integrations, Docker/Traefik deployment files, and automated tests.
|
||||||
**Assessment type:** Source-code security review. This is not a penetration test, dependency vulnerability scan, formal threat model sign-off, or production configuration certification.
|
**Assessment type:** Source-code review. This is not a penetration test, dependency scan, container scan, formal threat-model sign-off, or production configuration certification.
|
||||||
|
|
||||||
## Executive Summary
|
## Executive Summary
|
||||||
|
|
||||||
LinkLog has several good security foundations: authenticated API dependencies, administrator authorization checks, owner checks for link operations, token hashing in the database, email verification, password reset token hashing and single-use behavior, TOTP login enforcement, last-administrator protection, parameterized SQLite queries, upload size limits, and non-root application execution in the container.
|
The current worktree contains strong security improvements: salted scrypt password hashing with legacy upgrade support, bearer-header authentication, hashed and expiring tokens, refresh-token rotation with device binding and family revocation, OTP recovery codes, encrypted newly written secrets, Mastodon SSRF controls, image decoding and re-encoding, reduced extension permissions, proxy-only production Compose, and append-only audit events.
|
||||||
|
|
||||||
The current implementation is not ready to expose directly to the public Internet without additional hardening. The most important issues are:
|
The following issues remain before an Internet-facing production release:
|
||||||
|
|
||||||
1. Passwords were previously stored as unsalted, fast SHA-256 hashes; this issue has now been addressed in the current worktree with salted scrypt hashes and legacy upgrade support.
|
1. Logout still accepts a bearer token in a JSON body rather than using the standard `Authorization` header.
|
||||||
2. Access tokens are accepted in query strings by session endpoints, which can leak through logs, browser history, proxies, and referrers.
|
2. SMTP, Mastodon, setup, and some user-service errors return raw exception details to clients.
|
||||||
3. SMTP credentials, Mastodon credentials, OAuth client secrets, and TOTP secrets are stored in plaintext in SQLite.
|
3. First-run setup is intentionally unauthenticated and lacks a bootstrap secret and application-level request-size controls.
|
||||||
4. Mastodon instance URLs are user-controlled and the backend makes outbound requests to them, creating an SSRF and egress-control concern.
|
4. Audit event details are serialized without defensive sanitization or size limits at the audit-service boundary.
|
||||||
5. Login has no effective rate limiting or account lockout.
|
5. The development secret fallback is not rejected at application startup in production.
|
||||||
6. The Firefox extension stores bearer tokens in browser local storage and requests broad website access.
|
6. Rate limiting is single-instance SQLite state, is not atomic under concurrency, and reset-mail issuance is not independently throttled.
|
||||||
7. The Compose setup still exposes the application port directly and relies on deployment-specific Traefik networking and labels.
|
7. Runtime verification, security headers, centralized audit export, retention, alerting, and dependency/container/security scanning remain incomplete.
|
||||||
|
|
||||||
These findings are prioritized below. Severity describes the potential security impact in a typical Internet-facing deployment, not the likelihood in every environment.
|
The application should remain behind the production reverse proxy, with real DNS/TLS, protected secrets, and restricted network access until these items are addressed.
|
||||||
|
|
||||||
## Positive Controls Already Present
|
## Verified Controls
|
||||||
|
|
||||||
- Bearer authentication is centralized in `backend/app/api/dependencies.py`.
|
- Passwords use salted scrypt hashes; valid legacy SHA-256 hashes are upgraded on login.
|
||||||
- Administrator routes use `require_admin`; standard users receive `403`.
|
- Bearer authentication is centralized through `get_current_user` and `require_admin`.
|
||||||
- Link update, delete, and Mastodon-post operations verify ownership.
|
- Query-string authentication is not accepted by protected session endpoints.
|
||||||
- Tokens are generated with UUID material, stored as SHA-256 hashes, expire, and can be revoked.
|
- Access tokens are short-lived by default; refresh tokens are hashed, separately expiring, device-bound, rotated, and family-revoked on reuse.
|
||||||
- Password-reset tokens are random, hashed, expiring, single-use, and revoke existing sessions after reset.
|
- Logout, password changes, and password resets revoke session material according to the token lifecycle.
|
||||||
- New administrator-created users require email verification before login.
|
- OTP enrollment provides ten one-time recovery codes; only hashes are stored.
|
||||||
- OTP uses time-based verification with a one-step clock window and is required before token issuance when enabled.
|
- Users can recover OTP with password plus a recovery code, and administrators can disable OTP for another user.
|
||||||
- The profile API does not return `password_hash` or `otp_secret` after the profile response hardening.
|
- Newly written SMTP, Mastodon, OAuth, and OTP secrets are encrypted with an external Fernet key.
|
||||||
- User privilege changes protect against removing the last administrator and prevent an administrator from changing their own privilege.
|
- Mastodon instances are restricted to HTTPS public hostnames, unsafe resolved addresses are rejected, and redirects are blocked.
|
||||||
- Uploaded avatars have a 2 MB limit, a restricted MIME allow-list, user-scoped filenames, and a persistent data location.
|
- Avatar uploads are size-limited, decoded with Pillow, pixel-limited, fully loaded, and re-encoded as server-generated PNG.
|
||||||
- SQLite foreign keys are enabled and ownership predicates are used for destructive link operations.
|
- Production Compose does not publish the application port and uses the external Traefik network; local direct access is separate.
|
||||||
- SQL statements use parameters rather than interpolated user values.
|
- The Firefox extension uses `activeTab`, session-scoped credentials, exact configured backend permissions, and a self-only extension-page CSP.
|
||||||
- The Docker image runs the application as UID 10001 after startup and defines a health check.
|
- SQLite queries are parameterized and foreign-key enforcement is enabled.
|
||||||
- `.env` and database/runtime files are ignored by Git.
|
- An append-only `security_audit_events` table records actor, action, target, outcome, and details for major administrative and destructive operations.
|
||||||
- The XPI build validates archive integrity, required files, and manifest parity.
|
- The current automated backend suite passes 49 tests.
|
||||||
- Browser rendering generally uses `textContent` for feed data, reducing DOM-based injection risk.
|
|
||||||
|
|
||||||
## Findings
|
## Findings
|
||||||
|
|
||||||
### SA-001: Unsalted fast SHA-256 password hashing
|
### SA-001: Logout uses non-standard token transport
|
||||||
|
|
||||||
**Severity:** Critical, remediated in current worktree
|
**Severity:** High, remediated in current worktree
|
||||||
**Evidence before remediation:** `backend/app/database.py` and `backend/app/services/auth_service.py` used unsalted SHA-256 password comparisons.
|
**Evidence before remediation:** `POST /api/auth/logout` accepted `{"token": ...}` in the JSON request body, and the web frontend sent the access token this way.
|
||||||
**Current state:** `backend/app/database.py` now creates salted scrypt hashes in the format `scrypt$N$r$p$salt$digest`. `verify_password()` uses the encoded parameters and constant-time comparison. `authenticate_user()` fetches by username, verifies in Python, and transparently replaces a valid legacy 64-character SHA-256 hash with a new scrypt hash.
|
**Impact:** Request bodies may be captured by debugging middleware, application logs, or monitoring systems. The endpoint also diverges from the bearer-header contract used elsewhere, increasing the chance of inconsistent token handling.
|
||||||
**Residual impact:** Existing accounts remain exposed until they successfully authenticate once after deployment. An attacker with a copy of an old database may still attack legacy hashes. Existing credentials should be rotated if the old database may have been exposed.
|
|
||||||
|
|
||||||
**Recommendation:** Deploy the current migration, require password rotation for accounts that cannot log in during migration, and monitor for remaining legacy hashes. Review scrypt cost parameters periodically and increase them as hardware changes. Do not revert to a fast general-purpose hash.
|
**Current state:** Logout requires `Authorization: Bearer <access-token>`, rejects body-only tokens with `401`, and revokes the token family server-side. The web frontend and Firefox extension send the header; regression coverage verifies access and refresh tokens are invalid after logout.
|
||||||
|
|
||||||
**Priority:** Completed in code; operational migration and credential rotation remain.
|
**Recommendation:** Keep logout header-only, retain family revocation, avoid logging authorization headers, and rotate legacy sessions issued before this change.
|
||||||
|
|
||||||
### SA-002: Bearer tokens accepted in query strings
|
**Priority:** Completed in code; legacy session rotation and log hygiene remain.
|
||||||
|
|
||||||
**Severity:** High
|
### SA-002: Raw infrastructure errors are returned to clients
|
||||||
**Evidence:** `backend/app/api/auth.py` exposes `GET /api/auth/me?token=...`; the web frontend and Firefox extension use this form.
|
|
||||||
**Impact:** Query strings can be recorded by reverse-proxy access logs, browser history, monitoring systems, copied URLs, screenshots, and referrer headers. Anyone obtaining a token can use the bearer session until expiry or revocation. The token also identifies the user session because the token is the credential.
|
|
||||||
|
|
||||||
**Recommendation:** Make `Authorization: Bearer <token>` the only supported authentication transport for authenticated endpoints. Change the web and extension callers to send the header. If a compatibility transition is required, keep query-token support temporary, disable caching, add a deprecation period, and scrub query parameters from access logs. Consider rotating all existing tokens after migration.
|
**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.
|
||||||
|
|
||||||
**Priority:** High.
|
**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.
|
||||||
|
|
||||||
### SA-003: Sensitive secrets stored in plaintext SQLite
|
**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.
|
||||||
|
|
||||||
**Severity:** High
|
**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.
|
||||||
**Evidence:** `backend/app/services/email_service.py` stores SMTP settings including `smtp_password` in `app_settings`; `backend/app/services/mastodon_oauth.py` stores Mastodon application secrets and user access tokens in `app_settings` and `user_plugin_config`; `backend/app/api/user_config.py` stores `otp_secret` in the `users` table.
|
|
||||||
**Impact:** Read access to the database exposes SMTP credentials, Mastodon posting authority, OAuth client secrets, and TOTP seeds. TOTP seeds cannot be changed by a user who loses the database copy. Database backups therefore contain reusable credentials, not just application data.
|
|
||||||
|
|
||||||
**Recommendation:** Encrypt secrets at rest using an external secret-management system or an application encryption key held outside the database. At minimum, use a dedicated secret key supplied through a protected environment/secret file, encrypt sensitive values before SQLite storage, restrict file and volume permissions, and document backup key management. Rotate all credentials after a suspected database disclosure. Continue omitting secrets from API responses.
|
**Priority:** Completed in code; centralized logging and operational controls remain.
|
||||||
|
|
||||||
**Priority:** High.
|
### SA-003: First-run setup is unauthenticated and lacks application-level body limits
|
||||||
|
|
||||||
### SA-004: User-controlled Mastodon instance creates SSRF and uncontrolled egress risk
|
**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.
|
||||||
|
|
||||||
**Severity:** High
|
**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.
|
||||||
**Evidence:** `normalize_instance()` in `backend/app/services/mastodon_oauth.py` and the outbound requests in `backend/app/services/plugin_manager.py` accept an instance supplied by the user and call `urlopen()` against it.
|
|
||||||
**Impact:** A user can potentially configure an internal hostname, loopback address, cloud metadata endpoint, or other private network destination. The backend may send OAuth registration, token, status, or deletion requests to that destination. In addition to SSRF, this bypasses expected network egress policy and may disclose OAuth-related request data to an unintended host.
|
|
||||||
|
|
||||||
**Recommendation:** Validate Mastodon instances as HTTPS public hostnames. Resolve DNS and reject loopback, link-local, private, multicast, unspecified, and reserved IP ranges, including IPv4-mapped IPv6 addresses. Re-check after redirects and disable or strictly limit redirects. Prefer an outbound proxy with an allow-list and network egress policy. Set explicit URL and response-size limits and use a vetted HTTP client with safe redirect handling. Do not accept arbitrary schemes.
|
**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.
|
**Priority:** High for Internet-facing fresh installations.
|
||||||
|
|
||||||
### SA-005: Login endpoint lacks rate limiting and lockout
|
### SA-004: Audit details are not sanitized at the audit-service boundary
|
||||||
|
|
||||||
**Severity:** High
|
|
||||||
**Evidence:** `POST /api/auth/login` in `backend/app/api/auth.py` has no IP, username, or account rate limit. The OTP verification path is also not rate-limited separately.
|
|
||||||
**Impact:** Attackers can perform password guessing and OTP guessing at high speed. Sending a password-reset email after failed authentication can also be abused to generate mail volume and user harassment, even though the response remains generic.
|
|
||||||
|
|
||||||
**Recommendation:** Add a distributed rate limiter keyed by IP and normalized username, with conservative burst limits, exponential backoff, and monitoring. Rate-limit password-reset issuance independently and avoid sending reset mail for every failed attempt. Consider temporary account protection after repeated failures without creating a user-enumeration oracle. Return `Retry-After` where appropriate.
|
|
||||||
|
|
||||||
**Priority:** High.
|
|
||||||
|
|
||||||
### SA-006: Firefox extension has broad host access and stores bearer tokens in local storage
|
|
||||||
|
|
||||||
**Severity:** High
|
|
||||||
**Evidence:** `webextension/manifest.json` declares `host_permissions: ["<all_urls>"]`; `webextension/options.js` and `webextension/popup.js` store and retrieve `accessToken` through `browser.storage.local`.
|
|
||||||
**Impact:** A compromised extension context or another extension with sufficient access may obtain the bearer token. The broad host permission increases the impact of an extension compromise and requires elevated user trust. The token grants access until expiry or revocation.
|
|
||||||
|
|
||||||
**Recommendation:** Minimize permissions to the APIs actually needed. Prefer `activeTab` and explicit user interaction for page capture, and avoid `<all_urls>` unless required by a demonstrated workflow. Store session credentials in the narrowest available extension storage, minimize token lifetime, support refresh-token rotation, and clear all session material on logout or token invalidation. Add a Content Security Policy and review every extension script for dependency and injection risk.
|
|
||||||
|
|
||||||
**Priority:** High.
|
|
||||||
|
|
||||||
### SA-007: Production Compose configuration exposes the application directly
|
|
||||||
|
|
||||||
**Severity:** Medium/High
|
|
||||||
**Evidence:** `docker-compose.yml` publishes `${APP_PORT:-8000}:8000` while also configuring Traefik labels. The file uses an external `linklog_traefik` network and deployment-specific labels.
|
|
||||||
**Impact:** The application can bypass the reverse proxy and any TLS, authentication middleware, rate limiting, or security headers configured there. The default `LINKLOG_PUBLIC_URL=localhost` is also unsuitable for a public deployment. A network or label mismatch can silently expose an unprotected direct endpoint or make operators disable controls to restore access.
|
|
||||||
|
|
||||||
**Recommendation:** Split local development and production Compose files. In production, do not publish the application port to the host; attach it only to the reverse-proxy network. Ensure the app and Traefik share the same explicitly named network and validate the effective rendered configuration in CI. Require a non-local public hostname, TLS, security headers, request-size limits, and proxy-level rate limiting. Keep the direct port only in a documented local profile.
|
|
||||||
|
|
||||||
**Priority:** High for Internet-facing deployments.
|
|
||||||
|
|
||||||
### SA-008: Initial setup and SMTP validation are unauthenticated by design
|
|
||||||
|
|
||||||
**Severity:** Medium
|
**Severity:** Medium
|
||||||
**Evidence:** `backend/app/api/setup.py` exposes configuration, test-mail, status, and completion routes without a bearer dependency while no administrator exists.
|
**Evidence:** `record_audit_event()` serializes caller-supplied `details` directly to SQLite. Current callers generally avoid secrets, but the service does not enforce that contract or bound nested values and event size.
|
||||||
**Impact:** This is necessary for first-run provisioning, but an exposed fresh instance allows anyone who can reach it to attempt setup, modify pending configuration, trigger test mail, and consume the five-send testing quota. The setup pending data includes a password hash and SMTP password in the database.
|
|
||||||
|
|
||||||
**Recommendation:** Restrict first-run setup at the network layer until an operator has completed provisioning, or require a one-time bootstrap secret supplied through the environment/console. Bind setup to localhost or a private management interface where possible. Add CSRF protection if setup ever uses cookies, strict request throttling, audit logging, and an explicit setup expiration/cleanup mechanism. Disable setup routes permanently once configuration completes.
|
**Impact:** A future caller could persist passwords, tokens, OTP codes, SMTP credentials, sensitive URLs, or oversized data in the audit database. Audit records are durable and are not a suitable place for arbitrary request payloads.
|
||||||
|
|
||||||
**Priority:** Medium, high for exposed fresh deployments.
|
**Recommendation:** Use an allow-list of permitted detail fields per action, or recursively redact sensitive key names and URL query values. Bound string lengths and serialized event size. Add direct service tests with nested `password`, `token`, `secret`, and URL values and assert that they are redacted or rejected.
|
||||||
|
|
||||||
### SA-009: TOTP enrollment has no recovery codes or reset workflow
|
|
||||||
|
|
||||||
**Severity:** Medium
|
|
||||||
**Evidence:** `POST /api/user/otp/setup` returns the seed/provisioning URI and `POST /api/user/otp` requires a valid current OTP code to disable OTP.
|
|
||||||
**Impact:** A user who loses the authenticator device or seed can be locked out. Administrators have no documented recovery path that does not weaken authentication. Database readers can also use the plaintext seed as a second factor.
|
|
||||||
|
|
||||||
**Recommendation:** Generate one-time recovery codes during enrollment, display them once, hash them at rest, and invalidate each code on use. Require password reauthentication for disabling or replacing OTP. Add a controlled administrative recovery workflow with audit logging and notification. Avoid returning the seed after initial setup and never include it in profile responses.
|
|
||||||
|
|
||||||
**Priority:** Medium.
|
**Priority:** Medium.
|
||||||
|
|
||||||
### SA-010: Avatar validation trusts the client MIME type
|
### 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
|
**Severity:** Medium
|
||||||
**Evidence:** `upload_avatar()` in `backend/app/api/user_config.py` selects the extension from `UploadFile.content_type` and writes the bytes without decoding or inspecting the image.
|
**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:** A user can upload arbitrary content while labeling it as an image. Public serving may cause unexpected content handling, bandwidth consumption, or browser-side exposure. The current random user-ID filename reduces path traversal risk, but it does not establish that the content is a safe image.
|
|
||||||
|
|
||||||
**Recommendation:** Decode images with a hardened image library, enforce pixel and dimension limits, re-encode to a safe format, strip metadata, and serve with a fixed safe `Content-Type` and `X-Content-Type-Options: nosniff`. Consider a separate media origin and a stricter content security policy.
|
**Impact:** Browser defense-in-depth and resource exhaustion protections depend on external proxy configuration. A proxy configuration mistake can leave HTML, API, or media responses weaker than intended.
|
||||||
|
|
||||||
|
**Recommendation:** Add a documented application or guaranteed-proxy policy and test headers on HTML, API, and media responses. Use `TrustedHostMiddleware` with explicit production hosts, `nosniff`, restrictive framing/referrer rules, HSTS only on HTTPS, and bounded request bodies.
|
||||||
|
|
||||||
**Priority:** Medium.
|
**Priority:** Medium.
|
||||||
|
|
||||||
### SA-011: Error details can disclose infrastructure information
|
### SA-008: Audit operations lack request correlation, retention, export, and alerting
|
||||||
|
|
||||||
**Severity:** Medium
|
**Severity:** Medium
|
||||||
**Evidence:** Admin SMTP routes return exception text in `503` responses; Mastodon errors include upstream response bodies; the frontend displays these values to the user.
|
**Evidence:** Audit events contain actor/action/target/outcome/details/time but no request ID, source context, retention policy, protected export, or alerting pipeline.
|
||||||
**Impact:** Connection errors can disclose hostnames, ports, TLS details, library messages, upstream response bodies, or internal service information. The behavior is useful for administrators but may expose more detail than intended if an admin session is compromised or error responses are logged.
|
|
||||||
|
|
||||||
**Recommendation:** Log full technical details server-side with correlation IDs. Return a stable user-facing message plus a short reference ID. Allow detailed diagnostics only behind an explicit protected troubleshooting mode. Redact credentials, authorization headers, URLs containing secrets, and SMTP/Mastodon response fields before logging or returning them.
|
**Impact:** Operators can inspect database events but cannot reliably correlate them with request logs, detect attacks promptly, or guarantee retention and tamper-resistant access controls.
|
||||||
|
|
||||||
|
**Recommendation:** Add request IDs at middleware entry, export redacted events to protected logs or a security monitoring system, define retention and access controls, and alert on privilege changes, OTP resets, password resets, credential changes, refresh-token reuse, and destructive actions.
|
||||||
|
|
||||||
**Priority:** Medium.
|
**Priority:** Medium.
|
||||||
|
|
||||||
### SA-012: Token lifecycle has unused refresh-token semantics
|
### SA-009: Dependency, container, secret, and runtime security verification is incomplete
|
||||||
|
|
||||||
**Severity:** Medium
|
**Severity:** Medium
|
||||||
**Evidence:** `issue_token()` returns a `refresh_token` value, but only the access token is inserted into `tokens`; no refresh endpoint or refresh-token hash is implemented.
|
**Evidence:** 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:** Clients may assume the refresh token provides renewal or may store a value that cannot be revoked or used. This complicates session reasoning and can lead to unsafe client fallbacks. Access tokens currently live for the configured default of 30 days.
|
|
||||||
|
|
||||||
**Recommendation:** Either remove `refresh_token` from the API contract or implement a real refresh-token lifecycle: hash and persist refresh tokens, rotate them on use, detect reuse, bind them to a session/device, expire them separately, and revoke the token family on logout or password change. Reduce access-token lifetime after a real refresh flow is available.
|
**Impact:** Known vulnerable dependencies, image issues, accidental secret commits, proxy misconfiguration, and browser-runtime permission failures can reach release despite passing unit tests.
|
||||||
|
|
||||||
**Priority:** Medium.
|
**Recommendation:** Add CI jobs for Python dependency and license policy, container scanning, secret scanning, Compose rendering, authenticated dynamic API checks, and a Firefox smoke test covering permission grant, login, refresh, logout, and active-tab capture.
|
||||||
|
|
||||||
### SA-013: No explicit security headers, CORS policy, or request-size policy
|
**Priority:** Medium before public release.
|
||||||
|
|
||||||
**Severity:** Medium
|
## Residual Operational Requirements
|
||||||
**Evidence:** `backend/app/main.py` does not install security-header or CORS middleware, and the application routes do not define a global request-size limit.
|
|
||||||
**Impact:** Deployment behavior depends entirely on the reverse proxy. Missing `Content-Security-Policy`, `Strict-Transport-Security`, `X-Content-Type-Options`, `Referrer-Policy`, and frame protections weakens browser-side defenses. An overly permissive future CORS configuration could expose bearer-authenticated APIs. Large request bodies may consume resources even where individual avatar limits exist.
|
|
||||||
|
|
||||||
**Recommendation:** Add a documented restrictive security-header policy at the application or guaranteed proxy layer. Use `TrustedHostMiddleware` with an explicit production host list. Do not enable broad CORS; if cross-origin extension access requires it, allow only configured origins. Add global request and upload limits at the proxy and application layers.
|
- Replace documentation hostnames with real DNS names and enforce HTTPS/TLS.
|
||||||
|
- Keep production Compose proxy-only and verify the actual Traefik network and middleware in deployment.
|
||||||
**Priority:** Medium.
|
- Rotate legacy plaintext secrets and previously issued sessions after upgrades.
|
||||||
|
- Protect and encrypt database/avatar backups; test restoration and token/session revocation.
|
||||||
### SA-014: Development fallback secret is unsafe if the app is run without Compose configuration
|
- Monitor failed logins, reset-mail volume, refresh-token reuse, OTP recovery, privilege changes, and destructive actions.
|
||||||
|
- Review the Firefox extension against Mozilla Add-ons policy before signing.
|
||||||
**Severity:** Medium
|
|
||||||
**Evidence:** `Settings.secret_key` in `backend/app/core/config.py` defaults to `dev-secret-key-change-me`.
|
|
||||||
**Impact:** Local or incorrectly configured deployments can share a known secret. Even if the current token implementation does not use this value for signing, the setting creates a dangerous security assumption and may be used by future features.
|
|
||||||
|
|
||||||
**Recommendation:** Fail closed when `APP_ENV=production` and the secret is absent or matches a known development value. Generate secrets during provisioning, validate minimum length and entropy, and never ship a production fallback. Make all cryptographic uses explicit and test them.
|
|
||||||
|
|
||||||
**Priority:** Medium.
|
|
||||||
|
|
||||||
### SA-015: Some destructive and administrative operations lack audit logging
|
|
||||||
|
|
||||||
**Severity:** Low/Medium
|
|
||||||
**Evidence:** User creation/deletion, privilege changes, SMTP changes, theme changes, OTP enrollment/disablement, link deletion, and Mastodon deletion do not create durable security audit events.
|
|
||||||
**Impact:** Operators cannot reliably determine who changed privileges, modified delivery credentials, enrolled OTP, or deleted local/remote content. This limits incident response and accountability.
|
|
||||||
|
|
||||||
**Recommendation:** Add append-only audit events containing actor ID, action, target type/ID, timestamp, request ID, and outcome. Never store passwords, OTP codes, access tokens, SMTP passwords, or full sensitive request bodies. Export security events to protected logs.
|
|
||||||
|
|
||||||
**Priority:** Low/Medium.
|
|
||||||
|
|
||||||
## Authentication and Authorization Review
|
|
||||||
|
|
||||||
- **Authentication transport:** Bearer headers are used by most APIs, but query-string tokens remain a leakage risk. There is no cookie session, which reduces CSRF exposure for current bearer-only API calls. Credentials are now email-based; usernames remain presentation identities.
|
|
||||||
- **Password policy:** New and reset passwords require at least eight characters. This is better than no policy but should be replaced with a longer passphrase-oriented policy and breached-password screening after a proper password hash migration.
|
|
||||||
- **Email verification:** New administrator-created users cannot log in until verified. The setup-created first administrator is marked verified, which is appropriate for bootstrap but should be protected by the setup controls above.
|
|
||||||
- **Password reset:** Tokens are random, hashed, expiring, single-use, and revoke existing access tokens after reset. Reset-email generation errors are intentionally swallowed to preserve generic login behavior, but this should be paired with server-side monitoring.
|
|
||||||
- **OTP:** Login enforcement is present and OTP setup requires confirmation. Recovery codes, secret rotation, reauthentication, and encrypted secret storage are missing.
|
|
||||||
- **Authorization:** Admin checks and link ownership checks are present. The last-administrator invariant is enforced for privilege changes and deletion. Add authorization tests for every new destructive endpoint as the API grows.
|
|
||||||
|
|
||||||
## Data Protection Review
|
|
||||||
|
|
||||||
- SQLite is the primary data store and contains profile data, links, password hashes, tokens, SMTP settings, Mastodon credentials, OAuth state, and OTP secrets.
|
|
||||||
- Database backups must be treated as credential-bearing secrets, encrypted, access-controlled, rotated, and tested for secure deletion.
|
|
||||||
- Avatar files are persistent and publicly served. Validate and re-encode image content before accepting production uploads.
|
|
||||||
- Link URLs and comments are intentionally public feed data. Operators should document that users must not submit secrets in URLs or comments.
|
|
||||||
- SMTP and Mastodon integration errors should be redacted before entering logs or API responses.
|
|
||||||
|
|
||||||
## Frontend and Extension Review
|
|
||||||
|
|
||||||
- Feed content is generally assigned with `textContent`, which is a good XSS defense.
|
|
||||||
- User-supplied profile values rendered by Jinja should remain autoescaped; do not mark them safe without a narrowly reviewed reason.
|
|
||||||
- The web API currently uses bearer headers, so browser CSRF risk is lower than with cookie sessions. Keep it that way unless a CSRF token design is added.
|
|
||||||
- Browser local storage is exposed to any script running in the same origin. Keep third-party scripts out of authenticated pages and add a restrictive CSP.
|
|
||||||
- The extension's `<all_urls>` host permission should be reduced if the active-tab workflow is sufficient. Review Mozilla Add-ons policies before publishing signed releases.
|
|
||||||
- The extension stores access and refresh-token-like values in `browser.storage.local`; implement actual refresh semantics or stop storing/returning unused refresh values.
|
|
||||||
- Extension error messages should not include tokens or full sensitive URLs.
|
|
||||||
|
|
||||||
## Deployment Checklist
|
|
||||||
|
|
||||||
Before production exposure:
|
|
||||||
|
|
||||||
- [ ] Replace SHA-256 password hashing with Argon2id, scrypt, or bcrypt and migrate existing accounts.
|
|
||||||
- [ ] Remove query-string token authentication and rotate existing access tokens.
|
|
||||||
- [ ] Encrypt SMTP, Mastodon, OAuth, and OTP secrets at rest; protect encryption keys separately.
|
|
||||||
- [ ] Add login, OTP, reset-mail, and setup rate limiting.
|
|
||||||
- [ ] Restrict Mastodon instance validation and outbound network egress.
|
|
||||||
- [ ] Disable direct host publication of the application port in production.
|
|
||||||
- [ ] Configure HTTPS, HSTS, CSP, Referrer-Policy, frame protections, `nosniff`, and trusted hosts.
|
|
||||||
- [ ] Define a restrictive CORS policy or leave CORS disabled.
|
|
||||||
- [ ] Add global request-size limits and hardened image decoding/re-encoding.
|
|
||||||
- [ ] Add OTP recovery codes and a protected recovery workflow.
|
|
||||||
- [ ] Remove or implement refresh-token behavior.
|
|
||||||
- [ ] Add security audit events and centralized redacted logging.
|
|
||||||
- [ ] Rotate all credentials and set a unique high-entropy production secret.
|
|
||||||
- [ ] Review extension permissions and submit the XPI only after Mozilla policy review.
|
|
||||||
- [ ] Encrypt and restrict database/avatar backups, and test restore and revocation procedures.
|
|
||||||
- [ ] Run a dependency vulnerability scan and a dynamic penetration test against a production-like deployment.
|
|
||||||
|
|
||||||
## Suggested Priority Order
|
|
||||||
|
|
||||||
1. Password hashing migration.
|
|
||||||
2. Query-token removal and token rotation.
|
|
||||||
3. Secret-at-rest protection and backup controls.
|
|
||||||
4. Login/setup/OTP rate limiting.
|
|
||||||
5. Mastodon SSRF and egress restrictions.
|
|
||||||
6. Production network and TLS hardening.
|
|
||||||
7. Extension permission and credential-storage review.
|
|
||||||
8. Security headers, trusted hosts, request limits, media validation, recovery codes, and audit logging.
|
|
||||||
|
|
||||||
## Verification Performed
|
## Verification Performed
|
||||||
|
|
||||||
The repository's automated backend suite was run during this review and passed with 29 tests before the password-storage change; focused password/authentication tests subsequently passed after the remediation. Static Python and JavaScript checks were also used during feature development. These results demonstrate regression coverage, not absence of the findings above. A production release should additionally run a dependency scanner, container scanner, secret scanner, and authenticated dynamic security test.
|
- `PYTHONPATH=. pytest -q`: **49 passed** at the start of this audit.
|
||||||
|
- Static source review of backend APIs/services, frontend assets, extension manifest/scripts, Compose files, configuration, and tests.
|
||||||
|
- Targeted searches for authentication, token, secret, upload, outbound-request, error, and audit-log paths.
|
||||||
|
|
||||||
|
Functional tests demonstrate regression coverage only; they do not certify production security.
|
||||||
|
|||||||
@@ -1,5 +1,167 @@
|
|||||||
# Chat Log
|
# Chat Log
|
||||||
|
|
||||||
|
### User
|
||||||
|
The release server fails because its curl does not support `--fail-with-body`.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Replaced all three `--fail-with-body` uses in the release workflow with portable curl response capture and explicit HTTP status checks. Failed API and asset-upload responses now print their response body before exiting, while older curl versions remain supported.
|
||||||
|
|
||||||
|
### User
|
||||||
|
When posting to Mastodon change the formatting so there is an empty line between “From my #LinkLog:” and the title.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated the Mastodon formatter so the prefix and title are separate paragraphs: `From my #LinkLog:` followed by a blank line and then the title. Existing comment, source URL, and tag paragraph formatting remains unchanged.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Check the modified pages for the correct link because a version number was added to the signed XPI.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Verified that the signed artifact is `XPI/signed/LinkLog-0.1.0.xpi` and that the About page, Profile page, `webextension/updates.json`, README, and related regression test all reference the matching versioned filename. No changes were required.
|
||||||
|
|
||||||
|
### User
|
||||||
|
In the Profile page below the Save profile button add “If you have not downloaded the plugin yet find it here” with a link to the signed plugin.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added the plugin download prompt immediately below the Save profile button, linking “find it here” to the signed `LinkLog-0.1.0.xpi` artifact. Added profile-page regression assertions and recorded the change in VIBE.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Add a Plugin section to the About page with a download link to the signed XPI file.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added a Plugin section to the About page with a download link for the signed `LinkLog-0.1.0.xpi` artifact hosted on the repository's raw main branch. Added a page-rendering regression assertion.
|
||||||
|
|
||||||
|
### User
|
||||||
|
The Firefox plugin tests report that `strict_min_version` 112 is too low for `data_collection_permissions`, `storage.session`, and `permissions.request`.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Raised the extension minimum Firefox version to 142.0, covering the reported desktop and Android manifest/API compatibility warnings. Updated the README to require Firefox 142 or newer.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Implement SA-005: during startup reject missing or known development `LINKLOG_SECRET_KEY` in production, validate minimum length and entropy, require and validate the encryption key, and add fail-closed configuration tests.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added startup configuration validation before FastAPI app construction. Production now rejects missing/default/weak application secrets and missing or invalid Fernet encryption keys, while development defaults remain available. Added configuration tests for rejection and valid production settings, and updated SA-005 documentation.
|
||||||
|
|
||||||
|
### User
|
||||||
|
For SA-002, log technical details server-side with a request/correlation ID, return a stable public message with a short reference ID, redact secrets, and test that exception text is absent from responses.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Added request-ID middleware and stable public error references. SMTP, setup, email-verification, and Mastodon exception paths now log redacted technical summaries server-side without exposing raw exception text, credentials, authorization values, reset tokens, OTP data, or secret-bearing URL values. Added regression coverage and updated SA-002 documentation.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Remedy SA-001: Logout uses non-standard token transport.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Migrated logout to require `Authorization: Bearer <access-token>`, updated the web frontend and Firefox extension, and added regression coverage proving body-only logout is rejected while header logout revokes the access token and refresh-token family. Updated SA-001, the checklist, and README examples.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Perform a new security audit overwriting Security-audit.md with new and remaining issues.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Replaced the historical audit with a fresh current-state review dated 2026-08-26. The new report records verified controls and nine remaining findings: logout token transport, raw infrastructure errors, unauthenticated setup exposure, audit-detail sanitization, production secret fallback, non-distributed rate limiting, incomplete security headers/request policy, missing audit operations, and incomplete dependency/container/secret/runtime verification. The baseline backend suite passed 49 tests.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Update SA-012 to reflect the actual implementation, document device binding, rotation, reuse detection, family revocation, logout and password-reset revocation, update the checklist and README API examples, and add the refresh endpoint to the documented API surface.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Reconciled SA-012 and the authentication documentation with the implemented 15-minute access tokens and 30-day device-bound refresh tokens. Documented hashing, rotation, reuse-triggered family revocation, logout and password-reset revocation, added the refresh endpoint and curl example to the README, corrected extension login instructions, and checked off the refresh-token implementation item.
|
||||||
|
|
||||||
|
### User
|
||||||
|
Replace `LINKLOG_TOKEN_EXPIRY_DAYS` with `LINKLOG_TOKEN_EXPIRY_MINUTES`, add `LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS` to the production Compose environment, and add a CI test comparing Compose variables with Settings.
|
||||||
|
|
||||||
|
### Assistant outcome
|
||||||
|
Updated production Compose to pass the configured 15-minute access-token and 30-day refresh-token settings. Added a repository test that compares `LINKLOG_*` Compose keys with the environment keys declared by `Settings` and rejects the obsolete days-based access-token variable.
|
||||||
|
|
||||||
|
### User
|
||||||
|
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
|
## 2026-08-24
|
||||||
|
|
||||||
### User
|
### User
|
||||||
@@ -849,6 +1011,36 @@ Change the title of the field “One-time password” to “One-time password (w
|
|||||||
### Assistant outcome
|
### 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.
|
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
|
### User
|
||||||
For the new password in the user setting add a validation field to make sure they are the same before submitting.
|
For the new password in the user setting add a validation field to make sure they are the same before submitting.
|
||||||
|
|
||||||
@@ -878,3 +1070,135 @@ The login page should ask for OTP password.
|
|||||||
|
|
||||||
### Assistant outcome
|
### 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.
|
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.
|
||||||
|
|||||||
+125
-70
@@ -87,76 +87,131 @@
|
|||||||
83. Add a copyright statement to source files refer to GNU license
|
83. Add a copyright statement to source files refer to GNU license
|
||||||
84. Add the version to the name of the resulting xpi
|
84. Add the version to the name of the resulting xpi
|
||||||
85. Set the version number of the backend to 0.1.0
|
85. Set the version number of the backend to 0.1.0
|
||||||
84. Add the creation of an xpi bundle for the webextention to the Makefile
|
86. Add the creation of an xpi bundle for the webextention to the Makefile
|
||||||
85. Correct: A signed XPI will be generated manually and checked into the repository under XPI/signed
|
87. Correct: A signed XPI will be generated manually and checked into the repository under XPI/signed
|
||||||
86. The "data_collection_permissions" property is missing from the plugin
|
88. The "data_collection_permissions" property is missing from the plugin
|
||||||
87. Validate the XPI during the make process of the unsigned xpi
|
89. Validate the XPI during the make process of the unsigned xpi
|
||||||
88. pressing remove still does not remove a user.
|
90. pressing remove still does not remove a user.
|
||||||
89. Trying to remove user alice: Could not remove alice: Internal Server Error
|
91. Trying to remove user alice: Could not remove alice: Internal Server Error
|
||||||
90. create a gitea action that is ran every time main is updated and that creates a docker image tagged development
|
92. create a gitea action that is ran every time main is updated and that creates a docker image tagged development
|
||||||
91. Use an access token to publish to registry, not username and password
|
93. Use an access token to publish to registry, not username and password
|
||||||
92. Add SMTP capabilities to the backend. Use it to validate the email addresses using a validation link in mail
|
94. Add SMTP capabilities to the backend. Use it to validate the email addresses using a validation link in mail
|
||||||
93. Do not configure default users at bootstrap. Instead present a configuration page (only present if no administrator is configured). The configuration page asks for the admin users credetials and allows to configure the SMTP settings and sends a test mail after configuration
|
95. Do not configure default users at bootstrap. Instead present a configuration page (only present if no administrator is configured). The configuration page asks for the admin users credetials and allows to configure the SMTP settings and sends a test mail after configuration
|
||||||
94. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent."
|
96. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent."
|
||||||
95. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down.
|
97. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down.
|
||||||
96. when running the initial config use the defaults from the .env file when available
|
98. when running the initial config use the defaults from the .env file when available
|
||||||
97. Use oauth to register with the mastodon account and obtain access to post
|
99. Use oauth to register with the mastodon account and obtain access to post
|
||||||
98. Allow user to enter the mastodon server to authenticate to
|
100. Allow user to enter the mastodon server to authenticate to
|
||||||
99. Clicking authenticate with this server (social.secret-wg.org) generates 502 error
|
101. Clicking authenticate with this server (social.secret-wg.org) generates 502 error
|
||||||
100. Log the unlogged chat and promt in the VIBE directory
|
102. Log the unlogged chat and promt in the VIBE directory
|
||||||
101. when password is mistyped send a password reset link
|
103. when password is mistyped send a password reset link
|
||||||
102. when running the initial config use the defaults from the .env file when available
|
104. when running the initial config use the defaults from the .env file when available
|
||||||
103. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent."
|
105. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent."
|
||||||
104. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down.
|
106. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down.
|
||||||
105. Use oauth to register with the mastodon account and obtain access to post
|
107. Use oauth to register with the mastodon account and obtain access to post
|
||||||
106. Allow user to enter the mastodon server to authenticate to
|
108. Allow user to enter the mastodon server to authenticate to
|
||||||
107. Log the unlogged chat and promt in the VIBE directory
|
109. Log the unlogged chat and promt in the VIBE directory
|
||||||
108. Continue to log prompts and chats in VIBE
|
110. Continue to log prompts and chats in VIBE
|
||||||
109. use VIVE that is in the current directory
|
111. use VIVE that is in the current directory
|
||||||
110. Posting to mastodon seems to fail, try to fix, add debug logging
|
112. Posting to mastodon seems to fail, try to fix, add debug logging
|
||||||
111. LINKLOG_PUBLIC_URL and TRAEFIK_HOST are the same and can be merged. (use LINKLOG_PUBLIC_URL), fix docker-compose to use said variable
|
113. LINKLOG_PUBLIC_URL and TRAEFIK_HOST are the same and can be merged. (use LINKLOG_PUBLIC_URL), fix docker-compose to use said variable
|
||||||
112. Format mastodon posts like From my #LinkLog: Title, optional comment, and from: URL
|
114. Format mastodon posts like From my #LinkLog: Title, optional comment, and from: URL
|
||||||
113. 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.
|
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.
|
||||||
114. 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.
|
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.
|
||||||
115. Put the buttons on the right hand side of the link item, make the buttons smaller and same color scheme
|
117. Put the buttons on the right hand side of the link item, make the buttons smaller and same color scheme
|
||||||
116. Put the mastodon button on the lower right corner of the log entry
|
118. Put the mastodon button on the lower right corner of the log entry
|
||||||
117. Make sure that the makefile also rebuilds XPI if any of its source files are changed
|
119. Make sure that the makefile also rebuilds XPI if any of its source files are changed
|
||||||
117. Change that location to be immediately below the edit and delete button
|
120. Change that location to be immediately below the edit and delete button
|
||||||
116. 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.
|
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.
|
||||||
117. Continue to log interactions to the VIBE directory.
|
122. Continue to log interactions to the VIBE directory.
|
||||||
118. On the home page, when clicking on the avatar or the user, show the profile information.
|
123. On the home page, when clicking on the avatar or the user, show the profile information.
|
||||||
119. Localize the firefox plugin.
|
124. Localize the firefox plugin.
|
||||||
120. Create a spanish, german, french and dutch locale.
|
125. Create a spanish, german, french and dutch locale.
|
||||||
121. On the admin page add the SMTP settings (with the validation button).
|
126. On the admin page add the SMTP settings (with the validation button).
|
||||||
122. 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.
|
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.
|
||||||
123. Report any errors that may occur from the SMTP module to the user.
|
128. Report any errors that may occur from the SMTP module to the user.
|
||||||
124. 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.
|
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.
|
||||||
125. For the day and latte themes the contrast on the link items is too low.
|
130. For the day and latte themes the contrast on the link items is too low.
|
||||||
126. Add 3 other of the most popular themes.
|
131. Add 3 other of the most popular themes.
|
||||||
127. Show the tags in the linklog on the bottom left, move the date to the bottom right - horizontally align the tags with the date.
|
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.
|
||||||
128. Continue todos.
|
133. Continue todos.
|
||||||
129. Do not show 'no comment provided' but leave empty when no comment has been provided.
|
134. Do not show 'no comment provided' but leave empty when no comment has been provided.
|
||||||
130. Decrease the space between link-log items.
|
135. Decrease the space between link-log items.
|
||||||
131. Perform the next items on the todo list.
|
136. Perform the next items on the todo list.
|
||||||
132. Correct: move the sort and filter toolbar underneath the theme and menu, in the header, on the home page and on the <user> pages.
|
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.
|
||||||
133. Run frontend and style checks.
|
138. Run frontend and style checks.
|
||||||
134. Keep the sort and filter bar left of the logo and pack it snug against the menu and theme selector.
|
139. Keep the sort and filter bar left of the logo and pack it snug against the menu and theme selector.
|
||||||
135. 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.
|
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.
|
||||||
136. When a log entry is deleted then all mastodon posts are deleted too.
|
141. When a log entry is deleted then all mastodon posts are deleted too.
|
||||||
137. Don't forget to update the plugin to work with OTP.
|
142. Don't forget to update the plugin to work with OTP.
|
||||||
138. 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.
|
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.
|
||||||
139. Remove DEFAULT_BACKEND setting in the plugin.
|
144. Remove DEFAULT_BACKEND setting in the plugin.
|
||||||
140. Change the title of the field "One-time password" to "One-time password (when configured)".
|
145. Change the title of the field "One-time password" to "One-time password (when configured)".
|
||||||
141. Remove any leading and trailing spaces when entering fields in the settings page of the plugin.
|
146. The plugin settings still show 'emailLabel'; make that 'email' as title for the email field.
|
||||||
142. Do a full security audit document in what you have done in detail in Security-audit.md
|
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.
|
||||||
143. Address issue 1. and improve password storage
|
148. Display any errors that occur during posting.
|
||||||
144. The login page should ask for OTP password
|
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."
|
||||||
145. For the new password in the user setting add a validation field to make sure they are the same before submitting
|
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
|
||||||
146. Change so that authentication is based on email address rather than username - maintain the username for presentation purposes
|
151. Remove any leading and trailing spaces when entering fields in the settings page of the plugin.
|
||||||
147. Make sure the web plugin follows same logic
|
152. Do a full security audit document in what you have done in detail in Security-audit.md
|
||||||
146. Change so that authentication is based on email address rather than username - maintain the username for presentation purposes
|
153. Address issue 1. and improve password storage
|
||||||
147. Make sure the web plugin follows same logic
|
154. The login page should ask for OTP password
|
||||||
148. In the plugin <span data-i18n="emailLabel">emailLabel</span> should read: <span data-i18n="emailLabel">Email</span>
|
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
|
## Future entries
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
@@ -5,7 +5,7 @@ import json
|
|||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from backend.app.api.dependencies import require_admin
|
from backend.app.api.dependencies import require_admin
|
||||||
@@ -20,9 +20,14 @@ from backend.app.services.email_service import (
|
|||||||
)
|
)
|
||||||
from backend.app.services.email_verification import create_verification_token
|
from backend.app.services.email_verification import create_verification_token
|
||||||
from backend.app.services.theme_service import THEMES, get_enabled_themes, save_enabled_themes
|
from backend.app.services.theme_service import THEMES, get_enabled_themes, save_enabled_themes
|
||||||
|
from backend.app.services.secret_store import encrypt_secret
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings
|
||||||
|
from backend.app.services.audit_service import record_audit_event
|
||||||
|
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||||
|
import logging
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class AdminPluginUpdate(BaseModel):
|
class AdminPluginUpdate(BaseModel):
|
||||||
@@ -93,8 +98,24 @@ def list_users(_: dict = Depends(require_admin)):
|
|||||||
return [public_user(row) for row in rows]
|
return [public_user(row) for row in rows]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/users/{user_id}/otp/reset')
|
||||||
|
def reset_user_otp(user_id: str, current_user: dict = Depends(require_admin)):
|
||||||
|
with get_connection() as conn:
|
||||||
|
target = conn.execute('SELECT id FROM users WHERE id = ?', (user_id,)).fetchone()
|
||||||
|
if target is None:
|
||||||
|
raise HTTPException(status_code=404, detail='User not found')
|
||||||
|
conn.execute(
|
||||||
|
'UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||||
|
(user_id,),
|
||||||
|
)
|
||||||
|
conn.execute('DELETE FROM otp_recovery_codes WHERE user_id = ?', (user_id,))
|
||||||
|
conn.commit()
|
||||||
|
record_audit_event(current_user['id'], 'otp_reset', 'user', user_id)
|
||||||
|
return {'status': 'otp_reset', 'enabled': False, 'user_id': user_id}
|
||||||
|
|
||||||
|
|
||||||
@router.post('/users', status_code=201)
|
@router.post('/users', status_code=201)
|
||||||
def create_user(payload: AdminUserCreate, _: dict = Depends(require_admin)):
|
def create_user(payload: AdminUserCreate, request: Request, current_user: dict = Depends(require_admin)):
|
||||||
username = payload.username.strip()
|
username = payload.username.strip()
|
||||||
email = payload.email.strip()
|
email = payload.email.strip()
|
||||||
if not username or not email or len(payload.password) < 8:
|
if not username or not email or len(payload.password) < 8:
|
||||||
@@ -124,7 +145,9 @@ def create_user(payload: AdminUserCreate, _: dict = Depends(require_admin)):
|
|||||||
try:
|
try:
|
||||||
send_verification_email(row['email'], row['username'], verification_url)
|
send_verification_email(row['email'], row['username'], verification_url)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
raise HTTPException(status_code=503, detail=f'User created but verification email could not be sent: {error}') from error
|
logger.error('User verification email failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'User created but verification email could not be sent.')) from error
|
||||||
|
record_audit_event(current_user['id'], 'user_created', 'user', row['id'], details={'is_admin': bool(payload.is_admin)})
|
||||||
return public_user(row)
|
return public_user(row)
|
||||||
|
|
||||||
|
|
||||||
@@ -150,24 +173,26 @@ def get_admin_themes(_: dict = Depends(require_admin)):
|
|||||||
|
|
||||||
|
|
||||||
@router.put('/themes')
|
@router.put('/themes')
|
||||||
def update_admin_themes(payload: AdminThemesUpdate, _: dict = Depends(require_admin)):
|
def update_admin_themes(payload: AdminThemesUpdate, current_user: dict = Depends(require_admin)):
|
||||||
try:
|
try:
|
||||||
enabled = save_enabled_themes(payload.themes)
|
enabled = save_enabled_themes(payload.themes)
|
||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
raise HTTPException(status_code=422, detail=str(error)) from error
|
raise HTTPException(status_code=422, detail=str(error)) from error
|
||||||
|
record_audit_event(current_user['id'], 'themes_updated', 'application', details={'themes': enabled})
|
||||||
return {'themes': THEMES, 'enabled': enabled}
|
return {'themes': THEMES, 'enabled': enabled}
|
||||||
|
|
||||||
|
|
||||||
@router.put('/smtp')
|
@router.put('/smtp')
|
||||||
def update_admin_smtp_settings(payload: AdminSmtpUpdate, _: dict = Depends(require_admin)):
|
def update_admin_smtp_settings(payload: AdminSmtpUpdate, current_user: dict = Depends(require_admin)):
|
||||||
current = get_smtp_settings()
|
current = get_smtp_settings()
|
||||||
values = validate_smtp_values(payload, current)
|
values = validate_smtp_values(payload, current)
|
||||||
save_smtp_settings(values)
|
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)
|
return public_smtp_settings(values)
|
||||||
|
|
||||||
|
|
||||||
@router.post('/smtp/test')
|
@router.post('/smtp/test')
|
||||||
def validate_admin_smtp(payload: AdminSmtpUpdate, current_user: dict = Depends(require_admin)):
|
def validate_admin_smtp(payload: AdminSmtpUpdate, request: Request, current_user: dict = Depends(require_admin)):
|
||||||
values = validate_smtp_values(payload, get_smtp_settings())
|
values = validate_smtp_values(payload, get_smtp_settings())
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
@@ -188,7 +213,8 @@ def validate_admin_smtp(payload: AdminSmtpUpdate, current_user: dict = Depends(r
|
|||||||
try:
|
try:
|
||||||
send_test_email(current_user['email'], values)
|
send_test_email(current_user['email'], values)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
raise HTTPException(status_code=503, detail=f'SMTP validation failed: {error}') from error
|
logger.error('SMTP validation failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'SMTP validation failed.')) from error
|
||||||
sends = int(rate.get('sends', 0)) + 1
|
sends = int(rate.get('sends', 0)) + 1
|
||||||
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
|
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
|
||||||
if sends >= 5:
|
if sends >= 5:
|
||||||
@@ -243,6 +269,7 @@ def update_user_privileges(
|
|||||||
'SELECT id, username, email, is_admin, avatar_url, bio, created_at, email_verified FROM users WHERE id = ?',
|
'SELECT id, username, email, is_admin, avatar_url, bio, created_at, email_verified FROM users WHERE id = ?',
|
||||||
(user_id,),
|
(user_id,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
|
record_audit_event(current_user['id'], 'user_privileges_updated', 'user', user_id, details={'is_admin': bool(payload.is_admin)})
|
||||||
return public_user(row)
|
return public_user(row)
|
||||||
|
|
||||||
|
|
||||||
@@ -265,13 +292,15 @@ def delete_user(user_id: str, current_user: dict = Depends(require_admin)):
|
|||||||
conn.execute('DELETE FROM links WHERE user_id = ?', (user_id,))
|
conn.execute('DELETE FROM links WHERE user_id = ?', (user_id,))
|
||||||
conn.execute('DELETE FROM users WHERE id = ?', (user_id,))
|
conn.execute('DELETE FROM users WHERE id = ?', (user_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
record_audit_event(current_user['id'], 'user_deleted', 'user', user_id)
|
||||||
return {'status': 'deleted', 'id': user_id}
|
return {'status': 'deleted', 'id': user_id}
|
||||||
|
|
||||||
|
|
||||||
@router.delete('/labels/{label_id}')
|
@router.delete('/labels/{label_id}')
|
||||||
def admin_delete_label(label_id: str, _: dict = Depends(require_admin)):
|
def admin_delete_label(label_id: str, current_user: dict = Depends(require_admin)):
|
||||||
if not delete_label(label_id, is_admin=True):
|
if not delete_label(label_id, is_admin=True):
|
||||||
raise HTTPException(status_code=404, detail='Label not found')
|
raise HTTPException(status_code=404, detail='Label not found')
|
||||||
|
record_audit_event(current_user['id'], 'label_deleted', 'label', label_id)
|
||||||
return {'status': 'deleted', 'id': label_id}
|
return {'status': 'deleted', 'id': label_id}
|
||||||
|
|
||||||
|
|
||||||
@@ -330,7 +359,7 @@ def get_plugin(plugin_name: str, _: dict = Depends(require_admin)):
|
|||||||
def update_plugin(
|
def update_plugin(
|
||||||
plugin_name: str,
|
plugin_name: str,
|
||||||
payload: AdminPluginUpdate,
|
payload: AdminPluginUpdate,
|
||||||
_: dict = Depends(require_admin),
|
current_user: dict = Depends(require_admin),
|
||||||
):
|
):
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
current = conn.execute(
|
current = conn.execute(
|
||||||
@@ -345,6 +374,9 @@ def update_plugin(
|
|||||||
config = json.loads(current['config']) if current['config'] else {}
|
config = json.loads(current['config']) if current['config'] else {}
|
||||||
if payload.config is not None:
|
if payload.config is not None:
|
||||||
config.update(payload.config)
|
config.update(payload.config)
|
||||||
|
for secret_name in ('access_token', 'client_secret', 'smtp_password'):
|
||||||
|
if config.get(secret_name):
|
||||||
|
config[secret_name] = encrypt_secret(config[secret_name])
|
||||||
|
|
||||||
conn.execute(
|
conn.execute(
|
||||||
'''
|
'''
|
||||||
@@ -356,6 +388,7 @@ def update_plugin(
|
|||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
record_audit_event(current_user['id'], 'plugin_updated', 'plugin', plugin_name, details={'enabled': enabled})
|
||||||
return {
|
return {
|
||||||
'name': plugin_name,
|
'name': plugin_name,
|
||||||
'enabled': enabled,
|
'enabled': enabled,
|
||||||
|
|||||||
+56
-18
@@ -3,17 +3,21 @@
|
|||||||
|
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from backend.app.api.dependencies import get_current_user
|
||||||
from backend.app.database import get_connection, init_db
|
from backend.app.database import get_connection, init_db
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings
|
||||||
from backend.app.services.auth_service import authenticate_user, find_user
|
from backend.app.services.auth_service import authenticate_user, find_user
|
||||||
from backend.app.services.email_service import send_password_reset_email, smtp_configured
|
from backend.app.services.email_service import send_password_reset_email, smtp_configured
|
||||||
from backend.app.services.email_verification import verify_email
|
from backend.app.services.email_verification import verify_email
|
||||||
from backend.app.services.password_reset import create_reset_token, reset_password
|
from backend.app.services.password_reset import create_reset_token, reset_password
|
||||||
from backend.app.services.token_service import issue_token, revoke_token, validate_token
|
from backend.app.services.token_service import issue_token, revoke_token, rotate_refresh_token, validate_token
|
||||||
from backend.app.services.otp_service import verify_code
|
from backend.app.services.otp_service import verify_code
|
||||||
|
from backend.app.services.secret_store import decrypt_secret
|
||||||
|
from backend.app.services.email_addresses import verify_user_email_address
|
||||||
|
from backend.app.services.login_throttle import check_login_allowed, clear_login_failures, record_login_failure
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@@ -24,6 +28,12 @@ class LoginRequest(BaseModel):
|
|||||||
email: str
|
email: str
|
||||||
password: str
|
password: str
|
||||||
otp: str | None = None
|
otp: str | None = None
|
||||||
|
device_id: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshTokenRequest(BaseModel):
|
||||||
|
refresh_token: str
|
||||||
|
device_id: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class PasswordResetRequest(BaseModel):
|
class PasswordResetRequest(BaseModel):
|
||||||
@@ -32,10 +42,17 @@ class PasswordResetRequest(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/login')
|
@router.post('/login')
|
||||||
def login(payload: LoginRequest):
|
def login(payload: LoginRequest, request: Request):
|
||||||
user = authenticate_user(payload.email.strip(), payload.password)
|
email = payload.email.strip()
|
||||||
|
ip_address = request.client.host if request.client else 'unknown'
|
||||||
|
retry_after = check_login_allowed(ip_address, email)
|
||||||
|
if retry_after is not None:
|
||||||
|
raise HTTPException(status_code=429, detail='Too many failed login attempts. Try again later.', headers={'Retry-After': str(retry_after)})
|
||||||
|
|
||||||
|
user = authenticate_user(email, payload.password)
|
||||||
if user is None:
|
if user is None:
|
||||||
reset_user = find_user(payload.email.strip())
|
record_login_failure(ip_address, email)
|
||||||
|
reset_user = find_user(email)
|
||||||
if reset_user and reset_user['email_verified'] and smtp_configured():
|
if reset_user and reset_user['email_verified'] and smtp_configured():
|
||||||
try:
|
try:
|
||||||
token = create_reset_token(reset_user['id'])
|
token = create_reset_token(reset_user['id'])
|
||||||
@@ -46,19 +63,37 @@ def login(payload: LoginRequest):
|
|||||||
raise HTTPException(status_code=401, detail='Invalid username or password')
|
raise HTTPException(status_code=401, detail='Invalid username or password')
|
||||||
if not user['email_verified']:
|
if not user['email_verified']:
|
||||||
raise HTTPException(status_code=403, detail='Email address is not verified')
|
raise HTTPException(status_code=403, detail='Email address is not verified')
|
||||||
if user['otp_enabled'] and not verify_code(user['otp_secret'], payload.otp):
|
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')
|
raise HTTPException(status_code=401, detail='One-time password required or invalid')
|
||||||
|
|
||||||
token_data = issue_token(user['id'], user['username'])
|
clear_login_failures(ip_address, email)
|
||||||
|
token_data = issue_token(user['id'], user['username'], payload.device_id)
|
||||||
return {
|
return {
|
||||||
'access_token': token_data['access_token'],
|
'access_token': token_data['access_token'],
|
||||||
'token_type': 'bearer',
|
'token_type': 'bearer',
|
||||||
'expires_at': token_data['expires_at'],
|
'expires_at': token_data['expires_at'],
|
||||||
'refresh_token': token_data['refresh_token'],
|
'refresh_token': token_data['refresh_token'],
|
||||||
|
'device_id': token_data['device_id'],
|
||||||
'user': {'id': user['id'], 'username': user['username'], 'email': user['email'], 'otp_enabled': bool(user['otp_enabled'])}
|
'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')
|
@router.get('/verify-email')
|
||||||
def verify_email_address(token: str):
|
def verify_email_address(token: str):
|
||||||
if not verify_email(token):
|
if not verify_email(token):
|
||||||
@@ -66,6 +101,14 @@ def verify_email_address(token: str):
|
|||||||
return {'status': 'verified', 'message': 'Email address verified. You can now sign in.'}
|
return {'status': 'verified', 'message': 'Email address verified. You can now sign in.'}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/verify-additional-email')
|
||||||
|
def verify_additional_email_address(token: str):
|
||||||
|
if not verify_user_email_address(token):
|
||||||
|
raise HTTPException(status_code=400, detail='Email verification link is invalid or expired')
|
||||||
|
return {'status': 'verified', 'message': 'Email address verified. You can now sign in.'}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@router.post('/reset-password')
|
@router.post('/reset-password')
|
||||||
def reset_password_endpoint(payload: PasswordResetRequest):
|
def reset_password_endpoint(payload: PasswordResetRequest):
|
||||||
if len(payload.password) < 8:
|
if len(payload.password) < 8:
|
||||||
@@ -76,10 +119,12 @@ def reset_password_endpoint(payload: PasswordResetRequest):
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/logout')
|
@router.post('/logout')
|
||||||
def logout(payload: dict):
|
def logout(authorization: str | None = Header(default=None)):
|
||||||
token = payload.get('token')
|
if not authorization or not authorization.startswith('Bearer '):
|
||||||
|
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||||
|
token = authorization.replace('Bearer ', '', 1).strip()
|
||||||
if not token:
|
if not token:
|
||||||
raise HTTPException(status_code=400, detail='Token is required')
|
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||||
revoked = revoke_token(token)
|
revoked = revoke_token(token)
|
||||||
if not revoked:
|
if not revoked:
|
||||||
raise HTTPException(status_code=404, detail='Token not found or already revoked')
|
raise HTTPException(status_code=404, detail='Token not found or already revoked')
|
||||||
@@ -87,14 +132,7 @@ def logout(payload: dict):
|
|||||||
|
|
||||||
|
|
||||||
@router.get('/me')
|
@router.get('/me')
|
||||||
def current_user(token: str):
|
def current_user(user: dict = Depends(get_current_user)):
|
||||||
info = validate_token(token)
|
|
||||||
if info is None:
|
|
||||||
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
|
||||||
with get_connection() as conn:
|
|
||||||
user = conn.execute('SELECT * FROM users WHERE id = ?', (info['user_id'],)).fetchone()
|
|
||||||
if user is None:
|
|
||||||
raise HTTPException(status_code=404, detail='User not found')
|
|
||||||
return {
|
return {
|
||||||
'id': user['id'],
|
'id': user['id'],
|
||||||
'username': user['username'],
|
'username': user['username'],
|
||||||
|
|||||||
@@ -2,14 +2,15 @@
|
|||||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from fastapi import APIRouter, Header, HTTPException, status
|
from fastapi import APIRouter, Header, HTTPException, Response, status
|
||||||
import logging
|
import logging
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from backend.app.services.link_service import create_link, delete_link, get_link_tags, get_owned_link, list_public_links, list_tags, mark_mastodon_posted, update_link
|
from backend.app.services.link_service import create_link, delete_link, find_owned_link_by_title_url, get_link_tags, get_owned_link, list_public_links, list_tags, mark_mastodon_posted, update_link
|
||||||
from backend.app.database import get_connection
|
from backend.app.database import get_connection
|
||||||
from backend.app.services.plugin_manager import plugin_manager
|
from backend.app.services.plugin_manager import plugin_manager
|
||||||
from backend.app.services.token_service import validate_token
|
from backend.app.services.token_service import validate_token
|
||||||
|
from backend.app.services.audit_service import record_audit_event
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -35,8 +36,23 @@ def available_tags():
|
|||||||
return list_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)
|
@router.post('/links', status_code=status.HTTP_201_CREATED)
|
||||||
def create_link_endpoint(payload: LinkCreate, authorization: str | None = Header(default=None)):
|
def create_link_endpoint(payload: LinkCreate, response: Response, authorization: str | None = Header(default=None)):
|
||||||
if not authorization or not authorization.startswith('Bearer '):
|
if not authorization or not authorization.startswith('Bearer '):
|
||||||
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
||||||
token = authorization.replace('Bearer ', '', 1)
|
token = authorization.replace('Bearer ', '', 1)
|
||||||
@@ -45,16 +61,28 @@ def create_link_endpoint(payload: LinkCreate, authorization: str | None = Header
|
|||||||
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
raise HTTPException(status_code=401, detail='Token expired or invalid')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
record = create_link(info['user_id'], payload.title, payload.url, payload.comment, payload.timestamp, payload.tags)
|
record = find_owned_link_by_title_url(info['user_id'], payload.title, payload.url)
|
||||||
|
duplicate = record is not None
|
||||||
|
if duplicate:
|
||||||
|
record = update_link(record['id'], info['user_id'], payload.title, payload.url, payload.comment, payload.tags)
|
||||||
|
else:
|
||||||
|
record = create_link(info['user_id'], payload.title, payload.url, payload.comment, payload.timestamp, payload.tags)
|
||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
raise HTTPException(status_code=422, detail=str(error)) from error
|
raise HTTPException(status_code=422, detail=str(error)) from error
|
||||||
|
if duplicate:
|
||||||
|
response.status_code = status.HTTP_200_OK
|
||||||
plugin_results = plugin_manager.dispatch({'type': 'link_created', **record})
|
plugin_results = plugin_manager.dispatch({'type': 'link_created', **record})
|
||||||
mastodon_result = next((result for result in plugin_results if result.get('plugin') == 'mastodon'), None)
|
mastodon_result = next((result for result in plugin_results if result.get('plugin') == 'mastodon'), None)
|
||||||
if mastodon_result and mastodon_result.get('status') == 'posted':
|
if mastodon_result and mastodon_result.get('status') == 'posted':
|
||||||
mark_mastodon_posted(record['id'], info['user_id'], mastodon_result.get('post_id'))
|
mark_mastodon_posted(record['id'], info['user_id'], mastodon_result.get('post_id'))
|
||||||
if any(result.get('status') == 'failed' for result in plugin_results):
|
if any(result.get('status') == 'failed' for result in plugin_results):
|
||||||
logger.warning('One or more plugins failed for link_id=%s results=%s', record['id'], plugin_results)
|
logger.warning('One or more plugins failed for link_id=%s results=%s', record['id'], plugin_results)
|
||||||
return record
|
plugin_errors = [
|
||||||
|
{'plugin': result.get('plugin', 'unknown'), 'reason': result.get('reason', 'Plugin failed')}
|
||||||
|
for result in plugin_results
|
||||||
|
if result.get('status') == 'failed'
|
||||||
|
]
|
||||||
|
return {**record, 'duplicate': duplicate, 'plugin_errors': plugin_errors}
|
||||||
|
|
||||||
|
|
||||||
@router.put('/links/{link_id}')
|
@router.put('/links/{link_id}')
|
||||||
@@ -100,6 +128,7 @@ def delete_link_endpoint(
|
|||||||
raise HTTPException(status_code=502, detail=result.get('reason', 'Could not delete Mastodon posts'))
|
raise HTTPException(status_code=502, detail=result.get('reason', 'Could not delete Mastodon posts'))
|
||||||
if not delete_link(link_id, info['user_id']):
|
if not delete_link(link_id, info['user_id']):
|
||||||
raise HTTPException(status_code=404, detail='Link not found or not owned by user')
|
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}
|
return {'status': 'deleted', 'id': link_id}
|
||||||
|
|
||||||
|
|
||||||
@@ -123,6 +152,7 @@ def post_link_to_mastodon(
|
|||||||
result = plugin_manager.post_to_mastodon({'type': 'link_created', **event})
|
result = plugin_manager.post_to_mastodon({'type': 'link_created', **event})
|
||||||
if result.get('status') == 'posted':
|
if result.get('status') == 'posted':
|
||||||
mark_mastodon_posted(link_id, info['user_id'], result.get('post_id'))
|
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')}
|
return {'status': 'posted', 'post_id': result.get('post_id')}
|
||||||
if result.get('status') == 'skipped':
|
if result.get('status') == 'skipped':
|
||||||
raise HTTPException(status_code=409, detail='Mastodon is not enabled or configured')
|
raise HTTPException(status_code=409, detail='Mastodon is not enabled or configured')
|
||||||
|
|||||||
@@ -10,12 +10,15 @@ from starlette.requests import Request
|
|||||||
|
|
||||||
from backend.app.api.dependencies import get_current_user
|
from backend.app.api.dependencies import get_current_user
|
||||||
from backend.app.services.mastodon_oauth import finish_authorization, start_authorization
|
from backend.app.services.mastodon_oauth import finish_authorization, start_authorization
|
||||||
|
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||||
|
import logging
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@router.get('/oauth/start')
|
@router.get('/oauth/start')
|
||||||
def oauth_start(instance: str = 'mastodon.social', user: dict = Depends(get_current_user)):
|
def oauth_start(request: Request, instance: str = 'mastodon.social', user: dict = Depends(get_current_user)):
|
||||||
try:
|
try:
|
||||||
authorization_url = start_authorization(user['id'], instance)
|
authorization_url = start_authorization(user['id'], instance)
|
||||||
except HTTPError as error:
|
except HTTPError as error:
|
||||||
@@ -27,7 +30,8 @@ def oauth_start(instance: str = 'mastodon.social', user: dict = Depends(get_curr
|
|||||||
headers=headers,
|
headers=headers,
|
||||||
) from error
|
) from error
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
raise HTTPException(status_code=502, detail=f'Could not register with Mastodon: {error}') from error
|
logger.error('Mastodon registration failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=502, detail=public_error(request, 'Could not register with Mastodon.')) from error
|
||||||
return {'authorization_url': authorization_url}
|
return {'authorization_url': authorization_url}
|
||||||
|
|
||||||
|
|
||||||
@@ -38,5 +42,6 @@ def oauth_callback(request: Request, code: str | None = None, state: str | None
|
|||||||
try:
|
try:
|
||||||
finish_authorization(code, state)
|
finish_authorization(code, state)
|
||||||
except Exception as callback_error:
|
except Exception as callback_error:
|
||||||
return RedirectResponse(f'/profile?mastodon_error={quote(str(callback_error))}')
|
logger.error('Mastodon callback failed request_id=%s error=%s', request_id(request), redacted_error(callback_error))
|
||||||
|
return RedirectResponse(f'/profile?mastodon_error={quote(public_error(request, "Could not complete Mastodon authorization."))}')
|
||||||
return RedirectResponse('/profile?mastodon=connected')
|
return RedirectResponse('/profile?mastodon=connected')
|
||||||
@@ -5,14 +5,17 @@ from datetime import datetime, timedelta, timezone
|
|||||||
import json
|
import json
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException, Request
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings
|
||||||
from backend.app.database import get_connection, hash_password
|
from backend.app.database import get_connection, hash_password
|
||||||
from backend.app.services.email_service import get_smtp_settings, save_smtp_settings, send_test_email
|
from backend.app.services.email_service import get_smtp_settings, save_smtp_settings, send_test_email
|
||||||
|
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||||
|
import logging
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class SetupRequest(BaseModel):
|
class SetupRequest(BaseModel):
|
||||||
@@ -92,7 +95,7 @@ def save_configuration(payload: SetupRequest):
|
|||||||
|
|
||||||
|
|
||||||
@router.post('/test-mail')
|
@router.post('/test-mail')
|
||||||
def test_mail(payload: TestMailRequest | None = None):
|
def test_mail(request: Request, payload: TestMailRequest | None = None):
|
||||||
if has_administrator():
|
if has_administrator():
|
||||||
raise HTTPException(status_code=409, detail='LinkLog is already configured')
|
raise HTTPException(status_code=409, detail='LinkLog is already configured')
|
||||||
pending = get_pending_setup()
|
pending = get_pending_setup()
|
||||||
@@ -119,7 +122,8 @@ def test_mail(payload: TestMailRequest | None = None):
|
|||||||
try:
|
try:
|
||||||
send_test_email(payload.email if payload and payload.email else pending['email'])
|
send_test_email(payload.email if payload and payload.email else pending['email'])
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
raise HTTPException(status_code=503, detail=f'SMTP test mail could not be sent: {error}') from error
|
logger.error('SMTP test mail failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'SMTP test mail could not be sent.')) from error
|
||||||
|
|
||||||
sends = int(rate.get('sends', 0)) + 1
|
sends = int(rate.get('sends', 0)) + 1
|
||||||
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
|
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
|
||||||
|
|||||||
+210
-21
@@ -2,21 +2,35 @@
|
|||||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import warnings
|
||||||
|
from io import BytesIO
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
|
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
|
||||||
|
from PIL import Image, UnidentifiedImageError
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from backend.app.api.dependencies import get_current_user
|
from backend.app.api.dependencies import get_current_user
|
||||||
from backend.app.database import AVATARS_DIR, get_connection, hash_password, verify_password
|
from backend.app.database import AVATARS_DIR, get_connection, hash_password, verify_password
|
||||||
from backend.app.services.link_service import create_label, delete_label, list_user_labels, update_label
|
from backend.app.services.link_service import create_label, delete_label, list_user_labels, update_label
|
||||||
from backend.app.services.otp_service import create_secret, provisioning_uri, verify_code
|
from backend.app.services.otp_service import consume_recovery_code, create_recovery_codes, create_secret, provisioning_uri, verify_code
|
||||||
|
from backend.app.services.email_addresses import add_user_email_address, create_email_verification, list_user_email_addresses
|
||||||
|
from backend.app.services.email_service import send_verification_email, smtp_configured
|
||||||
|
from backend.app.core.config import settings
|
||||||
|
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
|
||||||
|
from backend.app.services.audit_service import record_audit_event
|
||||||
|
from backend.app.core.errors import public_error, redacted_error, request_id
|
||||||
|
import logging
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
MAX_AVATAR_BYTES = 2 * 1024 * 1024
|
||||||
|
MAX_AVATAR_PIXELS = 25_000_000
|
||||||
|
|
||||||
|
|
||||||
class UserConfigUpdate(BaseModel):
|
class UserConfigUpdate(BaseModel):
|
||||||
email: str | None = None
|
|
||||||
bio: str | None = None
|
bio: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@@ -28,6 +42,18 @@ class PasswordUpdate(BaseModel):
|
|||||||
class OtpUpdate(BaseModel):
|
class OtpUpdate(BaseModel):
|
||||||
action: str
|
action: str
|
||||||
code: str | None = None
|
code: str | None = None
|
||||||
|
current_password: str | None = None
|
||||||
|
recovery_code: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class AdditionalEmail(BaseModel):
|
||||||
|
email: str
|
||||||
|
|
||||||
|
|
||||||
|
class OtpRecovery(BaseModel):
|
||||||
|
current_password: str
|
||||||
|
recovery_code: str
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class UserPluginConfigUpdate(BaseModel):
|
class UserPluginConfigUpdate(BaseModel):
|
||||||
@@ -66,7 +92,6 @@ def update_current_user_profile(
|
|||||||
if current is None:
|
if current is None:
|
||||||
raise HTTPException(status_code=404, detail='User not found')
|
raise HTTPException(status_code=404, detail='User not found')
|
||||||
|
|
||||||
email = payload.email or current['email']
|
|
||||||
bio = payload.bio if payload.bio is not None else current['bio']
|
bio = payload.bio if payload.bio is not None else current['bio']
|
||||||
|
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -75,7 +100,7 @@ def update_current_user_profile(
|
|||||||
SET email = ?, bio = ?, updated_at = CURRENT_TIMESTAMP
|
SET email = ?, bio = ?, updated_at = CURRENT_TIMESTAMP
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
''',
|
''',
|
||||||
(email, bio, user['id']),
|
(current['email'], bio, user['id']),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
@@ -95,6 +120,7 @@ def update_password(payload: PasswordUpdate, user: dict = Depends(get_current_us
|
|||||||
(hash_password(payload.new_password), user['id']),
|
(hash_password(payload.new_password), user['id']),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
record_audit_event(user['id'], 'password_changed', 'user', user['id'])
|
||||||
return {'status': 'password_updated'}
|
return {'status': 'password_updated'}
|
||||||
|
|
||||||
|
|
||||||
@@ -109,16 +135,27 @@ def setup_otp(user: dict = Depends(get_current_user)):
|
|||||||
raise HTTPException(status_code=409, detail='One-time password is already enabled')
|
raise HTTPException(status_code=409, detail='One-time password is already enabled')
|
||||||
secret = create_secret()
|
secret = create_secret()
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
conn.execute('UPDATE users SET otp_secret = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (secret, user['id']))
|
conn.execute('UPDATE users SET otp_secret = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (encrypt_secret(secret), user['id']))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return {'secret': secret, 'otpauth_url': provisioning_uri(secret, user['username'])}
|
record_audit_event(user['id'], 'otp_enrolled', 'user', user['id'])
|
||||||
|
return {
|
||||||
|
'secret': secret,
|
||||||
|
'otpauth_url': provisioning_uri(secret, user['username']),
|
||||||
|
'recovery_codes': create_recovery_codes(user['id']),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.post('/otp')
|
@router.post('/otp')
|
||||||
def update_otp(payload: OtpUpdate, user: dict = Depends(get_current_user)):
|
def update_otp(payload: OtpUpdate, user: dict = Depends(get_current_user)):
|
||||||
if payload.action not in {'enable', 'disable'}:
|
if payload.action not in {'enable', 'disable'}:
|
||||||
raise HTTPException(status_code=422, detail='OTP action must be enable or disable')
|
raise HTTPException(status_code=422, detail='OTP action must be enable or disable')
|
||||||
if not verify_code(user['otp_secret'], payload.code):
|
if payload.action == 'disable' and not payload.current_password:
|
||||||
|
raise HTTPException(status_code=400, detail='Current password is required to disable one-time password')
|
||||||
|
if payload.action == 'disable' and not verify_password(payload.current_password, user['password_hash']):
|
||||||
|
raise HTTPException(status_code=400, detail='Current password is incorrect')
|
||||||
|
valid_code = verify_code(decrypt_secret(user['otp_secret']), payload.code)
|
||||||
|
valid_recovery_code = payload.action == 'disable' and payload.recovery_code and consume_recovery_code(user['id'], payload.recovery_code)
|
||||||
|
if not valid_code and not valid_recovery_code:
|
||||||
raise HTTPException(status_code=400, detail='Invalid one-time password')
|
raise HTTPException(status_code=400, detail='Invalid one-time password')
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
if payload.action == 'enable':
|
if payload.action == 'enable':
|
||||||
@@ -126,9 +163,145 @@ def update_otp(payload: OtpUpdate, user: dict = Depends(get_current_user)):
|
|||||||
else:
|
else:
|
||||||
conn.execute('UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
|
conn.execute('UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
record_audit_event(user['id'], f'otp_{payload.action}d', 'user', user['id'])
|
||||||
return {'status': 'updated', 'enabled': payload.action == 'enable'}
|
return {'status': 'updated', 'enabled': payload.action == 'enable'}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/otp/recover')
|
||||||
|
def recover_otp(payload: OtpRecovery, user: dict = Depends(get_current_user)):
|
||||||
|
if not verify_password(payload.current_password, user['password_hash']):
|
||||||
|
raise HTTPException(status_code=400, detail='Current password is incorrect')
|
||||||
|
if not consume_recovery_code(user['id'], payload.recovery_code):
|
||||||
|
raise HTTPException(status_code=400, detail='Recovery code is invalid or already used')
|
||||||
|
with get_connection() as conn:
|
||||||
|
conn.execute(
|
||||||
|
'UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||||
|
(user['id'],),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
record_audit_event(user['id'], 'otp_recovered', 'user', user['id'])
|
||||||
|
return {'status': 'otp_recovered', 'enabled': False}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/emails')
|
||||||
|
def get_additional_emails(user: dict = Depends(get_current_user)):
|
||||||
|
return [{'email': user['email'], 'verified': bool(user['email_verified']), 'primary': True}] + list_user_email_addresses(user['id'])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/emails', status_code=201)
|
||||||
|
def add_additional_email(payload: AdditionalEmail, request: Request, user: dict = Depends(get_current_user)):
|
||||||
|
email = payload.email.strip().lower()
|
||||||
|
if email == user['email'].lower():
|
||||||
|
raise HTTPException(status_code=409, detail='This is already the primary email address')
|
||||||
|
with get_connection() as conn:
|
||||||
|
if conn.execute('SELECT 1 FROM users WHERE lower(email) = ?', (email,)).fetchone():
|
||||||
|
raise HTTPException(status_code=409, detail='Email address already exists')
|
||||||
|
additional_count = conn.execute(
|
||||||
|
'SELECT COUNT(*) AS count FROM user_email_addresses WHERE user_id = ?',
|
||||||
|
(user['id'],),
|
||||||
|
).fetchone()['count']
|
||||||
|
if additional_count >= 5:
|
||||||
|
raise HTTPException(status_code=422, detail='You can add at most five additional email addresses')
|
||||||
|
try:
|
||||||
|
address = add_user_email_address(user['id'], email)
|
||||||
|
except ValueError as error:
|
||||||
|
raise HTTPException(status_code=409, detail=str(error)) from error
|
||||||
|
if smtp_configured():
|
||||||
|
email_address, token = create_email_verification(user['id'], address['id'])
|
||||||
|
verification_url = f'{settings.public_url}/api/auth/verify-additional-email?token={token}'
|
||||||
|
try:
|
||||||
|
send_verification_email(email_address, user['username'], verification_url)
|
||||||
|
except Exception as error:
|
||||||
|
logger.error('Additional email verification failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'Email address added but verification email could not be sent.')) from error
|
||||||
|
with get_connection() as conn:
|
||||||
|
conn.execute(
|
||||||
|
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||||
|
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||||
|
(f'email_verify_rate:{address["id"]}', json.dumps({'sends': 1, 'last_sent': datetime.now(timezone.utc).isoformat()})),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return address
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/emails/{address_id}/resend')
|
||||||
|
def resend_additional_email(address_id: str, request: Request, user: dict = Depends(get_current_user)):
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
setting_name = f'email_verify_rate:{address_id}'
|
||||||
|
with get_connection() as conn:
|
||||||
|
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
|
||||||
|
address = conn.execute('SELECT email, verified FROM user_email_addresses WHERE id = ? AND user_id = ?', (address_id, user['id'])).fetchone()
|
||||||
|
if address is None:
|
||||||
|
raise HTTPException(status_code=404, detail='Email address not found')
|
||||||
|
if address['verified']:
|
||||||
|
raise HTTPException(status_code=409, detail='Email address is already verified')
|
||||||
|
rate = json.loads(row['value']) if row else {}
|
||||||
|
last_sent = datetime.fromisoformat(rate['last_sent']) if rate.get('last_sent') else None
|
||||||
|
cooldown_until = datetime.fromisoformat(rate['cooldown_until']) if rate.get('cooldown_until') else None
|
||||||
|
if cooldown_until and now < cooldown_until:
|
||||||
|
retry_after = int((cooldown_until - now).total_seconds()) + 1
|
||||||
|
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before resending verification email.', headers={'Retry-After': str(retry_after)})
|
||||||
|
if last_sent and now - last_sent < timedelta(seconds=20):
|
||||||
|
retry_after = int((timedelta(seconds=20) - (now - last_sent)).total_seconds()) + 1
|
||||||
|
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before resending verification email.', headers={'Retry-After': str(retry_after)})
|
||||||
|
email, token = create_email_verification(user['id'], address_id)
|
||||||
|
verification_url = f'{settings.public_url}/api/auth/verify-additional-email?token={token}'
|
||||||
|
try:
|
||||||
|
send_verification_email(email, user['username'], verification_url)
|
||||||
|
except Exception as error:
|
||||||
|
logger.error('Verification email resend failed request_id=%s error=%s', request_id(request), redacted_error(error))
|
||||||
|
raise HTTPException(status_code=503, detail=public_error(request, 'Verification email could not be sent.')) from error
|
||||||
|
sends = int(rate.get('sends', 0)) + 1
|
||||||
|
updated = {'sends': sends, 'last_sent': now.isoformat()}
|
||||||
|
if sends >= 5:
|
||||||
|
updated['cooldown_until'] = (now + timedelta(minutes=2)).isoformat()
|
||||||
|
with get_connection() as conn:
|
||||||
|
conn.execute('''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||||
|
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''', (setting_name, json.dumps(updated)))
|
||||||
|
conn.commit()
|
||||||
|
return {'status': 'sent', 'message': f'Verification email sent to {email}.', 'next_allowed_at': (now + timedelta(seconds=20)).isoformat()}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete('/emails/{address_id}')
|
||||||
|
def remove_additional_email(address_id: str, user: dict = Depends(get_current_user)):
|
||||||
|
with get_connection() as conn:
|
||||||
|
cursor = conn.execute('DELETE FROM user_email_addresses WHERE id = ? AND user_id = ?', (address_id, user['id']))
|
||||||
|
conn.commit()
|
||||||
|
if cursor.rowcount == 0:
|
||||||
|
raise HTTPException(status_code=404, detail='Email address not found')
|
||||||
|
record_audit_event(user['id'], 'email_address_deleted', 'email_address', address_id)
|
||||||
|
return {'status': 'deleted', 'id': address_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/emails/{address_id}/make-primary')
|
||||||
|
def make_email_primary(address_id: str, user: dict = Depends(get_current_user)):
|
||||||
|
with get_connection() as conn:
|
||||||
|
address = conn.execute(
|
||||||
|
'SELECT email, verified FROM user_email_addresses WHERE id = ? AND user_id = ?',
|
||||||
|
(address_id, user['id']),
|
||||||
|
).fetchone()
|
||||||
|
if address is None:
|
||||||
|
raise HTTPException(status_code=404, detail='Email address not found')
|
||||||
|
if not address['verified']:
|
||||||
|
raise HTTPException(status_code=400, detail='Email address must be validated before it can become primary')
|
||||||
|
old_email = user['email']
|
||||||
|
conn.execute(
|
||||||
|
'DELETE FROM user_email_addresses WHERE id = ? AND user_id = ?',
|
||||||
|
(address_id, user['id']),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
'INSERT INTO user_email_addresses (id, user_id, email, verified) VALUES (?, ?, ?, 1)',
|
||||||
|
(str(uuid4()), user['id'], old_email),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
'UPDATE users SET email = ?, email_verified = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||||
|
(address['email'], user['id']),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
record_audit_event(user['id'], 'primary_email_changed', 'user', user['id'])
|
||||||
|
return {'status': 'updated', 'email': address['email']}
|
||||||
|
|
||||||
|
|
||||||
@router.get('/labels')
|
@router.get('/labels')
|
||||||
def get_labels(user: dict = Depends(get_current_user)):
|
def get_labels(user: dict = Depends(get_current_user)):
|
||||||
return list_user_labels(user['id'])
|
return list_user_labels(user['id'])
|
||||||
@@ -157,6 +330,7 @@ def edit_label(label_id: str, payload: LabelUpdate, user: dict = Depends(get_cur
|
|||||||
def remove_label(label_id: str, user: dict = Depends(get_current_user)):
|
def remove_label(label_id: str, user: dict = Depends(get_current_user)):
|
||||||
if not delete_label(label_id, user['id']):
|
if not delete_label(label_id, user['id']):
|
||||||
raise HTTPException(status_code=404, detail='Label not found or not owned by user')
|
raise HTTPException(status_code=404, detail='Label not found or not owned by user')
|
||||||
|
record_audit_event(user['id'], 'label_deleted', 'label', label_id)
|
||||||
return {'status': 'deleted', 'id': label_id}
|
return {'status': 'deleted', 'id': label_id}
|
||||||
|
|
||||||
|
|
||||||
@@ -165,25 +339,33 @@ async def upload_avatar(
|
|||||||
avatar: UploadFile = File(...),
|
avatar: UploadFile = File(...),
|
||||||
user: dict = Depends(get_current_user),
|
user: dict = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
allowed_types = {
|
if avatar.content_type not in {'image/gif', 'image/jpeg', 'image/png', 'image/webp'}:
|
||||||
'image/gif': '.gif',
|
|
||||||
'image/jpeg': '.jpg',
|
|
||||||
'image/png': '.png',
|
|
||||||
'image/webp': '.webp',
|
|
||||||
}
|
|
||||||
suffix = allowed_types.get(avatar.content_type or '')
|
|
||||||
if suffix is None:
|
|
||||||
raise HTTPException(status_code=415, detail='Avatar must be a PNG, JPEG, GIF, or WebP image')
|
raise HTTPException(status_code=415, detail='Avatar must be a PNG, JPEG, GIF, or WebP image')
|
||||||
|
|
||||||
contents = await avatar.read(2 * 1024 * 1024 + 1)
|
contents = await avatar.read(MAX_AVATAR_BYTES + 1)
|
||||||
if len(contents) > 2 * 1024 * 1024:
|
if len(contents) > MAX_AVATAR_BYTES:
|
||||||
raise HTTPException(status_code=413, detail='Avatar must be 2 MB or smaller')
|
raise HTTPException(status_code=413, detail='Avatar must be 2 MB or smaller')
|
||||||
|
|
||||||
avatar_path = AVATARS_DIR / f'{user["id"]}{suffix}'
|
try:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||||
|
with Image.open(BytesIO(contents)) as image:
|
||||||
|
if image.width * image.height > MAX_AVATAR_PIXELS:
|
||||||
|
raise HTTPException(status_code=413, detail='Avatar dimensions are too large')
|
||||||
|
image.verify()
|
||||||
|
with Image.open(BytesIO(contents)) as image:
|
||||||
|
image.load()
|
||||||
|
normalized = image.convert('RGBA')
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except (Image.DecompressionBombError, Image.DecompressionBombWarning, UnidentifiedImageError, OSError, ValueError) as error:
|
||||||
|
raise HTTPException(status_code=415, detail='Avatar content is not a valid image') from error
|
||||||
|
|
||||||
|
avatar_path = AVATARS_DIR / f'{user["id"]}.png'
|
||||||
|
normalized.save(avatar_path, format='PNG', optimize=True)
|
||||||
for existing_path in AVATARS_DIR.glob(f'{user["id"]}.*'):
|
for existing_path in AVATARS_DIR.glob(f'{user["id"]}.*'):
|
||||||
if existing_path != avatar_path:
|
if existing_path != avatar_path:
|
||||||
existing_path.unlink(missing_ok=True)
|
existing_path.unlink(missing_ok=True)
|
||||||
avatar_path.write_bytes(contents)
|
|
||||||
avatar_url = f'/media/{avatar_path.name}'
|
avatar_url = f'/media/{avatar_path.name}'
|
||||||
|
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
@@ -192,6 +374,7 @@ async def upload_avatar(
|
|||||||
(avatar_url, user['id']),
|
(avatar_url, user['id']),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
record_audit_event(user['id'], 'avatar_updated', 'user', user['id'])
|
||||||
return {'avatar_url': avatar_url}
|
return {'avatar_url': avatar_url}
|
||||||
|
|
||||||
|
|
||||||
@@ -207,6 +390,8 @@ def get_user_plugin_config(plugin_name: str, user: dict = Depends(get_current_us
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
config = json.loads(row['config']) if row['config'] else {}
|
config = json.loads(row['config']) if row['config'] else {}
|
||||||
|
if config.get('access_token'):
|
||||||
|
config.pop('access_token')
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
@@ -224,6 +409,8 @@ def update_user_plugin_config(
|
|||||||
|
|
||||||
current_config = json.loads(current['config']) if current and current['config'] else {}
|
current_config = json.loads(current['config']) if current and current['config'] else {}
|
||||||
updates = payload.model_dump(exclude_none=True)
|
updates = payload.model_dump(exclude_none=True)
|
||||||
|
if updates.get('access_token'):
|
||||||
|
updates['access_token'] = encrypt_secret(updates['access_token'])
|
||||||
merged = {**current_config, **updates}
|
merged = {**current_config, **updates}
|
||||||
|
|
||||||
if current is None:
|
if current is None:
|
||||||
@@ -246,4 +433,6 @@ def update_user_plugin_config(
|
|||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return merged
|
public_config = dict(merged)
|
||||||
|
public_config.pop('access_token', None)
|
||||||
|
return public_config
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ from dataclasses import dataclass
|
|||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet
|
||||||
|
|
||||||
|
|
||||||
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
||||||
DB_PATH = BASE_DIR / 'data' / 'linklog.db'
|
DB_PATH = BASE_DIR / 'data' / 'linklog.db'
|
||||||
@@ -20,12 +22,15 @@ def normalize_public_url(value: str) -> str:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Settings:
|
class Settings:
|
||||||
|
app_env: str = os.getenv('APP_ENV', 'development').lower()
|
||||||
app_name: str = os.getenv('LINKLOG_APP_NAME', 'LinkLog')
|
app_name: str = os.getenv('LINKLOG_APP_NAME', 'LinkLog')
|
||||||
version: str = os.getenv('LINKLOG_VERSION', '0.1.0')
|
version: str = os.getenv('LINKLOG_VERSION', '0.1.0')
|
||||||
database_url: str = os.getenv('LINKLOG_DATABASE_URL', f'sqlite:///{DB_PATH}')
|
database_url: str = os.getenv('LINKLOG_DATABASE_URL', f'sqlite:///{DB_PATH}')
|
||||||
secret_key: str = os.getenv('LINKLOG_SECRET_KEY', 'dev-secret-key-change-me')
|
secret_key: str = os.getenv('LINKLOG_SECRET_KEY', 'dev-secret-key-change-me')
|
||||||
token_expiry_days: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_DAYS', '30'))
|
data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
|
||||||
public_url: str = normalize_public_url(os.getenv('LINKLOG_PUBLIC_URL', 'http://localhost:8000'))
|
token_expiry_minutes: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_MINUTES', '15'))
|
||||||
|
refresh_token_expiry_days: int = int(os.getenv('LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS', '30'))
|
||||||
|
public_url: str = normalize_public_url(os.getenv('LINKLOG_PUBLIC_URL', 'linklog.example.com'))
|
||||||
smtp_host: str = os.getenv('LINKLOG_SMTP_HOST', '')
|
smtp_host: str = os.getenv('LINKLOG_SMTP_HOST', '')
|
||||||
smtp_port: int = int(os.getenv('LINKLOG_SMTP_PORT', '587'))
|
smtp_port: int = int(os.getenv('LINKLOG_SMTP_PORT', '587'))
|
||||||
smtp_username: str = os.getenv('LINKLOG_SMTP_USERNAME', '')
|
smtp_username: str = os.getenv('LINKLOG_SMTP_USERNAME', '')
|
||||||
@@ -57,3 +62,19 @@ class Settings:
|
|||||||
|
|
||||||
|
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
|
|
||||||
|
|
||||||
|
def validate_configuration(values: Settings) -> None:
|
||||||
|
if values.app_env == 'production':
|
||||||
|
if not values.secret_key or values.secret_key == 'dev-secret-key-change-me':
|
||||||
|
raise RuntimeError('LINKLOG_SECRET_KEY must be configured in production')
|
||||||
|
if len(values.secret_key) < 32 or len(set(values.secret_key)) < 12:
|
||||||
|
raise RuntimeError('LINKLOG_SECRET_KEY must be at least 32 characters with sufficient entropy')
|
||||||
|
if not values.data_encryption_key:
|
||||||
|
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY must be configured in production')
|
||||||
|
|
||||||
|
if values.data_encryption_key:
|
||||||
|
try:
|
||||||
|
Fernet(values.data_encryption_key.encode('ascii'))
|
||||||
|
except (ValueError, UnicodeEncodeError) as error:
|
||||||
|
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY must be a valid Fernet key') from error
|
||||||
|
|||||||
@@ -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)}'
|
||||||
@@ -192,6 +192,74 @@ WHERE mastodon_post_ids IS NULL;
|
|||||||
ALTER TABLE users ADD COLUMN otp_secret TEXT;
|
ALTER TABLE users ADD COLUMN otp_secret TEXT;
|
||||||
ALTER TABLE users ADD COLUMN otp_enabled INTEGER NOT NULL DEFAULT 0;
|
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);
|
||||||
|
''')
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+14
-2
@@ -1,8 +1,9 @@
|
|||||||
## Copyright © 2026 Olaf Kolkman
|
## Copyright © 2026 Olaf Kolkman
|
||||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, Request
|
||||||
import logging
|
import logging
|
||||||
|
from uuid import uuid4
|
||||||
from fastapi.responses import HTMLResponse
|
from fastapi.responses import HTMLResponse
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
@@ -17,13 +18,23 @@ from backend.app.api.public import router as public_router
|
|||||||
from backend.app.api.setup import router as setup_router
|
from backend.app.api.setup import router as setup_router
|
||||||
from backend.app.api.setup import has_administrator
|
from backend.app.api.setup import has_administrator
|
||||||
from backend.app.api.user_config import router as user_config_router
|
from backend.app.api.user_config import router as user_config_router
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings, validate_configuration
|
||||||
from backend.app.database import AVATARS_DIR
|
from backend.app.database import AVATARS_DIR
|
||||||
from backend.app.services.link_service import get_public_profile, list_public_links
|
from backend.app.services.link_service import get_public_profile, list_public_links
|
||||||
|
|
||||||
logging.basicConfig(level=getattr(logging, settings.log_level, logging.INFO))
|
logging.basicConfig(level=getattr(logging, settings.log_level, logging.INFO))
|
||||||
|
validate_configuration(settings)
|
||||||
|
|
||||||
app = FastAPI(title='LinkLog API', version=settings.version)
|
app = FastAPI(title='LinkLog API', version=settings.version)
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware('http')
|
||||||
|
async def add_request_id(request: Request, call_next):
|
||||||
|
request.state.request_id = request.headers.get('X-Request-ID') or str(uuid4())
|
||||||
|
response = await call_next(request)
|
||||||
|
response.headers['X-Request-ID'] = request.state.request_id
|
||||||
|
return response
|
||||||
|
|
||||||
app.mount('/static', StaticFiles(directory='frontend/static'), name='static')
|
app.mount('/static', StaticFiles(directory='frontend/static'), name='static')
|
||||||
app.mount('/media', StaticFiles(directory=AVATARS_DIR), name='media')
|
app.mount('/media', StaticFiles(directory=AVATARS_DIR), name='media')
|
||||||
app.include_router(auth_router, prefix='/api/auth')
|
app.include_router(auth_router, prefix='/api/auth')
|
||||||
@@ -35,6 +46,7 @@ app.include_router(user_config_router, prefix='/api/user')
|
|||||||
app.include_router(setup_router, prefix='/api/setup')
|
app.include_router(setup_router, prefix='/api/setup')
|
||||||
|
|
||||||
templates = Jinja2Templates(directory='frontend/templates')
|
templates = Jinja2Templates(directory='frontend/templates')
|
||||||
|
templates.env.globals['app_version'] = settings.version
|
||||||
|
|
||||||
|
|
||||||
@app.get('/', response_class=HTMLResponse)
|
@app.get('/', response_class=HTMLResponse)
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -7,7 +7,15 @@ from backend.app.database import get_connection, hash_password, verify_password
|
|||||||
|
|
||||||
def authenticate_user(email: str, password: str):
|
def authenticate_user(email: str, password: str):
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
row = conn.execute('SELECT * FROM users WHERE email = ?', (email,)).fetchone()
|
row = conn.execute(
|
||||||
|
'''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']):
|
if row is None or not verify_password(password, row['password_hash']):
|
||||||
return None
|
return None
|
||||||
user = dict(row)
|
user = dict(row)
|
||||||
@@ -26,4 +34,11 @@ def authenticate_user(email: str, password: str):
|
|||||||
def find_user(email: str):
|
def find_user(email: str):
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
row = conn.execute('SELECT * FROM users WHERE email = ?', (email,)).fetchone()
|
row = conn.execute('SELECT * FROM users WHERE email = ?', (email,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
row = conn.execute(
|
||||||
|
'''SELECT users.* FROM users JOIN user_email_addresses
|
||||||
|
ON user_email_addresses.user_id = users.id
|
||||||
|
WHERE user_email_addresses.email = ?''',
|
||||||
|
(email,),
|
||||||
|
).fetchone()
|
||||||
return dict(row) if row else None
|
return dict(row) if row else None
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -2,11 +2,56 @@
|
|||||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
from email.message import EmailMessage
|
from email.message import EmailMessage
|
||||||
|
from html import escape
|
||||||
|
from pathlib import Path
|
||||||
from smtplib import SMTP
|
from smtplib import SMTP
|
||||||
import json
|
import json
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings
|
||||||
from backend.app.database import get_connection
|
from backend.app.database import get_connection
|
||||||
|
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
|
||||||
|
|
||||||
|
LOGO_PATH = Path(__file__).resolve().parents[3] / 'frontend' / 'static' / 'logo.svg'
|
||||||
|
|
||||||
|
|
||||||
|
def _html_email(body_html: str) -> str:
|
||||||
|
public_url = settings.public_url
|
||||||
|
parsed_url = urlparse(public_url)
|
||||||
|
public_hostname = parsed_url.hostname or public_url
|
||||||
|
safe_public_url = escape(public_url, quote=True)
|
||||||
|
safe_public_hostname = escape(public_hostname)
|
||||||
|
return f'''<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<body style="margin:0;background:#1e1e2e;color:#cdd6f4;font-family:Arial,sans-serif;line-height:1.6;">
|
||||||
|
<div style="max-width:620px;margin:32px auto;padding:0 20px;">
|
||||||
|
<div style="background:#11111b;border:1px solid #45475a;border-radius:12px;overflow:hidden;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#181825;">
|
||||||
|
<tr>
|
||||||
|
<td style="padding:20px 24px;text-align:left;vertical-align:top;width:50px;">
|
||||||
|
<img src="cid:linklog-logo" alt="LinkLog" width="50" height="50" style="display:block;width:50px;height:50px;">
|
||||||
|
</td>
|
||||||
|
<td style="padding:20px 0 20px 12px;text-align:left;vertical-align:top;">
|
||||||
|
<span style="color:#cba6f7;font-family:'Asset',Georgia,serif;font-size:18px;line-height:50px;">Hello, a message from <a href="{safe_public_url}" style="color:#cba6f7;text-decoration:underline;">{safe_public_hostname}</a></span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
<div style="padding:28px 32px;">{body_html}</div>
|
||||||
|
</div>
|
||||||
|
<p style="margin:18px 0;text-align:center;color:#a6adc8;font-size:12px;">LinkLog</p>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>'''
|
||||||
|
|
||||||
|
|
||||||
|
def _add_html_body(message: EmailMessage, html_body: str) -> None:
|
||||||
|
message.add_alternative(_html_email(html_body), subtype='html')
|
||||||
|
html_part = message.get_payload()[-1]
|
||||||
|
try:
|
||||||
|
logo = LOGO_PATH.read_bytes()
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
html_part.add_related(logo, maintype='image', subtype='svg+xml', cid='<linklog-logo>')
|
||||||
|
|
||||||
|
|
||||||
def get_smtp_settings() -> dict:
|
def get_smtp_settings() -> dict:
|
||||||
@@ -22,6 +67,7 @@ def get_smtp_settings() -> dict:
|
|||||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone()
|
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone()
|
||||||
if row:
|
if row:
|
||||||
values.update(json.loads(row['value']))
|
values.update(json.loads(row['value']))
|
||||||
|
values['smtp_password'] = decrypt_secret(values['smtp_password'])
|
||||||
return values
|
return values
|
||||||
|
|
||||||
|
|
||||||
@@ -30,7 +76,7 @@ def save_smtp_settings(values: dict) -> None:
|
|||||||
conn.execute(
|
conn.execute(
|
||||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||||
('smtp', json.dumps(values)),
|
('smtp', json.dumps({**values, 'smtp_password': encrypt_secret(values['smtp_password'])})),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
@@ -40,7 +86,8 @@ def smtp_configured(smtp_values: dict | None = None) -> bool:
|
|||||||
return bool(smtp['smtp_host'] and smtp['smtp_from'])
|
return bool(smtp['smtp_host'] and smtp['smtp_from'])
|
||||||
|
|
||||||
|
|
||||||
def send_message(email: str, subject: str, body: str, smtp_values: dict | None = None) -> None:
|
def send_message(email: str, subject: str, body: str, html_body: str | None = None,
|
||||||
|
smtp_values: dict | None = None) -> None:
|
||||||
smtp = smtp_values or get_smtp_settings()
|
smtp = smtp_values or get_smtp_settings()
|
||||||
if not smtp_configured(smtp):
|
if not smtp_configured(smtp):
|
||||||
raise RuntimeError('SMTP is not configured; set LINKLOG_SMTP_HOST and LINKLOG_SMTP_FROM')
|
raise RuntimeError('SMTP is not configured; set LINKLOG_SMTP_HOST and LINKLOG_SMTP_FROM')
|
||||||
@@ -50,6 +97,8 @@ def send_message(email: str, subject: str, body: str, smtp_values: dict | None =
|
|||||||
message['From'] = smtp['smtp_from']
|
message['From'] = smtp['smtp_from']
|
||||||
message['To'] = email
|
message['To'] = email
|
||||||
message.set_content(body)
|
message.set_content(body)
|
||||||
|
if html_body:
|
||||||
|
_add_html_body(message, html_body)
|
||||||
|
|
||||||
with SMTP(smtp['smtp_host'], smtp['smtp_port'], timeout=10) as connection:
|
with SMTP(smtp['smtp_host'], smtp['smtp_port'], timeout=10) as connection:
|
||||||
if smtp['smtp_use_tls']:
|
if smtp['smtp_use_tls']:
|
||||||
@@ -60,12 +109,17 @@ def send_message(email: str, subject: str, body: str, smtp_values: dict | None =
|
|||||||
|
|
||||||
|
|
||||||
def send_verification_email(email: str, username: str, verification_url: str) -> None:
|
def send_verification_email(email: str, username: str, verification_url: str) -> None:
|
||||||
|
safe_username = escape(username)
|
||||||
|
safe_url = escape(verification_url, quote=True)
|
||||||
send_message(
|
send_message(
|
||||||
email,
|
email,
|
||||||
'Verify your LinkLog email address',
|
'Verify your LinkLog email address',
|
||||||
f'Hello {username},\n\n'
|
f'Hello {username},\n\n'
|
||||||
f'Verify your LinkLog email address by opening this link:\n{verification_url}\n\n'
|
f'Verify your LinkLog email address by opening this link:\n{verification_url}\n\n'
|
||||||
f'This link expires in {settings.email_verification_expiry_hours} hours.\n',
|
f'This link expires in {settings.email_verification_expiry_hours} hours.\n',
|
||||||
|
f'<p>Hello {safe_username},</p><p>Verify your LinkLog email address:</p>'
|
||||||
|
f'<p><a href="{safe_url}" style="display:inline-block;padding:10px 16px;background:#89b4fa;color:#11111b;text-decoration:none;border-radius:6px;">Verify email address</a></p>'
|
||||||
|
f'<p style="color:#a6adc8;font-size:14px;">This link expires in {settings.email_verification_expiry_hours} hours.</p>',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -74,15 +128,21 @@ def send_test_email(email: str, smtp_values: dict | None = None) -> None:
|
|||||||
email,
|
email,
|
||||||
'LinkLog SMTP test',
|
'LinkLog SMTP test',
|
||||||
'This is a test message from LinkLog. SMTP is configured correctly.\n',
|
'This is a test message from LinkLog. SMTP is configured correctly.\n',
|
||||||
smtp_values,
|
'<p>This is a test message from LinkLog.</p><p style="color:#a6adc8;">SMTP is configured correctly.</p>',
|
||||||
|
smtp_values=smtp_values,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def send_password_reset_email(email: str, username: str, reset_url: str) -> None:
|
def send_password_reset_email(email: str, username: str, reset_url: str) -> None:
|
||||||
|
safe_username = escape(username)
|
||||||
|
safe_url = escape(reset_url, quote=True)
|
||||||
send_message(
|
send_message(
|
||||||
email,
|
email,
|
||||||
'Reset your LinkLog password',
|
'Reset your LinkLog password',
|
||||||
f'Hello {username},\n\n'
|
f'Hello {username},\n\n'
|
||||||
f'Reset your LinkLog password by opening this link:\n{reset_url}\n\n'
|
f'Reset your LinkLog password by opening this link:\n{reset_url}\n\n'
|
||||||
f'This link expires in {settings.password_reset_expiry_hours} hours.\n',
|
f'This link expires in {settings.password_reset_expiry_hours} hours.\n',
|
||||||
|
f'<p>Hello {safe_username},</p><p>Reset your LinkLog password:</p>'
|
||||||
|
f'<p><a href="{safe_url}" style="display:inline-block;padding:10px 16px;background:#f38ba8;color:#11111b;text-decoration:none;border-radius:6px;">Reset password</a></p>'
|
||||||
|
f'<p style="color:#a6adc8;font-size:14px;">This link expires in {settings.password_reset_expiry_hours} hours.</p>',
|
||||||
)
|
)
|
||||||
@@ -109,6 +109,20 @@ def create_link(
|
|||||||
return record
|
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):
|
def list_public_links(username: str | None = None):
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
rows = conn.execute(
|
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()
|
||||||
@@ -7,18 +7,17 @@ import json
|
|||||||
from secrets import token_urlsafe
|
from secrets import token_urlsafe
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
from urllib.error import HTTPError
|
from urllib.error import HTTPError
|
||||||
from urllib.request import Request, urlopen
|
from urllib.request import Request
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings
|
||||||
from backend.app.database import get_connection
|
from backend.app.database import get_connection
|
||||||
|
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
|
||||||
|
from backend.app.services.mastodon_security import open_no_redirect, validate_public_instance
|
||||||
|
|
||||||
|
|
||||||
def normalize_instance(instance: str) -> str:
|
def normalize_instance(instance: str) -> str:
|
||||||
value = instance.strip().rstrip('/')
|
return validate_public_instance(instance)
|
||||||
if not value:
|
|
||||||
raise ValueError('Mastodon instance is required')
|
|
||||||
return value if '://' in value else f'https://{value}'
|
|
||||||
|
|
||||||
|
|
||||||
def post_form(url: str, values: dict) -> dict:
|
def post_form(url: str, values: dict) -> dict:
|
||||||
@@ -28,7 +27,7 @@ def post_form(url: str, values: dict) -> dict:
|
|||||||
headers={'Content-Type': 'application/x-www-form-urlencoded'},
|
headers={'Content-Type': 'application/x-www-form-urlencoded'},
|
||||||
method='POST',
|
method='POST',
|
||||||
)
|
)
|
||||||
with urlopen(request, timeout=10) as response:
|
with open_no_redirect(request, timeout=10) as response:
|
||||||
return json.loads(response.read().decode('utf-8'))
|
return json.loads(response.read().decode('utf-8'))
|
||||||
|
|
||||||
|
|
||||||
@@ -39,6 +38,8 @@ def start_authorization(user_id: str, instance: str) -> str:
|
|||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
|
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
|
||||||
app = json.loads(row['value']) if row else None
|
app = json.loads(row['value']) if row else None
|
||||||
|
if app and app.get('client_secret'):
|
||||||
|
app['client_secret'] = decrypt_secret(app['client_secret'])
|
||||||
if not app:
|
if not app:
|
||||||
app = post_form(f'{instance}/api/v1/apps', {
|
app = post_form(f'{instance}/api/v1/apps', {
|
||||||
'client_name': settings.mastodon_client_name,
|
'client_name': settings.mastodon_client_name,
|
||||||
@@ -50,7 +51,7 @@ def start_authorization(user_id: str, instance: str) -> str:
|
|||||||
conn.execute(
|
conn.execute(
|
||||||
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||||
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
|
||||||
(setting_name, json.dumps(app)),
|
(setting_name, json.dumps({**app, 'client_secret': encrypt_secret(app['client_secret'])})),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
state = token_urlsafe(32)
|
state = token_urlsafe(32)
|
||||||
@@ -62,7 +63,7 @@ def start_authorization(user_id: str, instance: str) -> str:
|
|||||||
(id, user_id, state_hash, instance, client_id, client_secret, redirect_uri, expires_at)
|
(id, user_id, state_hash, instance, client_id, client_secret, redirect_uri, expires_at)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||||
(str(uuid4()), user_id, sha256(state.encode()).hexdigest(), instance,
|
(str(uuid4()), user_id, sha256(state.encode()).hexdigest(), instance,
|
||||||
app['client_id'], app['client_secret'], redirect_uri, expires_at.isoformat()),
|
app['client_id'], encrypt_secret(app['client_secret']), redirect_uri, expires_at.isoformat()),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return f'{instance}/oauth/authorize?' + urlencode({
|
return f'{instance}/oauth/authorize?' + urlencode({
|
||||||
@@ -90,7 +91,7 @@ def finish_authorization(code: str, state: str) -> str:
|
|||||||
'grant_type': 'authorization_code',
|
'grant_type': 'authorization_code',
|
||||||
'code': code,
|
'code': code,
|
||||||
'client_id': record['client_id'],
|
'client_id': record['client_id'],
|
||||||
'client_secret': record['client_secret'],
|
'client_secret': decrypt_secret(record['client_secret']),
|
||||||
'redirect_uri': record['redirect_uri'],
|
'redirect_uri': record['redirect_uri'],
|
||||||
})
|
})
|
||||||
access_token = token.get('access_token')
|
access_token = token.get('access_token')
|
||||||
@@ -102,7 +103,7 @@ def finish_authorization(code: str, state: str) -> str:
|
|||||||
(record['user_id'], 'mastodon'),
|
(record['user_id'], 'mastodon'),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
config = json.loads(current['config']) if current and current['config'] else {}
|
config = json.loads(current['config']) if current and current['config'] else {}
|
||||||
config.update({'instance': record['instance'], 'access_token': access_token})
|
config.update({'instance': record['instance'], 'access_token': encrypt_secret(access_token)})
|
||||||
if current:
|
if current:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
'UPDATE user_plugin_config SET config = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND plugin_name = ?',
|
'UPDATE user_plugin_config SET config = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND plugin_name = ?',
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -7,12 +7,43 @@ import hmac
|
|||||||
import secrets
|
import secrets
|
||||||
import time
|
import time
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from backend.app.database import get_connection
|
||||||
|
|
||||||
|
|
||||||
def create_secret() -> str:
|
def create_secret() -> str:
|
||||||
return base64.b32encode(secrets.token_bytes(20)).decode('ascii').rstrip('=')
|
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:
|
def provisioning_uri(secret: str, username: str, issuer: str = 'LinkLog') -> str:
|
||||||
return f'otpauth://totp/{quote(issuer)}:{quote(username)}?secret={secret}&issuer={quote(issuer)}'
|
return f'otpauth://totp/{quote(issuer)}:{quote(username)}?secret={secret}&issuer={quote(issuer)}'
|
||||||
|
|
||||||
|
|||||||
@@ -5,9 +5,11 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
from urllib.error import HTTPError, URLError
|
from urllib.error import HTTPError, URLError
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
from urllib.request import Request, urlopen
|
from urllib.request import Request
|
||||||
|
|
||||||
from backend.app.plugins.base import BasePlugin
|
from backend.app.plugins.base import BasePlugin
|
||||||
|
from backend.app.services.secret_store import decrypt_secret
|
||||||
|
from backend.app.services.mastodon_security import open_no_redirect, validate_public_instance
|
||||||
|
|
||||||
DEFAULT_POST_PREFIX = 'From my #LinkLog: '
|
DEFAULT_POST_PREFIX = 'From my #LinkLog: '
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -47,10 +49,12 @@ class MastodonPlugin(BasePlugin):
|
|||||||
).fetchone()
|
).fetchone()
|
||||||
if row and row['config']:
|
if row and row['config']:
|
||||||
config.update(json.loads(row['config']))
|
config.update(json.loads(row['config']))
|
||||||
|
config['access_token'] = decrypt_secret(config.get('access_token', ''))
|
||||||
|
|
||||||
instance = str(config.get('instance', '')).strip().rstrip('/')
|
try:
|
||||||
if instance and '://' not in instance:
|
instance = validate_public_instance(str(config.get('instance', '')))
|
||||||
instance = f'https://{instance}'
|
except ValueError as error:
|
||||||
|
return {'status': 'failed', 'plugin': self.name, 'reason': str(error)}
|
||||||
access_token = str(config.get('access_token', '')).strip()
|
access_token = str(config.get('access_token', '')).strip()
|
||||||
if not instance or not access_token:
|
if not instance or not access_token:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -64,7 +68,9 @@ class MastodonPlugin(BasePlugin):
|
|||||||
post_prefix = f'#{str(config["hashtag"]).strip().lstrip("#")} '
|
post_prefix = f'#{str(config["hashtag"]).strip().lstrip("#")} '
|
||||||
post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX).strip()
|
post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX).strip()
|
||||||
title = str(event.get('title') or '').strip()
|
title = str(event.get('title') or '').strip()
|
||||||
status_parts = [f'{post_prefix} {title}'.strip()]
|
status_parts = [post_prefix.strip()]
|
||||||
|
if title:
|
||||||
|
status_parts.append(title)
|
||||||
if event.get('comment'):
|
if event.get('comment'):
|
||||||
status_parts.append(event['comment'])
|
status_parts.append(event['comment'])
|
||||||
if title:
|
if title:
|
||||||
@@ -90,7 +96,7 @@ class MastodonPlugin(BasePlugin):
|
|||||||
},
|
},
|
||||||
method='POST',
|
method='POST',
|
||||||
)
|
)
|
||||||
with urlopen(request, timeout=5) as response:
|
with open_no_redirect(request, timeout=5) as response:
|
||||||
response_body = response.read().decode('utf-8')
|
response_body = response.read().decode('utf-8')
|
||||||
logger.debug(
|
logger.debug(
|
||||||
'Mastodon post response: endpoint=%s status=%s body_length=%d',
|
'Mastodon post response: endpoint=%s status=%s body_length=%d',
|
||||||
@@ -135,10 +141,12 @@ class MastodonPlugin(BasePlugin):
|
|||||||
).fetchone()
|
).fetchone()
|
||||||
if row and row['config']:
|
if row and row['config']:
|
||||||
config.update(json.loads(row['config']))
|
config.update(json.loads(row['config']))
|
||||||
|
config['access_token'] = decrypt_secret(config.get('access_token', ''))
|
||||||
|
|
||||||
instance = str(config.get('instance', '')).strip().rstrip('/')
|
try:
|
||||||
if instance and '://' not in instance:
|
instance = validate_public_instance(str(config.get('instance', '')))
|
||||||
instance = f'https://{instance}'
|
except ValueError as error:
|
||||||
|
return {'status': 'failed', 'plugin': self.name, 'reason': str(error)}
|
||||||
access_token = str(config.get('access_token', '')).strip()
|
access_token = str(config.get('access_token', '')).strip()
|
||||||
post_ids = event.get('mastodon_post_ids') or []
|
post_ids = event.get('mastodon_post_ids') or []
|
||||||
if not post_ids and event.get('mastodon_post_id'):
|
if not post_ids and event.get('mastodon_post_id'):
|
||||||
@@ -153,7 +161,7 @@ class MastodonPlugin(BasePlugin):
|
|||||||
headers={'Authorization': f'Bearer {access_token}', 'User-Agent': 'LinkLog/1.0'},
|
headers={'Authorization': f'Bearer {access_token}', 'User-Agent': 'LinkLog/1.0'},
|
||||||
method='DELETE',
|
method='DELETE',
|
||||||
)
|
)
|
||||||
with urlopen(request, timeout=5) as response:
|
with open_no_redirect(request, timeout=5) as response:
|
||||||
response.read()
|
response.read()
|
||||||
return {'status': 'deleted', 'plugin': self.name, 'count': len(post_ids)}
|
return {'status': 'deleted', 'plugin': self.name, 'count': len(post_ids)}
|
||||||
except HTTPError as error:
|
except HTTPError as error:
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
## Copyright © 2026 Olaf Kolkman
|
## Copyright © 2026 Olaf Kolkman
|
||||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from hashlib import sha256
|
from hashlib import sha256
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
@@ -13,29 +13,42 @@ def hash_token(token: str) -> str:
|
|||||||
return sha256(token.encode('utf-8')).hexdigest()
|
return sha256(token.encode('utf-8')).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def issue_token(user_id: str, username: str) -> dict:
|
def _token_expiry() -> datetime:
|
||||||
token = f'token-{username}-{uuid4().hex}'
|
return datetime.now(timezone.utc) + timedelta(minutes=settings.token_expiry_minutes)
|
||||||
expires_at = datetime.now(timezone.utc).replace(microsecond=0)
|
|
||||||
expires_at = expires_at.replace(day=expires_at.day + 30 if False else expires_at.day)
|
|
||||||
# one-month expiry, held as a configured value in settings
|
def _persist_token(conn, user_id: str, token: str, token_type: str, expires_at: datetime,
|
||||||
from datetime import timedelta
|
device_id: str, family_id: str) -> None:
|
||||||
expires_at = datetime.now(timezone.utc) + timedelta(days=settings.token_expiry_days)
|
conn.execute(
|
||||||
|
'''
|
||||||
|
INSERT INTO tokens
|
||||||
|
(id, user_id, token_hash, token_type, expires_at, created_at, revoked, device_id, token_family_id)
|
||||||
|
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, 0, ?, ?)
|
||||||
|
''',
|
||||||
|
(str(uuid4()), user_id, hash_token(token), token_type, expires_at.isoformat(), device_id, family_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def issue_token(user_id: str, username: str, device_id: str | None = None) -> dict:
|
||||||
|
device_id = device_id.strip() if device_id and device_id.strip() else f'device-{uuid4().hex}'
|
||||||
|
family_id = str(uuid4())
|
||||||
|
access_token = f'token-{username}-{uuid4().hex}'
|
||||||
|
refresh_token = f'refresh-{username}-{uuid4().hex}'
|
||||||
|
access_expires_at = _token_expiry()
|
||||||
|
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
|
||||||
|
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
conn.execute(
|
_persist_token(conn, user_id, access_token, 'access', access_expires_at, device_id, family_id)
|
||||||
'''
|
_persist_token(conn, user_id, refresh_token, 'refresh', refresh_expires_at, device_id, family_id)
|
||||||
INSERT INTO tokens (id, user_id, token_hash, token_type, expires_at, created_at, revoked)
|
|
||||||
VALUES (?, ?, ?, 'access', ?, CURRENT_TIMESTAMP, 0)
|
|
||||||
''',
|
|
||||||
(str(uuid4()), user_id, hash_token(token), expires_at.isoformat())
|
|
||||||
)
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'access_token': token,
|
'access_token': access_token,
|
||||||
'token_type': 'bearer',
|
'token_type': 'bearer',
|
||||||
'expires_at': expires_at.isoformat(),
|
'expires_at': access_expires_at.isoformat(),
|
||||||
'refresh_token': f'refresh-{uuid4().hex}',
|
'refresh_token': refresh_token,
|
||||||
|
'device_id': device_id,
|
||||||
|
'token_family_id': family_id,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -45,7 +58,7 @@ def validate_token(token: str) -> dict | None:
|
|||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
'''
|
'''
|
||||||
SELECT * FROM tokens
|
SELECT * FROM tokens
|
||||||
WHERE token_hash = ? AND revoked = 0 AND expires_at > ?
|
WHERE token_hash = ? AND token_type = 'access' AND revoked = 0 AND expires_at > ?
|
||||||
''',
|
''',
|
||||||
(token_hash, datetime.now(timezone.utc).isoformat()),
|
(token_hash, datetime.now(timezone.utc).isoformat()),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
@@ -54,12 +67,64 @@ def validate_token(token: str) -> dict | None:
|
|||||||
return dict(row)
|
return dict(row)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_refresh_token(token: str, device_id: str | None = None) -> dict | None:
|
||||||
|
with get_connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
'''
|
||||||
|
SELECT * FROM tokens
|
||||||
|
WHERE token_hash = ? AND token_type = 'refresh' AND revoked = 0 AND expires_at > ?
|
||||||
|
AND (? IS NULL OR device_id = ?)
|
||||||
|
''',
|
||||||
|
(hash_token(token), datetime.now(timezone.utc).isoformat(), device_id, device_id),
|
||||||
|
).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def rotate_refresh_token(refresh_token: str, device_id: str | None = None) -> dict | None:
|
||||||
|
current = validate_refresh_token(refresh_token, device_id)
|
||||||
|
with get_connection() as conn:
|
||||||
|
if current is None:
|
||||||
|
row = conn.execute(
|
||||||
|
'SELECT token_family_id FROM tokens WHERE token_hash = ? AND token_type = ? AND token_family_id IS NOT NULL',
|
||||||
|
(hash_token(refresh_token), 'refresh'),
|
||||||
|
).fetchone()
|
||||||
|
if row:
|
||||||
|
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (row['token_family_id'],))
|
||||||
|
conn.commit()
|
||||||
|
return None
|
||||||
|
|
||||||
|
user = conn.execute('SELECT username FROM users WHERE id = ?', (current['user_id'],)).fetchone()
|
||||||
|
if user is None:
|
||||||
|
return None
|
||||||
|
family_id = current['token_family_id']
|
||||||
|
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (family_id,))
|
||||||
|
new_access = f'token-{user["username"]}-{uuid4().hex}'
|
||||||
|
new_refresh = f'refresh-{user["username"]}-{uuid4().hex}'
|
||||||
|
access_expires_at = _token_expiry()
|
||||||
|
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
|
||||||
|
_persist_token(conn, current['user_id'], new_access, 'access', access_expires_at, current['device_id'], family_id)
|
||||||
|
_persist_token(conn, current['user_id'], new_refresh, 'refresh', refresh_expires_at, current['device_id'], family_id)
|
||||||
|
conn.commit()
|
||||||
|
return {
|
||||||
|
'access_token': new_access,
|
||||||
|
'token_type': 'bearer',
|
||||||
|
'expires_at': access_expires_at.isoformat(),
|
||||||
|
'refresh_token': new_refresh,
|
||||||
|
'device_id': current['device_id'],
|
||||||
|
'user_id': current['user_id'],
|
||||||
|
'username': user['username'],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def revoke_token(token: str) -> bool:
|
def revoke_token(token: str) -> bool:
|
||||||
token_hash = hash_token(token)
|
token_hash = hash_token(token)
|
||||||
with get_connection() as conn:
|
with get_connection() as conn:
|
||||||
cursor = conn.execute(
|
cursor = conn.execute(
|
||||||
'UPDATE tokens SET revoked = 1 WHERE token_hash = ?',
|
'''UPDATE tokens SET revoked = 1
|
||||||
(token_hash,),
|
WHERE token_hash = ? OR token_family_id = (
|
||||||
|
SELECT token_family_id FROM tokens WHERE token_hash = ?
|
||||||
|
)''',
|
||||||
|
(token_hash, token_hash),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return cursor.rowcount > 0
|
return cursor.rowcount > 0
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ uvicorn==0.52.4
|
|||||||
pydantic==2.13.4
|
pydantic==2.13.4
|
||||||
jinja2==3.1.6
|
jinja2==3.1.6
|
||||||
python-multipart==0.0.20
|
python-multipart==0.0.20
|
||||||
|
Pillow==11.3.0
|
||||||
pytest==9.1.1
|
pytest==9.1.1
|
||||||
httpx==0.28.1
|
httpx==0.28.1
|
||||||
httpx2==2.12.0
|
httpx2==2.12.0
|
||||||
|
cryptography==46.0.3
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import pytest
|
|||||||
TEST_DATABASE_DIRECTORY = tempfile.TemporaryDirectory(prefix='linklog-tests-')
|
TEST_DATABASE_DIRECTORY = tempfile.TemporaryDirectory(prefix='linklog-tests-')
|
||||||
TEST_DATABASE_PATH = os.path.join(TEST_DATABASE_DIRECTORY.name, 'linklog.db')
|
TEST_DATABASE_PATH = os.path.join(TEST_DATABASE_DIRECTORY.name, 'linklog.db')
|
||||||
os.environ['LINKLOG_DATABASE_PATH'] = TEST_DATABASE_PATH
|
os.environ['LINKLOG_DATABASE_PATH'] = TEST_DATABASE_PATH
|
||||||
|
os.environ['LINKLOG_DATA_ENCRYPTION_KEY'] = 'L5M4sQYVjD1N7pT2Xk8R0aBcDeFgHiJkLmNoPqRsTuV='
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope='session', autouse=True)
|
@pytest.fixture(scope='session', autouse=True)
|
||||||
|
|||||||
+202
-19
@@ -13,6 +13,8 @@ from fastapi.testclient import TestClient
|
|||||||
from backend.app.main import app
|
from backend.app.main import app
|
||||||
from backend.app.database import get_connection
|
from backend.app.database import get_connection
|
||||||
from backend.app.services.email_service import get_smtp_settings
|
from backend.app.services.email_service import get_smtp_settings
|
||||||
|
from backend.app.services.login_throttle import clear_login_failures
|
||||||
|
from backend.app.services.otp_service import current_code
|
||||||
from backend.app.services.password_reset import create_reset_token
|
from backend.app.services.password_reset import create_reset_token
|
||||||
from backend.app.services.token_service import issue_token
|
from backend.app.services.token_service import issue_token
|
||||||
|
|
||||||
@@ -39,7 +41,7 @@ def test_login_returns_token():
|
|||||||
assert 'access_token' in payload
|
assert 'access_token' in payload
|
||||||
assert payload['token_type'] == 'bearer'
|
assert payload['token_type'] == 'bearer'
|
||||||
|
|
||||||
admin_session = client.get('/api/auth/me', params={'token': payload['access_token']})
|
admin_session = client.get('/api/auth/me', headers={'Authorization': f"Bearer {payload['access_token']}"})
|
||||||
assert admin_session.status_code == 200
|
assert admin_session.status_code == 200
|
||||||
assert admin_session.json()['is_admin'] is True
|
assert admin_session.json()['is_admin'] is True
|
||||||
|
|
||||||
@@ -47,9 +49,66 @@ def test_login_returns_token():
|
|||||||
'email': 'bob@example.com',
|
'email': 'bob@example.com',
|
||||||
'password': 'secret123',
|
'password': 'secret123',
|
||||||
}).json()['access_token']
|
}).json()['access_token']
|
||||||
user_session = client.get('/api/auth/me', params={'token': user_token})
|
user_session = client.get('/api/auth/me', headers={'Authorization': f"Bearer {user_token}"})
|
||||||
assert user_session.status_code == 200
|
assert user_session.status_code == 200
|
||||||
assert user_session.json()['is_admin'] is False
|
assert user_session.json()['is_admin'] is False
|
||||||
|
assert client.get('/api/auth/me', params={'token': payload['access_token']}).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout_requires_bearer_header_and_revokes_token_family():
|
||||||
|
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
|
||||||
|
token = login['access_token']
|
||||||
|
headers = {'Authorization': f'Bearer {token}'}
|
||||||
|
assert client.post('/api/auth/logout', json={'token': token}).status_code == 401
|
||||||
|
assert client.get('/api/auth/me', headers=headers).status_code == 200
|
||||||
|
assert client.post('/api/auth/logout', headers=headers).status_code == 200
|
||||||
|
assert client.get('/api/auth/me', headers=headers).status_code == 401
|
||||||
|
assert client.post('/api/auth/refresh', json={'refresh_token': login['refresh_token'], 'device_id': login['device_id']}).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_rate_limit_locks_out_after_five_failures_and_resets_on_success():
|
||||||
|
email = f'unknown-{uuid4().hex}@example.com'
|
||||||
|
for attempt in range(5):
|
||||||
|
response = client.post('/api/auth/login', json={'email': email, 'password': 'wrong-password'})
|
||||||
|
assert response.status_code == 401, attempt
|
||||||
|
locked = client.post('/api/auth/login', json={'email': email, 'password': 'wrong-password'})
|
||||||
|
assert locked.status_code == 429
|
||||||
|
assert int(locked.headers['Retry-After']) > 0
|
||||||
|
|
||||||
|
clear_login_failures('testclient', email)
|
||||||
|
valid = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'})
|
||||||
|
assert valid.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_refresh_token_rotates_and_reuse_revokes_family():
|
||||||
|
device_id = f'device-{uuid4().hex}'
|
||||||
|
login = client.post('/api/auth/login', json={
|
||||||
|
'email': 'alice@example.com',
|
||||||
|
'password': 'secret123',
|
||||||
|
'device_id': device_id,
|
||||||
|
})
|
||||||
|
assert login.status_code == 200
|
||||||
|
first = login.json()
|
||||||
|
|
||||||
|
rotated = client.post('/api/auth/refresh', json={
|
||||||
|
'refresh_token': first['refresh_token'],
|
||||||
|
'device_id': device_id,
|
||||||
|
})
|
||||||
|
assert rotated.status_code == 200
|
||||||
|
second = rotated.json()
|
||||||
|
assert second['refresh_token'] != first['refresh_token']
|
||||||
|
assert client.get('/api/auth/me', headers={'Authorization': f"Bearer {second['access_token']}"}).status_code == 200
|
||||||
|
|
||||||
|
reused = client.post('/api/auth/refresh', json={
|
||||||
|
'refresh_token': first['refresh_token'],
|
||||||
|
'device_id': device_id,
|
||||||
|
})
|
||||||
|
assert reused.status_code == 401
|
||||||
|
family_revoked = client.post('/api/auth/refresh', json={
|
||||||
|
'refresh_token': second['refresh_token'],
|
||||||
|
'device_id': device_id,
|
||||||
|
})
|
||||||
|
assert family_revoked.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
def test_password_hashes_are_salted_and_legacy_hashes_upgrade_on_login():
|
def test_password_hashes_are_salted_and_legacy_hashes_upgrade_on_login():
|
||||||
@@ -168,7 +227,31 @@ def test_admin_reports_smtp_validation_errors():
|
|||||||
'smtp_use_tls': False,
|
'smtp_use_tls': False,
|
||||||
})
|
})
|
||||||
assert failed_validation.status_code == 503
|
assert failed_validation.status_code == 503
|
||||||
assert 'connection refused' in failed_validation.json()['detail']
|
assert failed_validation.json()['detail'].startswith('SMTP validation failed. Reference: ')
|
||||||
|
assert 'connection refused' not in failed_validation.json()['detail']
|
||||||
|
assert failed_validation.headers['X-Request-ID']
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_id_is_preserved_and_sensitive_error_text_is_not_returned():
|
||||||
|
headers = login_headers()
|
||||||
|
with get_connection() as conn:
|
||||||
|
conn.execute('DELETE FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',))
|
||||||
|
conn.commit()
|
||||||
|
with patch('backend.app.api.admin.send_test_email', side_effect=RuntimeError('password=super-secret token=abc123')):
|
||||||
|
response = client.post(
|
||||||
|
'/api/admin/smtp/test',
|
||||||
|
headers={**headers, 'X-Request-ID': 'audit-test-123'},
|
||||||
|
json={
|
||||||
|
'smtp_host': 'smtp.example.com',
|
||||||
|
'smtp_port': 2525,
|
||||||
|
'smtp_from': 'admin@example.com',
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert response.status_code == 503
|
||||||
|
assert response.headers['X-Request-ID'] == 'audit-test-123'
|
||||||
|
assert response.json()['detail'] == 'SMTP validation failed. Reference: audit-test-123'
|
||||||
|
assert 'super-secret' not in response.text
|
||||||
|
assert 'abc123' not in response.text
|
||||||
|
|
||||||
|
|
||||||
def test_admin_can_add_list_and_remove_users():
|
def test_admin_can_add_list_and_remove_users():
|
||||||
@@ -192,6 +275,52 @@ def test_admin_can_add_list_and_remove_users():
|
|||||||
assert client.put('/api/admin/users/user-1', headers=headers, json={'is_admin': False}).status_code == 400
|
assert client.put('/api/admin/users/user-1', headers=headers, json={'is_admin': False}).status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_can_reset_another_users_otp():
|
||||||
|
admin_headers = login_headers()
|
||||||
|
user_login = client.post('/api/auth/login', json={
|
||||||
|
'email': 'bob@example.com',
|
||||||
|
'password': 'secret123',
|
||||||
|
}).json()
|
||||||
|
user_headers = {'Authorization': f"Bearer {user_login['access_token']}"}
|
||||||
|
setup = client.post('/api/user/otp/setup', headers=user_headers)
|
||||||
|
assert setup.status_code == 200
|
||||||
|
secret = setup.json()['secret']
|
||||||
|
recovery_code = setup.json()['recovery_codes'][0]
|
||||||
|
assert client.post('/api/user/otp', headers=user_headers, json={
|
||||||
|
'action': 'enable', 'code': current_code(secret),
|
||||||
|
}).status_code == 200
|
||||||
|
|
||||||
|
assert client.post('/api/admin/users/user-2/otp/reset', headers=admin_headers).json() == {
|
||||||
|
'status': 'otp_reset', 'enabled': False, 'user_id': 'user-2',
|
||||||
|
}
|
||||||
|
assert client.get('/api/user/otp', headers=user_headers).json() == {'enabled': False}
|
||||||
|
assert client.post('/api/user/otp/recover', headers=user_headers, json={
|
||||||
|
'current_password': 'secret123', 'recovery_code': recovery_code,
|
||||||
|
}).status_code == 400
|
||||||
|
assert client.post('/api/admin/users/user-2/otp/reset', headers=login_headers('bob')).status_code == 403
|
||||||
|
assert client.post('/api/admin/users/missing-user/otp/reset', headers=admin_headers).status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_security_audit_events_are_append_only_and_do_not_store_secrets():
|
||||||
|
admin_headers = login_headers()
|
||||||
|
response = client.put('/api/admin/themes', headers=admin_headers, json={'themes': ['plain-day']})
|
||||||
|
assert response.status_code == 200
|
||||||
|
with get_connection() as conn:
|
||||||
|
event = conn.execute(
|
||||||
|
'''SELECT actor_id, action, target_type, outcome, details
|
||||||
|
FROM security_audit_events
|
||||||
|
WHERE action = 'themes_updated'
|
||||||
|
ORDER BY created_at DESC, rowid DESC LIMIT 1''',
|
||||||
|
).fetchone()
|
||||||
|
assert event is not None
|
||||||
|
assert event['actor_id'] == 'user-1'
|
||||||
|
assert event['target_type'] == 'application'
|
||||||
|
assert event['outcome'] == 'success'
|
||||||
|
assert 'password' not in event['details'].lower()
|
||||||
|
assert 'token' not in event['details'].lower()
|
||||||
|
assert 'secret' not in event['details'].lower()
|
||||||
|
|
||||||
|
|
||||||
def test_new_user_must_verify_email_before_login():
|
def test_new_user_must_verify_email_before_login():
|
||||||
headers = login_headers()
|
headers = login_headers()
|
||||||
username = f'unverified-{uuid4().hex}'
|
username = f'unverified-{uuid4().hex}'
|
||||||
@@ -414,6 +543,57 @@ def test_submit_link_stores_cleaned_url_and_public_feed():
|
|||||||
assert 'alice' in users_response.json()
|
assert 'alice' in users_response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_link_updates_comment_tags_and_retriggers_plugins():
|
||||||
|
headers = login_headers()
|
||||||
|
payload = {
|
||||||
|
'title': 'Duplicate candidate',
|
||||||
|
'url': 'https://example.com/duplicate?utm_source=campaign',
|
||||||
|
'comment': 'first comment',
|
||||||
|
'tags': ['#First'],
|
||||||
|
}
|
||||||
|
first = client.post('/api/links', headers=headers, json=payload)
|
||||||
|
assert first.status_code == 201
|
||||||
|
|
||||||
|
with patch('backend.app.api.links.plugin_manager.dispatch', return_value=[]) as dispatch:
|
||||||
|
duplicate = client.post('/api/links', headers=headers, json={
|
||||||
|
**payload,
|
||||||
|
'comment': 'updated comment',
|
||||||
|
'tags': ['#Second'],
|
||||||
|
})
|
||||||
|
assert duplicate.status_code == 200
|
||||||
|
assert duplicate.json()['duplicate'] is True
|
||||||
|
assert duplicate.json()['id'] == first.json()['id']
|
||||||
|
dispatch.assert_called_once()
|
||||||
|
assert dispatch.call_args.args[0]['comment'] == 'updated comment'
|
||||||
|
assert dispatch.call_args.args[0]['tags'] == ['#Second']
|
||||||
|
feed_item = next(item for item in client.get('/api/public/feed').json() if item['id'] == first.json()['id'])
|
||||||
|
assert feed_item['comment'] == 'updated comment'
|
||||||
|
assert feed_item['tags'] == ['#Second']
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_link_check_is_authenticated_and_detects_existing_entry():
|
||||||
|
headers = login_headers()
|
||||||
|
payload = {'title': 'Check candidate', 'url': 'https://example.com/check-candidate'}
|
||||||
|
assert client.get('/api/links/check', params=payload).status_code == 401
|
||||||
|
created = client.post('/api/links', headers=headers, json=payload)
|
||||||
|
assert created.status_code == 201
|
||||||
|
check = client.get('/api/links/check', headers=headers, params=payload)
|
||||||
|
assert check.status_code == 200
|
||||||
|
assert check.json()['exists'] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_link_save_reports_plugin_posting_errors():
|
||||||
|
with patch('backend.app.api.links.plugin_manager.dispatch', return_value=[
|
||||||
|
{'status': 'failed', 'plugin': 'mastodon', 'reason': 'HTTP 503: unavailable'},
|
||||||
|
]):
|
||||||
|
response = client.post('/api/links', headers=login_headers(), json={
|
||||||
|
'title': 'Plugin error report',
|
||||||
|
'url': 'https://example.com/plugin-error-report',
|
||||||
|
})
|
||||||
|
assert response.status_code == 201
|
||||||
|
assert response.json()['plugin_errors'] == [{'plugin': 'mastodon', 'reason': 'HTTP 503: unavailable'}]
|
||||||
|
|
||||||
|
|
||||||
def test_links_support_tags_and_tag_filtering():
|
def test_links_support_tags_and_tag_filtering():
|
||||||
headers = login_headers()
|
headers = login_headers()
|
||||||
response = client.post('/api/links', headers=headers, json={
|
response = client.post('/api/links', headers=headers, json={
|
||||||
@@ -498,8 +678,7 @@ def test_only_link_owner_can_edit_link():
|
|||||||
|
|
||||||
def test_logout_revokes_token_and_admin_can_list_plugins():
|
def test_logout_revokes_token_and_admin_can_list_plugins():
|
||||||
headers = login_headers()
|
headers = login_headers()
|
||||||
token = headers['Authorization'].removeprefix('Bearer ')
|
assert client.post('/api/auth/logout', headers=headers).status_code == 200
|
||||||
assert client.post('/api/auth/logout', json={'token': token}).status_code == 200
|
|
||||||
|
|
||||||
revoked_response = client.post('/api/links', headers=headers, json={
|
revoked_response = client.post('/api/links', headers=headers, json={
|
||||||
'title': 'Should fail',
|
'title': 'Should fail',
|
||||||
@@ -548,6 +727,8 @@ def test_public_and_admin_pages_render_html():
|
|||||||
about_page = client.get('/about')
|
about_page = client.get('/about')
|
||||||
assert about_page.status_code == 200
|
assert about_page.status_code == 200
|
||||||
assert 'Save the good stuff' in about_page.text
|
assert 'Save the good stuff' in about_page.text
|
||||||
|
assert '<h2>Plugin</h2>' in about_page.text
|
||||||
|
assert 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi' in about_page.text
|
||||||
assert 'id="auth-about-link" href="/about"' in about_page.text
|
assert 'id="auth-about-link" href="/about"' in about_page.text
|
||||||
assert client.get('/admin').status_code == 200
|
assert client.get('/admin').status_code == 200
|
||||||
admin_page = client.get('/admin').text
|
admin_page = client.get('/admin').text
|
||||||
@@ -596,25 +777,26 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
|
|||||||
try:
|
try:
|
||||||
headers = login_headers()
|
headers = login_headers()
|
||||||
base_url = f'http://127.0.0.1:{server.server_port}'
|
base_url = f'http://127.0.0.1:{server.server_port}'
|
||||||
assert client.put('/api/user/plugins/mastodon', headers=headers, json={
|
with patch('backend.app.services.plugin_manager.validate_public_instance', return_value=base_url):
|
||||||
'instance': base_url,
|
assert client.put('/api/user/plugins/mastodon', headers=headers, json={
|
||||||
'access_token': 'test-token',
|
'instance': base_url,
|
||||||
'post_prefix': 'From my #LinkLog: ',
|
'access_token': 'test-token',
|
||||||
}).status_code == 200
|
'post_prefix': 'From my #LinkLog: ',
|
||||||
assert client.put('/api/admin/plugins/mastodon', headers=headers, json={'enabled': True}).status_code == 200
|
}).status_code == 200
|
||||||
|
assert client.put('/api/admin/plugins/mastodon', headers=headers, json={'enabled': True}).status_code == 200
|
||||||
|
|
||||||
response = client.post('/api/links', headers=headers, json={
|
response = client.post('/api/links', headers=headers, json={
|
||||||
'title': 'A useful page',
|
'title': 'A useful page',
|
||||||
'url': 'https://example.com/useful',
|
'url': 'https://example.com/useful',
|
||||||
'comment': 'Worth sharing',
|
'comment': 'Worth sharing',
|
||||||
'tags': ['#python', '#web'],
|
'tags': ['#python', '#web'],
|
||||||
})
|
})
|
||||||
|
|
||||||
assert response.status_code == 201
|
assert response.status_code == 201
|
||||||
assert received['path'] == '/api/v1/statuses'
|
assert received['path'] == '/api/v1/statuses'
|
||||||
assert received['authorization'] == 'Bearer test-token'
|
assert received['authorization'] == 'Bearer test-token'
|
||||||
assert received['content_type'] == 'application/x-www-form-urlencoded'
|
assert received['content_type'] == 'application/x-www-form-urlencoded'
|
||||||
assert received['body'] == {'status': ['From my #LinkLog: A useful page\n\nWorth sharing\n\nfrom: https://example.com/useful\n\n#python #web']}
|
assert received['body'] == {'status': ['From my #LinkLog:\n\nA useful page\n\nWorth sharing\n\nfrom: https://example.com/useful\n\n#python #web']}
|
||||||
posted_item = next(item for item in client.get('/api/public/feed/alice', headers=headers).json() if item['id'] == response.json()['id'])
|
posted_item = next(item for item in client.get('/api/public/feed/alice', headers=headers).json() if item['id'] == response.json()['id'])
|
||||||
assert posted_item['mastodon_posted'] is True
|
assert posted_item['mastodon_posted'] is True
|
||||||
finally:
|
finally:
|
||||||
@@ -631,7 +813,8 @@ def test_mastodon_post_without_title_omits_source_line():
|
|||||||
plugin = MastodonPlugin()
|
plugin = MastodonPlugin()
|
||||||
plugin.initialize({'instance': 'https://mastodon.example', 'access_token': 'test-token'})
|
plugin.initialize({'instance': 'https://mastodon.example', 'access_token': 'test-token'})
|
||||||
|
|
||||||
with patch('backend.app.services.plugin_manager.urlopen', return_value=response) as open_url:
|
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({
|
result = plugin.handle_event({
|
||||||
'url': 'https://example.com/useful',
|
'url': 'https://example.com/useful',
|
||||||
'title': '',
|
'title': '',
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -10,7 +10,7 @@ def test_database_migrations_are_versioned_and_idempotent():
|
|||||||
connection = sqlite3.connect(':memory:')
|
connection = sqlite3.connect(':memory:')
|
||||||
|
|
||||||
apply_migrations(connection)
|
apply_migrations(connection)
|
||||||
assert get_schema_version(connection) == 11
|
assert get_schema_version(connection) == 17
|
||||||
tables = {
|
tables = {
|
||||||
row[0]
|
row[0]
|
||||||
for row in connection.execute(
|
for row in connection.execute(
|
||||||
@@ -27,6 +27,6 @@ def test_database_migrations_are_versioned_and_idempotent():
|
|||||||
assert set(DEFAULT_TAGS) <= seeded_tags
|
assert set(DEFAULT_TAGS) <= seeded_tags
|
||||||
|
|
||||||
apply_migrations(connection)
|
apply_migrations(connection)
|
||||||
assert get_schema_version(connection) == 11
|
assert get_schema_version(connection) == 17
|
||||||
|
|
||||||
connection.close()
|
connection.close()
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from backend.app.services.email_service import send_test_email, send_verification_email
|
from backend.app.services.email_service import send_password_reset_email, send_test_email, send_verification_email
|
||||||
|
|
||||||
|
|
||||||
def test_send_verification_email_uses_smtp_settings(monkeypatch):
|
def test_send_verification_email_uses_smtp_settings(monkeypatch):
|
||||||
@@ -15,6 +15,7 @@ def test_send_verification_email_uses_smtp_settings(monkeypatch):
|
|||||||
monkeypatch.setattr(settings, 'smtp_username', 'mailer')
|
monkeypatch.setattr(settings, 'smtp_username', 'mailer')
|
||||||
monkeypatch.setattr(settings, 'smtp_password', 'secret')
|
monkeypatch.setattr(settings, 'smtp_password', 'secret')
|
||||||
monkeypatch.setattr(settings, 'smtp_use_tls', True)
|
monkeypatch.setattr(settings, 'smtp_use_tls', True)
|
||||||
|
monkeypatch.setattr(settings, 'public_url', 'https://linklog.example')
|
||||||
|
|
||||||
with patch('backend.app.services.email_service.SMTP') as smtp_class:
|
with patch('backend.app.services.email_service.SMTP') as smtp_class:
|
||||||
smtp = smtp_class.return_value.__enter__.return_value
|
smtp = smtp_class.return_value.__enter__.return_value
|
||||||
@@ -25,7 +26,22 @@ def test_send_verification_email_uses_smtp_settings(monkeypatch):
|
|||||||
smtp.login.assert_called_once_with('mailer', 'secret')
|
smtp.login.assert_called_once_with('mailer', 'secret')
|
||||||
message = smtp.send_message.call_args.args[0]
|
message = smtp.send_message.call_args.args[0]
|
||||||
assert message['To'] == 'user@example.com'
|
assert message['To'] == 'user@example.com'
|
||||||
assert 'https://linklog.example/verify' in message.get_content()
|
assert 'https://linklog.example/verify' in message.get_body(preferencelist=('plain',)).get_content()
|
||||||
|
html = message.get_body(preferencelist=('html',)).get_content()
|
||||||
|
assert 'cid:linklog-logo' in html
|
||||||
|
assert 'width="50" height="50"' in html
|
||||||
|
assert 'font-family:\'Asset\',Georgia,serif' in html
|
||||||
|
assert 'Hello, a message from' in html
|
||||||
|
assert 'vertical-align:top' in html
|
||||||
|
assert 'padding:20px 0 20px 12px' in html
|
||||||
|
assert 'font-size:18px' in html
|
||||||
|
assert 'href="https://linklog.example"' in html
|
||||||
|
assert '>linklog.example</a>' in html
|
||||||
|
assert any(
|
||||||
|
part.get_content_type() == 'image/svg+xml'
|
||||||
|
and part['Content-ID'] == '<linklog-logo>'
|
||||||
|
for part in message.walk()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_send_test_email_uses_configured_recipient(monkeypatch):
|
def test_send_test_email_uses_configured_recipient(monkeypatch):
|
||||||
@@ -40,3 +56,35 @@ def test_send_test_email_uses_configured_recipient(monkeypatch):
|
|||||||
message = smtp.send_message.call_args.args[0]
|
message = smtp.send_message.call_args.args[0]
|
||||||
assert message['To'] == 'admin@example.com'
|
assert message['To'] == 'admin@example.com'
|
||||||
assert message['Subject'] == 'LinkLog SMTP test'
|
assert message['Subject'] == 'LinkLog SMTP test'
|
||||||
|
assert message.get_body(preferencelist=('html',)) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_password_reset_email_escapes_html_and_includes_logo(monkeypatch):
|
||||||
|
from backend.app.core.config import settings
|
||||||
|
|
||||||
|
monkeypatch.setattr(settings, 'smtp_host', 'smtp.example.com')
|
||||||
|
monkeypatch.setattr(settings, 'smtp_from', 'LinkLog <no-reply@example.com>')
|
||||||
|
with patch('backend.app.services.email_service.SMTP') as smtp_class:
|
||||||
|
smtp = smtp_class.return_value.__enter__.return_value
|
||||||
|
send_password_reset_email('user@example.com', '<User>', 'https://linklog.example/reset?x=1&y=2')
|
||||||
|
|
||||||
|
message = smtp.send_message.call_args.args[0]
|
||||||
|
html = message.get_body(preferencelist=('html',)).get_content()
|
||||||
|
assert '<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,9 +1,14 @@
|
|||||||
## Copyright © 2026 Olaf Kolkman
|
## Copyright © 2026 Olaf Kolkman
|
||||||
## SPDX-License-Identifier: GPL-3.0-or-later
|
## SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
|
from PIL import Image
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
from backend.app.main import app
|
from backend.app.main import app
|
||||||
|
from backend.app.database import get_connection
|
||||||
from backend.app.services.otp_service import current_code
|
from backend.app.services.otp_service import current_code
|
||||||
|
|
||||||
|
|
||||||
@@ -45,6 +50,9 @@ def test_user_config_api_and_profile_page():
|
|||||||
assert '<a id="auth-username" class="user-name" href="/">' in page_response.text
|
assert '<a id="auth-username" class="user-name" href="/">' in page_response.text
|
||||||
assert 'id="auth-avatar"' not in page_response.text
|
assert 'id="auth-avatar"' not in page_response.text
|
||||||
assert 'name="new_password_confirmation"' in page_response.text
|
assert 'name="new_password_confirmation"' in page_response.text
|
||||||
|
assert 'id="additional-email-form"' in page_response.text
|
||||||
|
assert 'If you have not downloaded the plugin yet' in page_response.text
|
||||||
|
assert 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi' in page_response.text
|
||||||
|
|
||||||
bob_login = client.post('/api/auth/login', json={
|
bob_login = client.post('/api/auth/login', json={
|
||||||
'email': 'bob@example.com',
|
'email': 'bob@example.com',
|
||||||
@@ -65,15 +73,29 @@ def test_user_config_api_and_profile_page():
|
|||||||
'new_password': 'secret123',
|
'new_password': 'secret123',
|
||||||
}, headers=bob_headers).status_code == 200
|
}, headers=bob_headers).status_code == 200
|
||||||
|
|
||||||
|
image_buffer = BytesIO()
|
||||||
|
Image.new('RGB', (2, 2), 'red').save(image_buffer, format='JPEG')
|
||||||
upload_response = client.post(
|
upload_response = client.post(
|
||||||
'/api/user/avatar',
|
'/api/user/avatar',
|
||||||
headers=headers,
|
headers=headers,
|
||||||
files={'avatar': ('avatar.png', b'fake-png-data', 'image/png')},
|
files={'avatar': ('avatar.jpg', image_buffer.getvalue(), 'image/jpeg')},
|
||||||
)
|
)
|
||||||
assert upload_response.status_code == 200
|
assert upload_response.status_code == 200
|
||||||
avatar_url = upload_response.json()['avatar_url']
|
avatar_url = upload_response.json()['avatar_url']
|
||||||
assert avatar_url.startswith('/media/user-1.png')
|
assert avatar_url.startswith('/media/user-1.png')
|
||||||
assert client.get(avatar_url).content == b'fake-png-data'
|
stored_avatar = client.get(avatar_url)
|
||||||
|
assert stored_avatar.status_code == 200
|
||||||
|
assert stored_avatar.headers['content-type'] == 'image/png'
|
||||||
|
with Image.open(BytesIO(stored_avatar.content)) as image:
|
||||||
|
assert image.format == 'PNG'
|
||||||
|
assert image.size == (2, 2)
|
||||||
|
|
||||||
|
rejected_upload = client.post(
|
||||||
|
'/api/user/avatar',
|
||||||
|
headers=headers,
|
||||||
|
files={'avatar': ('avatar.png', b'fake-png-data', 'image/png')},
|
||||||
|
)
|
||||||
|
assert rejected_upload.status_code == 415
|
||||||
|
|
||||||
updated_profile = client.get('/api/user/me', headers=headers).json()
|
updated_profile = client.get('/api/user/me', headers=headers).json()
|
||||||
assert updated_profile['avatar_url'] == avatar_url
|
assert updated_profile['avatar_url'] == avatar_url
|
||||||
@@ -86,6 +108,8 @@ def test_user_can_enable_and_use_otp():
|
|||||||
assert setup.status_code == 200
|
assert setup.status_code == 200
|
||||||
secret = setup.json()['secret']
|
secret = setup.json()['secret']
|
||||||
assert setup.json()['otpauth_url'].startswith('otpauth://totp/')
|
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={
|
enabled = client.post('/api/user/otp', headers=headers, json={
|
||||||
'action': 'enable', 'code': current_code(secret),
|
'action': 'enable', 'code': current_code(secret),
|
||||||
@@ -100,7 +124,66 @@ def test_user_can_enable_and_use_otp():
|
|||||||
assert otp_login.status_code == 200
|
assert otp_login.status_code == 200
|
||||||
|
|
||||||
disabled = client.post('/api/user/otp', headers=headers, json={
|
disabled = client.post('/api/user/otp', headers=headers, json={
|
||||||
'action': 'disable', 'code': current_code(secret),
|
'action': 'disable', 'code': current_code(secret), 'current_password': 'secret123',
|
||||||
})
|
})
|
||||||
assert disabled.status_code == 200
|
assert disabled.status_code == 200
|
||||||
assert disabled.json()['enabled'] is False
|
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()
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ services:
|
|||||||
app:
|
app:
|
||||||
image: git.kolkman.org/olaf/link-log:development # or :latest or a version-tag
|
image: git.kolkman.org/olaf/link-log:development # or :latest or a version-tag
|
||||||
container_name: ${APP_CONTAINER_NAME:-linklog-app}
|
container_name: ${APP_CONTAINER_NAME:-linklog-app}
|
||||||
ports:
|
|
||||||
- "${APP_PORT:-8000}:8000"
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./linklog_data:/app/backend/data
|
- ./linklog_data:/app/backend/data
|
||||||
environment:
|
environment:
|
||||||
@@ -13,7 +11,8 @@ services:
|
|||||||
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
|
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
|
||||||
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
|
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
|
||||||
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
|
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
|
||||||
LINKLOG_TOKEN_EXPIRY_DAYS: ${LINKLOG_TOKEN_EXPIRY_DAYS:-30}
|
LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
|
||||||
|
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
|
||||||
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
|
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
|
||||||
LINKLOG_SMTP_HOST: ${LINKLOG_SMTP_HOST:-smtp.example.com}
|
LINKLOG_SMTP_HOST: ${LINKLOG_SMTP_HOST:-smtp.example.com}
|
||||||
LINKLOG_SMTP_PORT: ${LINKLOG_SMTP_PORT:-587}
|
LINKLOG_SMTP_PORT: ${LINKLOG_SMTP_PORT:-587}
|
||||||
|
|||||||
@@ -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}
|
||||||
+6
-6
@@ -7,8 +7,6 @@ services:
|
|||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: ${APP_CONTAINER_NAME:-linklog-app}
|
container_name: ${APP_CONTAINER_NAME:-linklog-app}
|
||||||
ports:
|
|
||||||
- "${APP_PORT:-8000}:8000"
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./linklog_data:/app/backend/data
|
- ./linklog_data:/app/backend/data
|
||||||
environment:
|
environment:
|
||||||
@@ -16,9 +14,11 @@ services:
|
|||||||
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
|
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
|
||||||
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
|
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
|
||||||
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
|
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
|
||||||
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-localhost}
|
LINKLOG_DATA_ENCRYPTION_KEY: ${LINKLOG_DATA_ENCRYPTION_KEY:?Set LINKLOG_DATA_ENCRYPTION_KEY in .env}
|
||||||
|
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
|
||||||
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-INFO}
|
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-INFO}
|
||||||
LINKLOG_TOKEN_EXPIRY_DAYS: ${LINKLOG_TOKEN_EXPIRY_DAYS:-30}
|
LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
|
||||||
|
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
|
||||||
LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
|
LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
|
||||||
restart: ${APP_RESTART_POLICY:-unless-stopped}
|
restart: ${APP_RESTART_POLICY:-unless-stopped}
|
||||||
healthcheck:
|
healthcheck:
|
||||||
@@ -35,10 +35,10 @@ services:
|
|||||||
|
|
||||||
|
|
||||||
traefik.http.routers.linklog.entrypoints: web
|
traefik.http.routers.linklog.entrypoints: web
|
||||||
traefik.http.routers.linklog.rule: Host(`${LINKLOG_PUBLIC_URL:-localhost}`)
|
traefik.http.routers.linklog.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
|
||||||
traefik.http.routers.linklog.middlewares: web-https-redirect,servicests
|
traefik.http.routers.linklog.middlewares: web-https-redirect,servicests
|
||||||
traefik.http.routers.linklog-secure.entrypoints: websecure
|
traefik.http.routers.linklog-secure.entrypoints: websecure
|
||||||
traefik.http.routers.linklog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-localhost}`)
|
traefik.http.routers.linklog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
|
||||||
traefik.http.routers.linklog-secure.tls: true
|
traefik.http.routers.linklog-secure.tls: true
|
||||||
traefik.http.routers.linklog-secure.middlewares: servicests
|
traefik.http.routers.linklog-secure.middlewares: servicests
|
||||||
|
|
||||||
|
|||||||
@@ -152,6 +152,11 @@ function renderUsers(users) {
|
|||||||
privilegeLabel.append(privilegeCheckbox, document.createTextNode(' Administrator'));
|
privilegeLabel.append(privilegeCheckbox, document.createTextNode(' Administrator'));
|
||||||
row.append(label, privilegeLabel);
|
row.append(label, privilegeLabel);
|
||||||
if (!isCurrentUser) {
|
if (!isCurrentUser) {
|
||||||
|
const otpButton = document.createElement('button');
|
||||||
|
otpButton.type = 'button';
|
||||||
|
otpButton.textContent = 'Reset OTP';
|
||||||
|
otpButton.addEventListener('click', () => resetUserOtp(user, otpButton));
|
||||||
|
row.append(otpButton);
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
button.type = 'button';
|
button.type = 'button';
|
||||||
button.className = 'danger-button';
|
button.className = 'danger-button';
|
||||||
@@ -163,6 +168,27 @@ function renderUsers(users) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function resetUserOtp(user, button) {
|
||||||
|
if (!window.confirm(`Disable OTP for ${user.username}?`)) return;
|
||||||
|
button.disabled = true;
|
||||||
|
const status = document.querySelector('#user-status');
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/admin/users/${encodeURIComponent(user.id)}/otp/reset`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: authHeaders(),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(await responseError(response, `Request failed (${response.status})`));
|
||||||
|
}
|
||||||
|
status.textContent = `OTP disabled for ${user.username}.`;
|
||||||
|
status.style.color = '#94e2d5';
|
||||||
|
} catch (error) {
|
||||||
|
status.textContent = `Could not reset OTP for ${user.username}: ${error.message}`;
|
||||||
|
status.style.color = '#f38ba8';
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function loadUsers() {
|
async function loadUsers() {
|
||||||
const response = await fetch('/api/admin/users', {headers: authHeaders()});
|
const response = await fetch('/api/admin/users', {headers: authHeaders()});
|
||||||
if (!response.ok) throw new Error('Could not load users');
|
if (!response.ok) throw new Error('Could not load users');
|
||||||
@@ -190,7 +216,7 @@ async function loadAdminState() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const sessionResponse = await fetch(`/api/auth/me?token=${encodeURIComponent(accessToken)}`);
|
const sessionResponse = await fetch('/api/auth/me', {headers: authHeaders()});
|
||||||
if (!sessionResponse.ok) {
|
if (!sessionResponse.ok) {
|
||||||
localStorage.removeItem('linklogAccessToken');
|
localStorage.removeItem('linklogAccessToken');
|
||||||
showSignedOutState();
|
showSignedOutState();
|
||||||
|
|||||||
@@ -47,7 +47,7 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
fetch(`/api/auth/me?token=${encodeURIComponent(token)}`)
|
fetch('/api/auth/me', {headers: {Authorization: `Bearer ${token}`}})
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
if (!response.ok) throw new Error('Session expired');
|
if (!response.ok) throw new Error('Session expired');
|
||||||
return response.json();
|
return response.json();
|
||||||
|
|||||||
@@ -12,8 +12,7 @@ logoutButton.addEventListener('click', async () => {
|
|||||||
if (token) {
|
if (token) {
|
||||||
await fetch('/api/auth/logout', {
|
await fetch('/api/auth/logout', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {Authorization: `Bearer ${token}`},
|
||||||
body: JSON.stringify({token}),
|
|
||||||
}).catch(() => undefined);
|
}).catch(() => undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+102
-3
@@ -12,12 +12,17 @@ const mastodonConnectButton = document.querySelector('#mastodon-connect');
|
|||||||
const otpSetupButton = document.querySelector('#otp-setup');
|
const otpSetupButton = document.querySelector('#otp-setup');
|
||||||
const otpEnableButton = document.querySelector('#otp-enable');
|
const otpEnableButton = document.querySelector('#otp-enable');
|
||||||
const otpDisableButton = document.querySelector('#otp-disable');
|
const otpDisableButton = document.querySelector('#otp-disable');
|
||||||
|
const otpRecoverButton = document.querySelector('#otp-recover');
|
||||||
const otpProvisioning = document.querySelector('#otp-provisioning');
|
const otpProvisioning = document.querySelector('#otp-provisioning');
|
||||||
const otpDisabled = document.querySelector('#otp-disabled');
|
const otpDisabled = document.querySelector('#otp-disabled');
|
||||||
const otpEnabled = document.querySelector('#otp-enabled');
|
const otpEnabled = document.querySelector('#otp-enabled');
|
||||||
const otpSecret = document.querySelector('#otp-secret');
|
const otpSecret = document.querySelector('#otp-secret');
|
||||||
const otpUri = document.querySelector('#otp-uri');
|
const otpUri = document.querySelector('#otp-uri');
|
||||||
|
const otpRecoveryCodes = document.querySelector('#otp-recovery-codes');
|
||||||
const otpStatus = document.querySelector('#otp-status');
|
const otpStatus = document.querySelector('#otp-status');
|
||||||
|
const emailAddressList = document.querySelector('#email-address-list');
|
||||||
|
const additionalEmailForm = document.querySelector('#additional-email-form');
|
||||||
|
const emailAddressStatus = document.querySelector('#email-address-status');
|
||||||
|
|
||||||
function authHeaders(includeJson = false) {
|
function authHeaders(includeJson = false) {
|
||||||
return {
|
return {
|
||||||
@@ -37,6 +42,80 @@ function setOtpStatus(message, isError = false) {
|
|||||||
otpStatus.style.color = isError ? '#b91c1c' : '#166534';
|
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() {
|
async function loadOtp() {
|
||||||
const response = await fetch('/api/user/otp', {headers: authHeaders()});
|
const response = await fetch('/api/user/otp', {headers: authHeaders()});
|
||||||
if (!response.ok) throw new Error('Could not load one-time password settings');
|
if (!response.ok) throw new Error('Could not load one-time password settings');
|
||||||
@@ -54,6 +133,7 @@ otpSetupButton.addEventListener('click', async () => {
|
|||||||
}
|
}
|
||||||
otpSecret.textContent = result.secret;
|
otpSecret.textContent = result.secret;
|
||||||
otpUri.href = result.otpauth_url;
|
otpUri.href = result.otpauth_url;
|
||||||
|
otpRecoveryCodes.textContent = result.recovery_codes.join('\n');
|
||||||
otpProvisioning.classList.remove('hidden');
|
otpProvisioning.classList.remove('hidden');
|
||||||
setOtpStatus('Enter a code from your authenticator app to confirm setup.');
|
setOtpStatus('Enter a code from your authenticator app to confirm setup.');
|
||||||
});
|
});
|
||||||
@@ -76,8 +156,9 @@ otpEnableButton.addEventListener('click', async () => {
|
|||||||
|
|
||||||
otpDisableButton.addEventListener('click', async () => {
|
otpDisableButton.addEventListener('click', async () => {
|
||||||
const code = document.querySelector('#otp-disable-code').value.trim();
|
const code = document.querySelector('#otp-disable-code').value.trim();
|
||||||
|
const currentPassword = document.querySelector('#otp-current-password').value;
|
||||||
const response = await fetch('/api/user/otp', {
|
const response = await fetch('/api/user/otp', {
|
||||||
method: 'POST', headers: authHeaders(true), body: JSON.stringify({action: 'disable', code}),
|
method: 'POST', headers: authHeaders(true), body: JSON.stringify({action: 'disable', code, current_password: currentPassword}),
|
||||||
});
|
});
|
||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -90,12 +171,30 @@ otpDisableButton.addEventListener('click', async () => {
|
|||||||
setOtpStatus('One-time password disabled.');
|
setOtpStatus('One-time password disabled.');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
otpRecoverButton.addEventListener('click', async () => {
|
||||||
|
const currentPassword = document.querySelector('#otp-current-password').value;
|
||||||
|
const recoveryCode = document.querySelector('#otp-recovery-code').value.trim();
|
||||||
|
const response = await fetch('/api/user/otp/recover', {
|
||||||
|
method: 'POST', headers: authHeaders(true), body: JSON.stringify({current_password: currentPassword, recovery_code: recoveryCode}),
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok) {
|
||||||
|
setOtpStatus(result.detail || 'Could not recover one-time password access.', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
otpDisabled.classList.remove('hidden');
|
||||||
|
otpEnabled.classList.add('hidden');
|
||||||
|
document.querySelector('#otp-current-password').value = '';
|
||||||
|
document.querySelector('#otp-recovery-code').value = '';
|
||||||
|
setOtpStatus('One-time password access recovered.');
|
||||||
|
});
|
||||||
|
|
||||||
async function loadProfile() {
|
async function loadProfile() {
|
||||||
const response = await fetch('/api/user/me', {headers: authHeaders()});
|
const response = await fetch('/api/user/me', {headers: authHeaders()});
|
||||||
if (!response.ok) throw new Error('Could not load profile');
|
if (!response.ok) throw new Error('Could not load profile');
|
||||||
const profile = await response.json();
|
const profile = await response.json();
|
||||||
document.querySelector('#username').textContent = profile.username || '';
|
document.querySelector('#username').textContent = profile.username || '';
|
||||||
document.querySelector('#email').value = profile.email || '';
|
document.querySelector('#email').textContent = profile.email || '';
|
||||||
document.querySelector('#bio').value = profile.bio || '';
|
document.querySelector('#bio').value = profile.bio || '';
|
||||||
const avatarPreview = document.querySelector('#avatar-preview');
|
const avatarPreview = document.querySelector('#avatar-preview');
|
||||||
if (profile.avatar_url) {
|
if (profile.avatar_url) {
|
||||||
@@ -211,7 +310,7 @@ passwordForm.addEventListener('submit', async (event) => {
|
|||||||
if (response.ok) passwordForm.reset();
|
if (response.ok) passwordForm.reset();
|
||||||
});
|
});
|
||||||
|
|
||||||
Promise.all([loadProfile(), loadMastodonConfig(), loadOtp()]).catch((error) => {
|
Promise.all([loadProfile(), loadMastodonConfig(), loadOtp(), loadEmailAddresses()]).catch((error) => {
|
||||||
setStatus('#profile-status', accessToken ? error.message : 'Please sign in first.', true);
|
setStatus('#profile-status', accessToken ? error.message : 'Please sign in first.', true);
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -430,6 +430,27 @@ button:focus-visible {
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.email-address-list {
|
||||||
|
display: grid;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.email-address-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding: 8px 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.email-address-row button {
|
||||||
|
min-width: 0;
|
||||||
|
padding: 5px 9px;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
}
|
||||||
|
|
||||||
.settings-panel textarea {
|
.settings-panel textarea {
|
||||||
min-height: 110px;
|
min-height: 110px;
|
||||||
resize: vertical;
|
resize: vertical;
|
||||||
|
|||||||
@@ -52,8 +52,14 @@
|
|||||||
<p>LinkLog is open source software. You can run your own instance, or contribute to the project on
|
<p>LinkLog is open source software. You can run your own instance, or contribute to the project on
|
||||||
<a href="https://git.kolkman.org/olaf/Link-Log">my repository</a>.</p>
|
<a href="https://git.kolkman.org/olaf/Link-Log">my repository</a>.</p>
|
||||||
</section>
|
</section>
|
||||||
|
<section class="link-item">
|
||||||
|
<h2>Plugin</h2>
|
||||||
|
<p>Install the Firefox plugin to save links directly from your browser. <a
|
||||||
|
href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi"
|
||||||
|
download>Download and install the Plugin</a>.</p>
|
||||||
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=3"></script>
|
<script src="/static/logout.js?v=3"></script>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
|
|||||||
@@ -115,7 +115,7 @@
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=2"></script>
|
<script src="/static/logout.js?v=2"></script>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
|
|||||||
@@ -76,7 +76,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
<section id="feed" class="feed" aria-live="polite"></section>
|
<section id="feed" class="feed" aria-live="polite"></section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
|
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=3"></script>
|
<script src="/static/logout.js?v=3"></script>
|
||||||
|
|||||||
@@ -44,7 +44,7 @@
|
|||||||
<div id="label-list" class="plugin-list"></div>
|
<div id="label-list" class="plugin-list"></div>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=3"></script>
|
<script src="/static/logout.js?v=3"></script>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
|
|||||||
@@ -55,7 +55,7 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
|
||||||
<script src="/static/auth-header.js?v=3"></script>
|
<script src="/static/auth-header.js?v=3"></script>
|
||||||
<script src="/static/logout.js?v=3"></script>
|
<script src="/static/logout.js?v=3"></script>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
|
|||||||
@@ -42,7 +42,7 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<footer class="site-footer">Copyright © 2026 Olaf Kolkman</footer>
|
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman</footer>
|
||||||
<script src="/static/theme.js?v=1"></script>
|
<script src="/static/theme.js?v=1"></script>
|
||||||
<script src="/static/setup.js"></script>
|
<script src="/static/setup.js"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -2,127 +2,155 @@
|
|||||||
<!-- Copyright © 2026 Olaf Kolkman -->
|
<!-- Copyright © 2026 Olaf Kolkman -->
|
||||||
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
<head>
|
||||||
<title>LinkLog Profile</title>
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<title>LinkLog Profile</title>
|
||||||
<link rel="stylesheet" href="/static/style.css" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
</head>
|
<link rel="stylesheet" href="/static/style.css" />
|
||||||
<body>
|
</head>
|
||||||
<header class="site-header">
|
|
||||||
<div class="container">
|
<body>
|
||||||
<div class="header-row">
|
<header class="site-header">
|
||||||
<div>
|
<div class="container">
|
||||||
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
<div class="header-row">
|
||||||
<h1>Profile</h1>
|
<div>
|
||||||
</div>
|
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
|
||||||
<div class="header-actions">
|
<h1>Profile</h1>
|
||||||
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
|
</div>
|
||||||
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
|
<div class="header-actions">
|
||||||
<a id="auth-home-link" href="/">Home</a>
|
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
|
||||||
<a id="auth-about-link" href="/about">About</a>
|
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
|
||||||
<a id="auth-login-button" href="/login">Sign in</a>
|
<a id="auth-home-link" href="/">Home</a>
|
||||||
<a id="auth-profile-link" class="hidden" href="/profile">Profile</a>
|
<a id="auth-about-link" href="/about">About</a>
|
||||||
<a id="auth-labels-link" class="hidden" href="/labels">Labels</a>
|
<a id="auth-login-button" href="/login">Sign in</a>
|
||||||
<a id="auth-admin-link" class="hidden" href="/admin">Admin</a>
|
<a id="auth-profile-link" class="hidden" href="/profile">Profile</a>
|
||||||
<div id="auth-session" class="auth-session hidden">
|
<a id="auth-labels-link" class="hidden" href="/labels">Labels</a>
|
||||||
<a id="auth-username" class="user-name" href="/"></a>
|
<a id="auth-admin-link" class="hidden" href="/admin">Admin</a>
|
||||||
</div>
|
<div id="auth-session" class="auth-session hidden">
|
||||||
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
|
<a id="auth-username" class="user-name" href="/"></a>
|
||||||
</nav>
|
</div>
|
||||||
</div>
|
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
|
||||||
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
<main class="container">
|
<main class="container">
|
||||||
<section class="link-item settings-panel">
|
<section class="link-item settings-panel">
|
||||||
<h2>Profile Settings</h2>
|
<h2>Profile Settings</h2>
|
||||||
<form id="profile-form">
|
<form id="profile-form">
|
||||||
<label>
|
<label>
|
||||||
Username
|
Username
|
||||||
<output id="username" class="readonly-value">Loading...</output>
|
<output id="username" class="readonly-value">Loading...</output>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
Email
|
Email
|
||||||
<input id="email" name="email" type="email" required />
|
<output id="email" class="readonly-value">Loading...</output>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
Bio
|
Bio
|
||||||
<textarea id="bio" name="bio" rows="4"></textarea>
|
<textarea id="bio" name="bio" rows="4"></textarea>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
Avatar image
|
Avatar image
|
||||||
<input id="avatar-file" name="avatar" type="file" accept="image/png,image/jpeg,image/gif,image/webp" />
|
<input id="avatar-file" name="avatar" type="file" accept="image/png,image/jpeg,image/gif,image/webp" />
|
||||||
</label>
|
</label>
|
||||||
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" />
|
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" />
|
||||||
<button type="submit">Save profile</button>
|
<button type="submit">Save profile</button>
|
||||||
<p id="profile-status" class="status" role="status"></p>
|
<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>
|
||||||
</form>
|
<p id="profile-status" class="status" role="status"></p>
|
||||||
</section>
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="link-item settings-panel">
|
<section class="link-item settings-panel">
|
||||||
<h2>Password</h2>
|
<h2>Email addresses</h2>
|
||||||
<form id="password-form">
|
<div id="email-address-list" class="email-address-list" aria-live="polite">Loading email addresses...</div>
|
||||||
<label>
|
<form id="additional-email-form">
|
||||||
Current password
|
<label>
|
||||||
<input name="current_password" type="password" autocomplete="current-password" required />
|
Additional email address
|
||||||
</label>
|
<input name="email" type="email" required />
|
||||||
<label>
|
</label>
|
||||||
New password
|
<button type="submit">Add email address</button>
|
||||||
<input name="new_password" type="password" minlength="8" autocomplete="new-password" required />
|
<p id="email-address-status" class="status" role="status"></p>
|
||||||
</label>
|
</form>
|
||||||
<label>
|
</section>
|
||||||
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">
|
<section class="link-item settings-panel">
|
||||||
<h2>One-time password</h2>
|
<h2>Password</h2>
|
||||||
<p>Use an authenticator app to add a second sign-in step.</p>
|
<form id="password-form">
|
||||||
<div id="otp-disabled">
|
<label>
|
||||||
<button id="otp-setup" type="button">Set up one-time password</button>
|
Current password
|
||||||
<div id="otp-provisioning" class="hidden">
|
<input name="current_password" type="password" autocomplete="current-password" required />
|
||||||
<p>Scan this QR code or enter the secret in your authenticator app:</p>
|
</label>
|
||||||
<code id="otp-secret"></code>
|
<label>
|
||||||
<p><a id="otp-uri" href="" target="_blank" rel="noopener noreferrer">Open authenticator link</a></p>
|
New password
|
||||||
<label>Verification code <input id="otp-setup-code" inputmode="numeric" autocomplete="one-time-code" /></label>
|
<input name="new_password" type="password" minlength="8" autocomplete="new-password" required />
|
||||||
<button id="otp-enable" type="button">Enable one-time password</button>
|
</label>
|
||||||
</div>
|
<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">
|
</div>
|
||||||
<p>One-time password is enabled.</p>
|
<div id="otp-enabled" class="hidden">
|
||||||
<label>Verification code <input id="otp-disable-code" inputmode="numeric" autocomplete="one-time-code" /></label>
|
<p>One-time password is enabled.</p>
|
||||||
<button id="otp-disable" type="button">Disable one-time password</button>
|
<label>Current password <input id="otp-current-password" type="password" autocomplete="current-password" /></label>
|
||||||
</div>
|
<label>Verification code <input id="otp-disable-code" inputmode="numeric"
|
||||||
<p id="otp-status" class="status" role="status"></p>
|
autocomplete="one-time-code" /></label>
|
||||||
</section>
|
<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>
|
|
||||||
Mastodon server
|
|
||||||
<input id="mastodon-instance" name="instance" type="text" value="mastodon.social" placeholder="mastodon.social" required />
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
Post prefix
|
|
||||||
<input id="mastodon-post-prefix" name="post_prefix" type="text" value="From my #LinkLog: " />
|
|
||||||
</label>
|
|
||||||
<button id="mastodon-connect" type="button">Authenticate with this server</button>
|
|
||||||
<button type="submit">Save Mastodon settings</button>
|
|
||||||
<p id="mastodon-status" class="status" role="status"></p>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
<footer class="site-footer">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>
|
|
||||||
</html>
|
</html>
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 320 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.9 MiB |
@@ -9,61 +9,66 @@ from pathlib import Path
|
|||||||
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
MANIFEST_PATH = ROOT / 'webextension' / 'manifest.json'
|
|
||||||
FRONTEND_VERSION_PATH = ROOT / 'frontend' / 'version.json'
|
|
||||||
SETTINGS_PATH = ROOT / 'backend' / 'app' / 'core' / 'config.py'
|
SETTINGS_PATH = ROOT / 'backend' / 'app' / 'core' / 'config.py'
|
||||||
UPDATES_PATH = ROOT / 'webextension' / 'updates.json'
|
|
||||||
SIGNED_DIR = ROOT / 'XPI' / 'signed'
|
SIGNED_DIR = ROOT / 'XPI' / 'signed'
|
||||||
|
VERSION_RE = re.compile(r'\d+\.\d+\.\d+')
|
||||||
|
|
||||||
|
|
||||||
def fail(message: str) -> None:
|
def fail(message: str) -> None:
|
||||||
raise SystemExit(f'release validation failed: {message}')
|
raise SystemExit(f'release validation failed: {message}')
|
||||||
|
|
||||||
|
|
||||||
|
def version_key(version: str) -> tuple[int, int, int]:
|
||||||
|
return tuple(int(part) for part in version.split('.'))
|
||||||
|
|
||||||
|
|
||||||
|
def find_latest_signed_xpi() -> tuple[str, Path]:
|
||||||
|
candidates = []
|
||||||
|
for xpi_path in SIGNED_DIR.glob('LinkLog-*.xpi'):
|
||||||
|
match = re.fullmatch(r'LinkLog-(\d+\.\d+\.\d+)\.xpi', xpi_path.name)
|
||||||
|
if match:
|
||||||
|
candidates.append((match.group(1), xpi_path))
|
||||||
|
if not candidates:
|
||||||
|
fail(f'no signed plugin artifacts found in {SIGNED_DIR.relative_to(ROOT)}')
|
||||||
|
return max(candidates, key=lambda candidate: version_key(candidate[0]))
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
manifest = json.loads(MANIFEST_PATH.read_text())
|
|
||||||
extension_version = manifest.get('version')
|
|
||||||
if not isinstance(extension_version, str) or not re.fullmatch(r'\d+\.\d+\.\d+', extension_version):
|
|
||||||
fail('webextension/manifest.json has no valid three-part version')
|
|
||||||
|
|
||||||
frontend_version = json.loads(FRONTEND_VERSION_PATH.read_text()).get('version')
|
|
||||||
if frontend_version != extension_version:
|
|
||||||
fail(f'frontend version {frontend_version} does not match extension version {extension_version}')
|
|
||||||
|
|
||||||
gecko_settings = manifest.get('browser_specific_settings', {}).get('gecko', {})
|
|
||||||
data_permissions = gecko_settings.get('data_collection_permissions')
|
|
||||||
if data_permissions != {'required': ['websiteActivity'], 'optional': []}:
|
|
||||||
fail('Firefox data_collection_permissions must require websiteActivity and have no optional categories')
|
|
||||||
|
|
||||||
settings = SETTINGS_PATH.read_text()
|
settings = SETTINGS_PATH.read_text()
|
||||||
match = re.search(r"version: str = os\.getenv\('LINKLOG_VERSION', '([^']+)'\)", settings)
|
match = re.search(r"version: str = os\.getenv\('LINKLOG_VERSION', '([^']+)'\)", settings)
|
||||||
if not match:
|
if not match:
|
||||||
fail('backend version default could not be found')
|
fail('backend version default could not be found')
|
||||||
backend_version = match.group(1)
|
backend_version = match.group(1)
|
||||||
if backend_version != extension_version:
|
if not VERSION_RE.fullmatch(backend_version):
|
||||||
fail(f'backend version {backend_version} does not match extension version {extension_version}')
|
fail(f'backend version {backend_version} is not a valid three-part version')
|
||||||
|
|
||||||
xpi_path = SIGNED_DIR / f'LinkLog-{extension_version}.xpi'
|
extension_version, xpi_path = find_latest_signed_xpi()
|
||||||
if not xpi_path.is_file():
|
|
||||||
fail(f'missing manually signed artifact: {xpi_path.relative_to(ROOT)}')
|
|
||||||
with zipfile.ZipFile(xpi_path) as archive:
|
with zipfile.ZipFile(xpi_path) as archive:
|
||||||
try:
|
try:
|
||||||
packaged_manifest = json.loads(archive.read('manifest.json'))
|
packaged_manifest = json.loads(archive.read('manifest.json'))
|
||||||
except KeyError:
|
except KeyError:
|
||||||
fail('signed XPI does not contain manifest.json')
|
fail('signed XPI does not contain manifest.json')
|
||||||
if packaged_manifest.get('version') != extension_version:
|
if packaged_manifest.get('version') != extension_version:
|
||||||
fail('signed XPI manifest version does not match webextension/manifest.json')
|
fail('signed XPI manifest version does not match its filename')
|
||||||
|
gecko_settings = packaged_manifest.get('browser_specific_settings', {}).get('gecko', {})
|
||||||
|
data_permissions = gecko_settings.get('data_collection_permissions')
|
||||||
|
if data_permissions != {'required': ['websiteActivity'], 'optional': []}:
|
||||||
|
fail('Firefox data_collection_permissions must require websiteActivity and have no optional categories')
|
||||||
if archive.testzip() is not None:
|
if archive.testzip() is not None:
|
||||||
fail('signed XPI contains a corrupt member')
|
fail('signed XPI contains a corrupt member')
|
||||||
|
|
||||||
updates = json.loads(UPDATES_PATH.read_text())
|
signed_xpi = xpi_path.relative_to(ROOT)
|
||||||
addon_id = gecko_settings['id']
|
if len(sys.argv) == 3 and sys.argv[1] == '--github-output':
|
||||||
update_entries = updates.get('addons', {}).get(addon_id, {}).get('updates', [])
|
with Path(sys.argv[2]).open('a') as output:
|
||||||
if not any(entry.get('version') == extension_version for entry in update_entries):
|
print(f'backend_version={backend_version}', file=output)
|
||||||
fail(f'webextension/updates.json has no update entry for {extension_version}')
|
print(f'plugin_version={extension_version}', file=output)
|
||||||
|
print(f'signed_xpi={signed_xpi}', file=output)
|
||||||
|
elif len(sys.argv) != 1:
|
||||||
|
fail('usage: validate_release.py [--github-output <path>]')
|
||||||
|
|
||||||
print(f'validated LinkLog release {frontend_version}')
|
print(f'validated LinkLog backend release {backend_version}')
|
||||||
print(f'xpi={xpi_path.relative_to(ROOT)}')
|
print(f'plugin_version={extension_version}')
|
||||||
|
print(f'signed_xpi={signed_xpi}')
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -15,6 +15,8 @@
|
|||||||
"openSettings": {"message": "Einstellungen öffnen"},
|
"openSettings": {"message": "Einstellungen öffnen"},
|
||||||
"signOut": {"message": "Abmelden"},
|
"signOut": {"message": "Abmelden"},
|
||||||
"backendUrlLabel": {"message": "Backend-URL"},
|
"backendUrlLabel": {"message": "Backend-URL"},
|
||||||
|
"emailLabel": {"message": "E-Mail"},
|
||||||
|
"emailPlaceholder": {"message": "alice@example.com"},
|
||||||
"usernameLabel": {"message": "Benutzername"},
|
"usernameLabel": {"message": "Benutzername"},
|
||||||
"usernamePlaceholder": {"message": "alice"},
|
"usernamePlaceholder": {"message": "alice"},
|
||||||
"passwordLabel": {"message": "Passwort"},
|
"passwordLabel": {"message": "Passwort"},
|
||||||
@@ -38,7 +40,10 @@
|
|||||||
"configureAndLogIn": {"message": "Konfiguriere die Backend-URL und melde dich zuerst an."},
|
"configureAndLogIn": {"message": "Konfiguriere die Backend-URL und melde dich zuerst an."},
|
||||||
"sessionExpired": {"message": "Sitzung abgelaufen. Authentifiziere dich in den Einstellungen erneut."},
|
"sessionExpired": {"message": "Sitzung abgelaufen. Authentifiziere dich in den Einstellungen erneut."},
|
||||||
"submissionFailed": {"message": "Senden fehlgeschlagen"},
|
"submissionFailed": {"message": "Senden fehlgeschlagen"},
|
||||||
"linkSaved": {"message": "Link erfolgreich gespeichert"},
|
"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."},
|
"submissionFailedConnection": {"message": "Senden fehlgeschlagen. Überprüfe die Verbindung zum Backend."},
|
||||||
"loggedInAt": {"message": "$USERNAME$ ist bei $BACKEND$ angemeldet", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
"loggedInAt": {"message": "$USERNAME$ ist bei $BACKEND$ angemeldet", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||||
"fillAllFields": {"message": "Fülle alle Felder aus"},
|
"fillAllFields": {"message": "Fülle alle Felder aus"},
|
||||||
|
|||||||
@@ -47,6 +47,12 @@
|
|||||||
"backendUrlLabel": {
|
"backendUrlLabel": {
|
||||||
"message": "Backend URL"
|
"message": "Backend URL"
|
||||||
},
|
},
|
||||||
|
"emailLabel": {
|
||||||
|
"message": "Email"
|
||||||
|
},
|
||||||
|
"emailPlaceholder": {
|
||||||
|
"message": "alice@example.com"
|
||||||
|
},
|
||||||
"usernameLabel": {
|
"usernameLabel": {
|
||||||
"message": "Username"
|
"message": "Username"
|
||||||
},
|
},
|
||||||
@@ -117,7 +123,26 @@
|
|||||||
"message": "Submission failed"
|
"message": "Submission failed"
|
||||||
},
|
},
|
||||||
"linkSaved": {
|
"linkSaved": {
|
||||||
"message": "Link saved successfully"
|
"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": {
|
"submissionFailedConnection": {
|
||||||
"message": "Submission failed. Check your backend connection."
|
"message": "Submission failed. Check your backend connection."
|
||||||
|
|||||||
@@ -15,6 +15,8 @@
|
|||||||
"openSettings": {"message": "Abrir configuración"},
|
"openSettings": {"message": "Abrir configuración"},
|
||||||
"signOut": {"message": "Cerrar sesión"},
|
"signOut": {"message": "Cerrar sesión"},
|
||||||
"backendUrlLabel": {"message": "URL del servidor"},
|
"backendUrlLabel": {"message": "URL del servidor"},
|
||||||
|
"emailLabel": {"message": "Correo electrónico"},
|
||||||
|
"emailPlaceholder": {"message": "alice@example.com"},
|
||||||
"usernameLabel": {"message": "Nombre de usuario"},
|
"usernameLabel": {"message": "Nombre de usuario"},
|
||||||
"usernamePlaceholder": {"message": "alice"},
|
"usernamePlaceholder": {"message": "alice"},
|
||||||
"passwordLabel": {"message": "Contraseña"},
|
"passwordLabel": {"message": "Contraseña"},
|
||||||
@@ -38,7 +40,10 @@
|
|||||||
"configureAndLogIn": {"message": "Configura la URL del servidor e inicia sesión primero."},
|
"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."},
|
"sessionExpired": {"message": "La sesión ha caducado. Vuelve a autenticarte en la configuración."},
|
||||||
"submissionFailed": {"message": "Error al enviar"},
|
"submissionFailed": {"message": "Error al enviar"},
|
||||||
"linkSaved": {"message": "Enlace guardado correctamente"},
|
"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."},
|
"submissionFailedConnection": {"message": "Error al enviar. Comprueba la conexión con el servidor."},
|
||||||
"loggedInAt": {"message": "$USERNAME$ ha iniciado sesión en $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
"loggedInAt": {"message": "$USERNAME$ ha iniciado sesión en $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||||
"fillAllFields": {"message": "Rellena todos los campos"},
|
"fillAllFields": {"message": "Rellena todos los campos"},
|
||||||
|
|||||||
@@ -15,6 +15,8 @@
|
|||||||
"openSettings": {"message": "Ouvrir les paramètres"},
|
"openSettings": {"message": "Ouvrir les paramètres"},
|
||||||
"signOut": {"message": "Se déconnecter"},
|
"signOut": {"message": "Se déconnecter"},
|
||||||
"backendUrlLabel": {"message": "URL du serveur"},
|
"backendUrlLabel": {"message": "URL du serveur"},
|
||||||
|
"emailLabel": {"message": "E-mail"},
|
||||||
|
"emailPlaceholder": {"message": "alice@example.com"},
|
||||||
"usernameLabel": {"message": "Nom d’utilisateur"},
|
"usernameLabel": {"message": "Nom d’utilisateur"},
|
||||||
"usernamePlaceholder": {"message": "alice"},
|
"usernamePlaceholder": {"message": "alice"},
|
||||||
"passwordLabel": {"message": "Mot de passe"},
|
"passwordLabel": {"message": "Mot de passe"},
|
||||||
@@ -38,7 +40,10 @@
|
|||||||
"configureAndLogIn": {"message": "Configurez l’URL du serveur et connectez-vous d’abord."},
|
"configureAndLogIn": {"message": "Configurez l’URL du serveur et connectez-vous d’abord."},
|
||||||
"sessionExpired": {"message": "Session expirée. Reconnectez-vous dans les paramètres."},
|
"sessionExpired": {"message": "Session expirée. Reconnectez-vous dans les paramètres."},
|
||||||
"submissionFailed": {"message": "Échec de l’envoi"},
|
"submissionFailed": {"message": "Échec de l’envoi"},
|
||||||
"linkSaved": {"message": "Lien enregistré"},
|
"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."},
|
"submissionFailedConnection": {"message": "Échec de l’envoi. Vérifiez la connexion au serveur."},
|
||||||
"loggedInAt": {"message": "$USERNAME$ est connecté à $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
"loggedInAt": {"message": "$USERNAME$ est connecté à $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||||
"fillAllFields": {"message": "Veuillez remplir tous les champs"},
|
"fillAllFields": {"message": "Veuillez remplir tous les champs"},
|
||||||
|
|||||||
@@ -15,6 +15,8 @@
|
|||||||
"openSettings": {"message": "Instellingen openen"},
|
"openSettings": {"message": "Instellingen openen"},
|
||||||
"signOut": {"message": "Uitloggen"},
|
"signOut": {"message": "Uitloggen"},
|
||||||
"backendUrlLabel": {"message": "Backend-URL"},
|
"backendUrlLabel": {"message": "Backend-URL"},
|
||||||
|
"emailLabel": {"message": "E-mail"},
|
||||||
|
"emailPlaceholder": {"message": "alice@example.com"},
|
||||||
"usernameLabel": {"message": "Gebruikersnaam"},
|
"usernameLabel": {"message": "Gebruikersnaam"},
|
||||||
"usernamePlaceholder": {"message": "alice"},
|
"usernamePlaceholder": {"message": "alice"},
|
||||||
"passwordLabel": {"message": "Wachtwoord"},
|
"passwordLabel": {"message": "Wachtwoord"},
|
||||||
@@ -38,7 +40,10 @@
|
|||||||
"configureAndLogIn": {"message": "Configureer de backend-URL en log eerst in."},
|
"configureAndLogIn": {"message": "Configureer de backend-URL en log eerst in."},
|
||||||
"sessionExpired": {"message": "Sessie verlopen. Verifieer opnieuw in de instellingen."},
|
"sessionExpired": {"message": "Sessie verlopen. Verifieer opnieuw in de instellingen."},
|
||||||
"submissionFailed": {"message": "Verzenden mislukt"},
|
"submissionFailed": {"message": "Verzenden mislukt"},
|
||||||
"linkSaved": {"message": "Koppeling opgeslagen"},
|
"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."},
|
"submissionFailedConnection": {"message": "Verzenden mislukt. Controleer de verbinding met de backend."},
|
||||||
"loggedInAt": {"message": "$USERNAME$ is ingelogd op $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
"loggedInAt": {"message": "$USERNAME$ is ingelogd op $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
|
||||||
"fillAllFields": {"message": "Vul alle velden in"},
|
"fillAllFields": {"message": "Vul alle velden in"},
|
||||||
|
|||||||
@@ -6,12 +6,15 @@
|
|||||||
"default_locale": "en-US",
|
"default_locale": "en-US",
|
||||||
"permissions": [
|
"permissions": [
|
||||||
"activeTab",
|
"activeTab",
|
||||||
"storage",
|
"storage"
|
||||||
"tabs"
|
|
||||||
],
|
],
|
||||||
"host_permissions": [
|
"optional_permissions": [
|
||||||
"<all_urls>"
|
"http://*/*",
|
||||||
|
"https://*/*"
|
||||||
],
|
],
|
||||||
|
"content_security_policy": {
|
||||||
|
"extension_pages": "script-src 'self'; object-src 'none'"
|
||||||
|
},
|
||||||
"action": {
|
"action": {
|
||||||
"default_title": "__MSG_extensionName__",
|
"default_title": "__MSG_extensionName__",
|
||||||
"default_popup": "popup.html",
|
"default_popup": "popup.html",
|
||||||
@@ -27,7 +30,7 @@
|
|||||||
"browser_specific_settings": {
|
"browser_specific_settings": {
|
||||||
"gecko": {
|
"gecko": {
|
||||||
"id": "linklog@kolkman.org",
|
"id": "linklog@kolkman.org",
|
||||||
"strict_min_version": "109.0",
|
"strict_min_version": "142.0",
|
||||||
"data_collection_permissions": {
|
"data_collection_permissions": {
|
||||||
"required": ["websiteActivity"],
|
"required": ["websiteActivity"],
|
||||||
"optional": []
|
"optional": []
|
||||||
|
|||||||
+91
-12
@@ -10,9 +10,38 @@ const otpInput = document.getElementById('otp');
|
|||||||
const session = document.getElementById('logged-in');
|
const session = document.getElementById('logged-in');
|
||||||
const sessionSummary = document.getElementById('session-summary');
|
const sessionSummary = document.getElementById('session-summary');
|
||||||
const signOutButton = document.getElementById('sign-out');
|
const signOutButton = document.getElementById('sign-out');
|
||||||
|
const sessionStore = browser.storage.session;
|
||||||
|
|
||||||
const t = window.linklogI18n;
|
const t = window.linklogI18n;
|
||||||
|
|
||||||
|
function normalizeBackendOrigin(backendUrl) {
|
||||||
|
try {
|
||||||
|
const url = new URL(backendUrl);
|
||||||
|
if (!['http:', 'https:'].includes(url.protocol)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return url.origin;
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function hasBackendPermission(backendUrl) {
|
||||||
|
const origin = normalizeBackendOrigin(backendUrl);
|
||||||
|
if (!origin) return false;
|
||||||
|
return browser.permissions.contains({origins: [`${origin}/*`]});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestBackendPermission(backendUrl) {
|
||||||
|
const origin = normalizeBackendOrigin(backendUrl);
|
||||||
|
if (!origin) return false;
|
||||||
|
try {
|
||||||
|
return await browser.permissions.request({origins: [`${origin}/*`]});
|
||||||
|
} catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function setStatus(message, isError = false) {
|
function setStatus(message, isError = false) {
|
||||||
statusEl.textContent = message;
|
statusEl.textContent = message;
|
||||||
statusEl.classList.remove('hidden');
|
statusEl.classList.remove('hidden');
|
||||||
@@ -21,14 +50,18 @@ function setStatus(message, isError = false) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadSettings() {
|
async function loadSettings() {
|
||||||
const settings = await browser.storage.local.get(['backendUrl', 'email', 'username', 'accessToken']);
|
const [settings, sessionSettings] = await Promise.all([
|
||||||
|
browser.storage.local.get(['backendUrl', 'email', 'username']),
|
||||||
|
sessionStore.get(['accessToken', 'refreshToken', 'tokenExpiresAt', 'deviceId']),
|
||||||
|
]);
|
||||||
backendUrlInput.value = settings.backendUrl || '';
|
backendUrlInput.value = settings.backendUrl || '';
|
||||||
emailInput.value = settings.email || '';
|
emailInput.value = settings.email || '';
|
||||||
|
|
||||||
if (settings.accessToken && settings.backendUrl) {
|
if (sessionSettings.accessToken && settings.backendUrl && await hasBackendPermission(settings.backendUrl)) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${settings.backendUrl}/api/auth/me?token=${encodeURIComponent(settings.accessToken)}`
|
`${settings.backendUrl}/api/auth/me`,
|
||||||
|
{headers: {Authorization: `Bearer ${sessionSettings.accessToken}`}},
|
||||||
);
|
);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const user = await response.json();
|
const user = await response.json();
|
||||||
@@ -55,12 +88,37 @@ function showLoggedOut() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function clearSession() {
|
async function clearSession() {
|
||||||
await browser.storage.local.remove(['accessToken', 'tokenType', 'tokenExpiresAt', 'refreshToken']);
|
await Promise.all([
|
||||||
|
sessionStore.remove(['accessToken', 'refreshToken', 'tokenExpiresAt', 'deviceId']),
|
||||||
|
browser.storage.local.remove(['accessToken', 'tokenType', 'tokenExpiresAt', 'refreshToken', 'deviceId']),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshAccessToken(settings) {
|
||||||
|
if (!settings.backendUrl || !settings.refreshToken || !settings.deviceId) return null;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${settings.backendUrl}/api/auth/refresh`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({refresh_token: settings.refreshToken, device_id: settings.deviceId}),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
await clearSession();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const data = await response.json();
|
||||||
|
const refreshed = {accessToken: data.access_token, refreshToken: data.refresh_token,
|
||||||
|
tokenExpiresAt: data.expires_at, deviceId: data.device_id || settings.deviceId};
|
||||||
|
await sessionStore.set(refreshed);
|
||||||
|
return refreshed;
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveSettingsAndLogin(event) {
|
async function saveSettingsAndLogin(event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const backendUrl = backendUrlInput.value.trim();
|
const backendUrl = normalizeBackendOrigin(backendUrlInput.value.trim());
|
||||||
const email = emailInput.value.trim();
|
const email = emailInput.value.trim();
|
||||||
const password = passwordInput.value;
|
const password = passwordInput.value;
|
||||||
const otp = otpInput.value.trim();
|
const otp = otpInput.value.trim();
|
||||||
@@ -70,6 +128,11 @@ async function saveSettingsAndLogin(event) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!(await requestBackendPermission(backendUrl))) {
|
||||||
|
setStatus(t('unableToLogIn'), true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${backendUrl}/api/auth/login`, {
|
const response = await fetch(`${backendUrl}/api/auth/login`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -82,14 +145,29 @@ async function saveSettingsAndLogin(event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
if (response.status === 401) {
|
||||||
|
const refreshed = await refreshAccessToken({...settings, ...sessionSettings});
|
||||||
|
if (refreshed) {
|
||||||
|
const retry = await fetch(`${settings.backendUrl}/api/auth/me`, {
|
||||||
|
headers: {Authorization: `Bearer ${refreshed.accessToken}`},
|
||||||
|
});
|
||||||
|
if (retry.ok) {
|
||||||
|
const user = await retry.json();
|
||||||
|
showLoggedIn(user.username || settings.email, settings.backendUrl);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
await browser.storage.local.set({
|
await browser.storage.local.set({
|
||||||
backendUrl,
|
backendUrl,
|
||||||
email,
|
email,
|
||||||
username: data.user?.username || email,
|
username: data.user?.username || email,
|
||||||
|
});
|
||||||
|
await sessionStore.set({
|
||||||
accessToken: data.access_token,
|
accessToken: data.access_token,
|
||||||
tokenType: data.token_type,
|
|
||||||
tokenExpiresAt: data.expires_at,
|
|
||||||
refreshToken: data.refresh_token,
|
refreshToken: data.refresh_token,
|
||||||
|
tokenExpiresAt: data.expires_at,
|
||||||
|
deviceId: data.device_id || `device-${crypto.randomUUID()}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
showLoggedIn(data.user?.username || email, backendUrl);
|
showLoggedIn(data.user?.username || email, backendUrl);
|
||||||
@@ -102,12 +180,13 @@ async function saveSettingsAndLogin(event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function signOut() {
|
async function signOut() {
|
||||||
const settings = await browser.storage.local.get(['accessToken']);
|
const settings = await browser.storage.local.get(['backendUrl']);
|
||||||
if (settings.accessToken) {
|
const sessionSettings = await sessionStore.get(['accessToken']);
|
||||||
await fetch(`${backendUrlInput.value.trim()}/api/auth/logout`, {
|
const backendUrl = normalizeBackendOrigin(backendUrlInput.value.trim());
|
||||||
|
if (sessionSettings.accessToken && settings.backendUrl && await hasBackendPermission(backendUrl)) {
|
||||||
|
await fetch(`${backendUrl}/api/auth/logout`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: {Authorization: `Bearer ${sessionSettings.accessToken}`},
|
||||||
body: JSON.stringify({ token: settings.accessToken }),
|
|
||||||
}).catch(() => undefined);
|
}).catch(() => undefined);
|
||||||
}
|
}
|
||||||
await clearSession();
|
await clearSession();
|
||||||
|
|||||||
@@ -149,6 +149,16 @@ button {
|
|||||||
color: #f38ba8;
|
color: #f38ba8;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.auth-session {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
border: 1px solid #585b70;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
color: #94e2d5;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
#auth-warning {
|
#auth-warning {
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
@@ -162,6 +172,11 @@ button {
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#auth-session[hidden],
|
||||||
|
#auth-warning[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
.extension-footer {
|
.extension-footer {
|
||||||
margin-top: 16px;
|
margin-top: 16px;
|
||||||
color: #7f849c;
|
color: #7f849c;
|
||||||
|
|||||||
@@ -15,7 +15,8 @@
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div id="status" class="status hidden" aria-live="polite"></div>
|
<div id="status" class="status hidden" aria-live="polite"></div>
|
||||||
<div id="auth-warning" class="status error" aria-live="polite">
|
<div id="auth-session" class="auth-session" hidden aria-live="polite"></div>
|
||||||
|
<div id="auth-warning" class="status error" hidden aria-live="polite">
|
||||||
<span data-i18n="authRequired">Please sign in to use LinkLog.</span>
|
<span data-i18n="authRequired">Please sign in to use LinkLog.</span>
|
||||||
<button type="button" id="warning-settings" class="secondary" data-i18n="openSettings">Open settings</button>
|
<button type="button" id="warning-settings" class="secondary" data-i18n="openSettings">Open settings</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+161
-16
@@ -12,9 +12,29 @@ const newTagsInput = document.getElementById('new-tags');
|
|||||||
const feedLink = document.getElementById('feed-link');
|
const feedLink = document.getElementById('feed-link');
|
||||||
const authWarning = document.getElementById('auth-warning');
|
const authWarning = document.getElementById('auth-warning');
|
||||||
const warningSettingsButton = document.getElementById('warning-settings');
|
const warningSettingsButton = document.getElementById('warning-settings');
|
||||||
|
const authSession = document.getElementById('auth-session');
|
||||||
|
const sessionStore = browser.storage.session;
|
||||||
|
|
||||||
const t = window.linklogI18n;
|
const t = window.linklogI18n;
|
||||||
|
|
||||||
|
function normalizeBackendOrigin(backendUrl) {
|
||||||
|
try {
|
||||||
|
const url = new URL(backendUrl);
|
||||||
|
if (!['http:', 'https:'].includes(url.protocol)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return url.origin;
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function hasBackendPermission(backendUrl) {
|
||||||
|
const origin = normalizeBackendOrigin(backendUrl);
|
||||||
|
if (!origin) return false;
|
||||||
|
return browser.permissions.contains({origins: [`${origin}/*`]});
|
||||||
|
}
|
||||||
|
|
||||||
function setStatus(message, isError = false) {
|
function setStatus(message, isError = false) {
|
||||||
statusEl.textContent = message;
|
statusEl.textContent = message;
|
||||||
statusEl.classList.remove('hidden');
|
statusEl.classList.remove('hidden');
|
||||||
@@ -23,26 +43,108 @@ function setStatus(message, isError = false) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function getSettings() {
|
async function getSettings() {
|
||||||
const result = await browser.storage.local.get([
|
const [settings, sessionSettings] = await Promise.all([
|
||||||
'backendUrl',
|
browser.storage.local.get(['backendUrl', 'username']),
|
||||||
'accessToken',
|
sessionStore.get(['accessToken', 'refreshToken', 'tokenExpiresAt', 'deviceId']),
|
||||||
'tokenExpiresAt',
|
|
||||||
]);
|
]);
|
||||||
return result;
|
return {...settings, ...sessionSettings};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function persistSession(settings) {
|
||||||
|
await sessionStore.set({
|
||||||
|
accessToken: settings.accessToken,
|
||||||
|
refreshToken: settings.refreshToken,
|
||||||
|
tokenExpiresAt: settings.tokenExpiresAt,
|
||||||
|
deviceId: settings.deviceId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function clearSession() {
|
||||||
|
await Promise.all([
|
||||||
|
sessionStore.remove(['accessToken', 'refreshToken', 'tokenExpiresAt', 'deviceId']),
|
||||||
|
browser.storage.local.remove(['accessToken', 'tokenType', 'tokenExpiresAt', 'refreshToken', 'deviceId']),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshAccessToken(settings) {
|
||||||
|
if (!settings.backendUrl || !settings.refreshToken || !settings.deviceId) return null;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${settings.backendUrl}/api/auth/refresh`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({refresh_token: settings.refreshToken, device_id: settings.deviceId}),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
await clearSession();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const data = await response.json();
|
||||||
|
const refreshed = {...settings, accessToken: data.access_token, refreshToken: data.refresh_token,
|
||||||
|
tokenExpiresAt: data.expires_at, deviceId: data.device_id || settings.deviceId};
|
||||||
|
await persistSession(refreshed);
|
||||||
|
return refreshed;
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function validateSession(settings) {
|
||||||
|
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl))) return null;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${settings.backendUrl}/api/auth/me`, {
|
||||||
|
headers: {'Authorization': `Bearer ${settings.accessToken}`},
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status === 401) {
|
||||||
|
const refreshed = await refreshAccessToken(settings);
|
||||||
|
if (refreshed) {
|
||||||
|
const retry = await fetch(`${refreshed.backendUrl}/api/auth/me`, {
|
||||||
|
headers: {'Authorization': `Bearer ${refreshed.accessToken}`},
|
||||||
|
});
|
||||||
|
if (retry.ok) return await retry.json();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await clearSession();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function showSignedOutState() {
|
function showSignedOutState() {
|
||||||
form.classList.add('hidden');
|
form.classList.add('hidden');
|
||||||
|
authSession.hidden = true;
|
||||||
|
authSession.classList.add('hidden');
|
||||||
|
authWarning.hidden = false;
|
||||||
authWarning.classList.remove('hidden');
|
authWarning.classList.remove('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
function showSignedInState() {
|
function showSignedInState(user, backendUrl) {
|
||||||
|
authWarning.hidden = true;
|
||||||
authWarning.classList.add('hidden');
|
authWarning.classList.add('hidden');
|
||||||
|
authSession.textContent = t('loggedInAt', [user.username || user.email, backendUrl]);
|
||||||
|
authSession.hidden = false;
|
||||||
|
authSession.classList.remove('hidden');
|
||||||
form.classList.remove('hidden');
|
form.classList.remove('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function showSavedState(message) {
|
||||||
|
document.querySelector('header').classList.add('hidden');
|
||||||
|
document.querySelector('.extension-footer').classList.add('hidden');
|
||||||
|
authSession.hidden = true;
|
||||||
|
authSession.classList.add('hidden');
|
||||||
|
authWarning.hidden = true;
|
||||||
|
authWarning.classList.add('hidden');
|
||||||
|
form.classList.add('hidden');
|
||||||
|
statusEl.textContent = message;
|
||||||
|
statusEl.classList.remove('hidden', 'error');
|
||||||
|
statusEl.classList.add('success');
|
||||||
|
}
|
||||||
|
|
||||||
async function updateFeedLink() {
|
async function updateFeedLink() {
|
||||||
const settings = await browser.storage.local.get(['backendUrl', 'username', 'accessToken']);
|
const settings = await getSettings();
|
||||||
if (!settings.backendUrl || !settings.username || !settings.accessToken) return;
|
if (!settings.backendUrl || !settings.username || !settings.accessToken) return;
|
||||||
try {
|
try {
|
||||||
const backend = new URL(settings.backendUrl);
|
const backend = new URL(settings.backendUrl);
|
||||||
@@ -59,12 +161,21 @@ async function loadExistingTags() {
|
|||||||
showSignedOutState();
|
showSignedOutState();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
showSignedInState();
|
const user = await validateSession(settings);
|
||||||
const response = await fetch(`${settings.backendUrl}/api/tags`, {
|
if (!user) {
|
||||||
headers: {'Authorization': `Bearer ${settings.accessToken}`},
|
showSignedOutState();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const currentSettings = await getSettings();
|
||||||
|
showSignedInState(user, currentSettings.backendUrl);
|
||||||
|
const response = await fetch(`${currentSettings.backendUrl}/api/tags`, {
|
||||||
|
headers: {'Authorization': `Bearer ${currentSettings.accessToken}`},
|
||||||
});
|
});
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
if (response.status === 401) showSignedOutState();
|
if (response.status === 401) {
|
||||||
|
showSignedOutState();
|
||||||
|
return;
|
||||||
|
}
|
||||||
existingTags.textContent = t('loadTagsFailed');
|
existingTags.textContent = t('loadTagsFailed');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -110,6 +221,24 @@ async function populateCurrentTab() {
|
|||||||
urlInput.value = tab.url || '';
|
urlInput.value = tab.url || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function checkExistingLink() {
|
||||||
|
const settings = await getSettings();
|
||||||
|
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl)) || !titleInput.value || !urlInput.value) return;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${settings.backendUrl}/api/links/check?${new URLSearchParams({
|
||||||
|
title: titleInput.value,
|
||||||
|
url: removeKnownTrackingParams(urlInput.value),
|
||||||
|
})}`, {
|
||||||
|
headers: {'Authorization': `Bearer ${settings.accessToken}`},
|
||||||
|
});
|
||||||
|
if (response.ok && (await response.json()).exists) {
|
||||||
|
setStatus(t('duplicateLinkWarning'), true);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Duplicate checking is advisory; submission remains available.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleSubmit(event) {
|
async function handleSubmit(event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setStatus(t('submitting'), false);
|
setStatus(t('submitting'), false);
|
||||||
@@ -118,18 +247,27 @@ async function handleSubmit(event) {
|
|||||||
const token = settings.accessToken;
|
const token = settings.accessToken;
|
||||||
const backendUrl = settings.backendUrl;
|
const backendUrl = settings.backendUrl;
|
||||||
|
|
||||||
if (!token || !backendUrl) {
|
if (!token || !backendUrl || !(await hasBackendPermission(backendUrl))) {
|
||||||
setStatus(t('configureAndLogIn'), true);
|
setStatus(t('configureAndLogIn'), true);
|
||||||
browser.runtime.openOptionsPage();
|
browser.runtime.openOptionsPage();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!await validateSession(settings)) {
|
||||||
|
showSignedOutState();
|
||||||
|
setStatus(t('sessionExpired'), true);
|
||||||
|
browser.runtime.openOptionsPage();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentSettings = await getSettings();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${backendUrl}/api/links`, {
|
const response = await fetch(`${currentSettings.backendUrl}/api/links`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Authorization': `Bearer ${token}`,
|
'Authorization': `Bearer ${currentSettings.accessToken}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
title: titleInput.value,
|
title: titleInput.value,
|
||||||
@@ -151,7 +289,14 @@ async function handleSubmit(event) {
|
|||||||
throw new Error(t('submissionFailed'));
|
throw new Error(t('submissionFailed'));
|
||||||
}
|
}
|
||||||
|
|
||||||
setStatus(t('linkSaved'));
|
const result = await response.json();
|
||||||
|
const saveMessage = result.duplicate ? t('linkAlreadyExists') : t('linkSaved', currentSettings.backendUrl);
|
||||||
|
if (result.plugin_errors?.length) {
|
||||||
|
const errors = result.plugin_errors.map((error) => `${error.plugin}: ${error.reason}`).join(' ');
|
||||||
|
showSavedState(`${saveMessage} ${t('publishingErrors', errors)}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showSavedState(saveMessage);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setStatus(t('submissionFailedConnection'), true);
|
setStatus(t('submissionFailedConnection'), true);
|
||||||
}
|
}
|
||||||
@@ -160,6 +305,6 @@ async function handleSubmit(event) {
|
|||||||
openSettingsButton.addEventListener('click', () => browser.runtime.openOptionsPage());
|
openSettingsButton.addEventListener('click', () => browser.runtime.openOptionsPage());
|
||||||
warningSettingsButton.addEventListener('click', () => browser.runtime.openOptionsPage());
|
warningSettingsButton.addEventListener('click', () => browser.runtime.openOptionsPage());
|
||||||
form.addEventListener('submit', handleSubmit);
|
form.addEventListener('submit', handleSubmit);
|
||||||
populateCurrentTab();
|
populateCurrentTab().then(checkExistingLink);
|
||||||
loadExistingTags();
|
loadExistingTags();
|
||||||
updateFeedLink();
|
updateFeedLink();
|
||||||
|
|||||||
Reference in New Issue
Block a user