12 Commits
Author SHA1 Message Date
Olaf 74b2c400c6 Fix release hash validation on older Python
Release LinkLog / release (push) Successful in 9s
Build LinkLog Development Image / development-image (push) Successful in 9s
2026-08-28 10:44:12 +02:00
Olaf 9bf9c94dd6 Versioning consistency and bump both the XPI and backend to version 0.2.0
Build LinkLog Development Image / development-image (push) Successful in 11s
Release LinkLog / release (push) Failing after 2s
2026-08-28 10:38:27 +02:00
olaf 5696c89dee Plugin follows duplicate behavior behavior of new-entry 2026-08-28 09:37:14 +02:00
olaf 50d61371e1 New Entry page improvements on link detection 2026-08-28 09:04:24 +02:00
olaf cf83c32b25 Fonts served via server
Build LinkLog Development Image / development-image (push) Successful in 22s
2026-08-28 08:19:43 +02:00
olaf 7bd64b870c Tried to fix a broke filter.
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-27 22:54:22 +02:00
olaf 9494d2b119 Red theme and regression 2026-08-27 22:22:41 +02:00
olaf 3661d0b4b7 Logo links to home page 2026-08-27 22:14:32 +02:00
olaf d433a305f5 Fixed mastodon checkbox on new entry page 2026-08-27 22:08:30 +02:00
olaf 1c2d1b71ff tag placement in new-entry page 2026-08-27 21:45:38 +02:00
olaf de916d2fc7 Eyecandy on admin page and fix of functionality on that page
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-08-27 21:16:11 +02:00
olaf 89f9be5e72 Label edit functionality added
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-27 20:38:02 +02:00
47 changed files with 1606 additions and 149 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
id: release id: release
run: | run: |
python3 scripts/release/validate_release.py --github-output "$GITHUB_OUTPUT" python3 scripts/release/validate_release.py --github-output "$GITHUB_OUTPUT"
backend_version=$(python3 -c "import re; text=open('backend/app/core/config.py').read(); print(re.search(r\"version: str = os\\.getenv\\('LINKLOG_VERSION', '([^']+)'\\)\", text).group(1))") backend_version=$(python3 -c "import json; print(json.load(open('frontend/version.json'))['version'])")
if [ "${GITHUB_REF_NAME#v}" != "$backend_version" ]; then if [ "${GITHUB_REF_NAME#v}" != "$backend_version" ]; then
echo "tag ${GITHUB_REF_NAME} does not match backend version $backend_version" >&2 echo "tag ${GITHUB_REF_NAME} does not match backend version $backend_version" >&2
exit 1 exit 1
+35
View File
@@ -1,5 +1,40 @@
# Changelog # Changelog
## Version v0.2.0
### Features
* Users can edit or delete labels created by themselves on the labels page
* Administrators can edit labels from the admin interface
* Filter label visibility so logged-in users only see default/admin-created labels and their own
* Grandfather tags with unknown ownership as default/admin interface labels
* Ability to minimize settings panels to only show headers in the Admin and Profile interfaces for easy navigation
* Styled settings panel headers with distinct theme accent colors for visual distinction
* Settings panels are collapsed by default when opening the Admin and Profile pages
* Show checked-by-default Mastodon publishing on New Entry only for configured users
* Made every web header logo link to the home page
* Added a high-contrast Red color theme
* Brightened the Red theme surfaces and deepened its crimson accents
* Allow every user to filter the feed using every available tag or label
* Bundle required web fonts during Docker image builds and serve them from LinkLog
* Bundle required web fonts during Docker image builds and serve them from LinkLog
* New Entry page warns when the title/URL combination already exists, matching the browser extension's duplicate warning
* New Entry page warns when an existing link with the same title has a different or missing URL (after tracking parameters are stripped)
* New Entry page auto-fills the title when the URL field loses focus, instead of requiring a manual button press
* Added a "Re-fetch Title" button to manually re-scrape the title after editing the URL
* New Entry duplicate detection and submission strip known tracking parameters (utm_*, gclid, fbclid, etc.) from URLs, mirroring the browser extension
* Browser extension popup now matches the New Entry page: it warns on duplicate title/URL, notes when the stored link has a different URL, and gained a "Re-fetch title" button; bumped extension version to 0.2.0
* Generate Firefox update metadata from every signed XPI with verified SHA-256 archive hashes
### Fixed
* Fixed element ID conflict on the Admin page so Available Themes load correctly
* Positioned new-entry tag checkboxes after their label text
* Kept new-entry tag checkboxes immediately left of their labels at all viewport sizes
* Prevented the new-entry form grid from placing tag checkboxes above their labels
* Kept unconfigured New Entry Mastodon publishing controls hidden
* Restored the home-page header layout, keeping the action controls above the filter toolbar
* Made the tag filter refresh the feed directly when its selection changes
* Cache-busted the feed script to ensure browsers load the responsive tag filter
* Fixed feed initialization so tag filtering does not receive promise results as a selected tag [Still no complete fix]
## Version v0.1.1 ## Version v0.1.1
### Features ### Features
* Ability to add new logs through the web interface * Ability to add new logs through the web interface
+2
View File
@@ -13,6 +13,8 @@ RUN pip install --no-cache-dir -r backend/requirements.txt
COPY backend ./backend COPY backend ./backend
COPY frontend ./frontend COPY frontend ./frontend
COPY scripts/download_fonts.py ./scripts/download_fonts.py
RUN python scripts/download_fonts.py
RUN useradd --create-home --uid 10001 linklog \ RUN useradd --create-home --uid 10001 linklog \
&& mkdir -p /app/backend/data \ && mkdir -p /app/backend/data \
&& chown -R linklog:linklog /app && chown -R linklog:linklog /app
+5 -1
View File
@@ -17,8 +17,9 @@ XPI_OUTPUT := $(XPI_UNSIGNED_DIR)/$(XPI_FILE)
EXTENSION_FILES := manifest.json logo.svg icon-16.png icon-32.png icon-48.png icon-96.png options.css options.html options.js popup.css popup.html popup.js l10n.js _locales/en-US/messages.json _locales/es/messages.json _locales/de/messages.json _locales/fr/messages.json _locales/nl/messages.json EXTENSION_FILES := manifest.json logo.svg icon-16.png icon-32.png icon-48.png icon-96.png options.css options.html options.js popup.css popup.html popup.js l10n.js _locales/en-US/messages.json _locales/es/messages.json _locales/de/messages.json _locales/fr/messages.json _locales/nl/messages.json
EXTENSION_SOURCES := $(addprefix webextension/,$(EXTENSION_FILES)) EXTENSION_SOURCES := $(addprefix webextension/,$(EXTENSION_FILES))
XPI_VALIDATOR := scripts/release/validate_xpi.py XPI_VALIDATOR := scripts/release/validate_xpi.py
UPDATES_GENERATOR := scripts/release/generate_updates.py
.PHONY: all logos xpi check-tools clean-generated .PHONY: all logos xpi update-updates check-tools clean-generated
all: logos all: logos
@@ -28,6 +29,9 @@ logos: check-tools $(GENERATED_LOGOS)
xpi: $(XPI_OUTPUT) xpi: $(XPI_OUTPUT)
update-updates: $(UPDATES_GENERATOR) webextension/manifest.json
@python3 $(UPDATES_GENERATOR)
$(XPI_OUTPUT): $(EXTENSION_SOURCES) $(GENERATED_LOGOS) $(XPI_VALIDATOR) $(XPI_OUTPUT): $(EXTENSION_SOURCES) $(GENERATED_LOGOS) $(XPI_VALIDATOR)
@test -n "$(EXTENSION_VERSION)" || { echo "Error: extension version is missing from webextension/manifest.json" >&2; exit 1; } @test -n "$(EXTENSION_VERSION)" || { echo "Error: extension version is missing from webextension/manifest.json" >&2; exit 1; }
@mkdir -p $(XPI_UNSIGNED_DIR) $(XPI_SIGNED_DIR) @mkdir -p $(XPI_UNSIGNED_DIR) $(XPI_SIGNED_DIR)
+5 -5
View File
@@ -28,7 +28,7 @@ For local development:
The backend currently uses FastAPI, uvicorn, SQLite, and Pydantic. `httpx2` is included for the Starlette-compatible test client. The backend currently uses FastAPI, uvicorn, SQLite, and Pydantic. `httpx2` is included for the Starlette-compatible test client.
Jinja2 is included for server-rendered HTML templates. Jinja2 is included for server-rendered HTML templates.
The backend version is `0.1.1` and is exposed through the FastAPI/OpenAPI metadata. It can be overridden with `LINKLOG_VERSION`. The backend version is `0.2.0` and is exposed through the FastAPI/OpenAPI metadata. It is read from `frontend/version.json`, the single source of truth shared by the backend and frontend.
LinkLog is licensed under the GNU General Public License, version 3 or any later version. See [LICENSE](LICENSE). LinkLog is licensed under the GNU General Public License, version 3 or any later version. See [LICENSE](LICENSE).
## Local Installation ## Local Installation
@@ -76,7 +76,7 @@ Open these URLs:
The browser extension requires a backend URL to be entered during setup; it does not assume a default server. The browser extension requires a backend URL to be entered during setup; it does not assume a default server.
The supplied `Logo.svg` is bundled as `frontend/static/logo.svg` for web pages and `webextension/logo.svg` for the Firefox popup and settings page. The supplied `Logo.svg` is bundled as `frontend/static/logo.svg` for web pages and `webextension/logo.svg` for the Firefox popup and settings page.
The visible LinkLog brand text uses the Google Foundry `Asset` font when available, with local fallbacks in the Firefox extension. The visible LinkLog brand text uses the Google Foundry `Asset` font. Docker image builds download and bundle Asset, DM Sans, and Space Grotesk under `/static/fonts`, so the web frontend loads fonts from the LinkLog server rather than Google. The Firefox extension uses its bundled assets and local fallback fonts without requesting Google Fonts.
## Regenerate Logo Assets ## Regenerate Logo Assets
@@ -110,11 +110,11 @@ This publishes `${APP_PORT:-8000}` and defaults the application URL to `http://l
## Releases ## Releases
Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `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. Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `frontend/version.json`; the tag must match that version. The Firefox plugin version is independent and comes from the most recent signed `XPI/signed/LinkLog-<version>.xpi` checked into the repository.
The signed XPI is produced manually and 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 signed XPI is produced manually and should be checked into `XPI/signed/LinkLog-<version>.xpi`. Run `make update-updates` after adding a signed XPI to regenerate `webextension/updates.json` from every valid signed release artifact. The workflow validates the latest signed XPI's embedded manifest, publishes Docker images to `git.kolkman.org/olaf/link-log:<backend-version>` and `:latest`, and creates a release README that describes the project, the current backend/container version, and the raw signed XPI download URL with the plugin version.
The extension's `update_url` points at the stable raw repository URL `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json`. Update `webextension/updates.json` with each signed XPI version and commit it together with the XPI. 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 extension's `update_url` points at the stable raw repository URL `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json`. Commit the regenerated `webextension/updates.json` together with each signed XPI. Release READMEs point to the raw signed XPI at `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-<version>.xpi`.
The workflow requires Gitea Actions secrets named `REGISTRY_USERNAME`, `REGISTRY_TOKEN`, and `RELEASE_TOKEN`. `REGISTRY_TOKEN` is a Gitea access token with permission to push packages; `RELEASE_TOKEN` needs permission to create releases and upload release assets. The workflow requires Gitea Actions secrets named `REGISTRY_USERNAME`, `REGISTRY_TOKEN`, and `RELEASE_TOKEN`. `REGISTRY_TOKEN` is a Gitea access token with permission to push packages; `RELEASE_TOKEN` needs permission to create releases and upload release assets.
+222
View File
@@ -1274,3 +1274,225 @@ Update the VIBE directory with what you have done.
### Assistant outcome ### 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. Appended the release workflow changes and this VIBE update request to `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md` in the existing append-only format.
### User
I want that the users is able to edit or delete labels(tags) that were created by the user itself. Also validate that any logged in user will only see the labels created by default, in the admin panel, and those by themselves, not by any other user. If this leads to an update in the database then if ownership of labels is unknown they may be grandfathered as-if created in the admin interface
### Assistant outcome
Implemented creator edit/delete rights for user labels on `/labels` and `/api/user/labels/{label_id}`, isolated label visibility so logged-in users only see default/admin labels and their own created labels, dynamically set `created_by` when new tags are saved from links, grandfathered existing tags with `NULL` ownership as default/admin labels, added `frontend/static/labels.js`, and expanded unit test coverage.
### User
Make sure that in the admin interface the labels can be edited
### Assistant outcome
Added `PUT /api/admin/labels/{label_id}` for administrator label renaming, updated `update_label` service function to accept `is_admin=True`, added inline edit controls to `frontend/static/admin.js` for administrator label management, and added regression test coverage.
### User
Make sure that the logs in VIBE are updated
### Assistant outcome
Updated `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md` with the recent user prompts and assistant outcomes.
### User
Update Changelog too
### Assistant outcome
Updated `CHANGELOG.MD` with the recent feature additions (user label CRUD, label visibility isolation, grandfathering unknown label ownership, and administrator label editing), and updated `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`.
### User
In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
### Assistant outcome
Added collapsible minimize/expand toggle buttons to all settings panels (`.settings-panel`) in the Admin interface. Clicking a panel header toggles its `.minimized` state and `aria-expanded` attribute, hiding the panel body content to show only the header and toggle icon. Added CSS rules and updated tests.
### User
Clicking on the collapse button doesn't toggle
### Assistant outcome
Fixed panel toggle initialization in `admin.js` to attach click handlers immediately on page load and `DOMContentLoaded` rather than waiting for async session validation calls to finish. Added `pointer-events: none` to button child elements in `style.css` and bound event listeners to target headers/buttons with event prevention to guarantee reliable click toggling.
### User
Give the header of each setting-panel a somewhat differing color
### Assistant outcome
Applied distinct theme accent colors (`var(--mauve)`, `var(--teal)`, `var(--peach)`, `var(--blue)`, `var(--lavender)`) to settings panel headers via `:nth-of-type` CSS rules, allowing panel toggle buttons to inherit the accent colors cleanly across all themes.
### User
change the background of the header too
### Assistant outcome
Added soft, translucent accent backgrounds (`color-mix` with `var(--surface-1)`) and accent left borders to each settings panel header in `style.css`. Updated `admin.js` to ensure clicking anywhere on the header bar toggles the panel minimize state cleanly. Passed all 55 tests.
### User
Make sure all setting-panels are collapsed when opening the page
### Assistant outcome
Updated `admin.html` and `admin.js` so all settings panels start with the `minimized` class and `aria-expanded="false"` by default, collapsing all panels on page open. Passed all 55 tests.
### User
Apply exactly the same functionality to the profile page
### Assistant outcome
Applied collapsible minimizable settings panels to the profile page (`user_profile.html` and `profile.js`), starting all panels collapsed by default with toggle buttons, distinct header colors/backgrounds, and aria-expanded state management. Passed all 55 tests.
### User
On the admin page under Available Themes, the page does not load available themes
### Assistant outcome
Fixed element ID conflict on `admin.html` where both the header theme submenu and the admin form container used `id="theme-options"`. Renamed the admin form container to `id="admin-theme-options"` and updated `admin.js` to target `#admin-theme-options`. Available themes now load correctly on the admin page. Passed all 55 tests.
### User
on the new-entry page the checkbox should be following the labels - now they are positioned above.
### Assistant outcome
Reordered the new-entry tag control markup so each label is followed by its checkbox. JavaScript syntax validation and the focused API test module passed with 35 tests.
### User
The checkboxes should be immediately to the left of the label not below left
### Assistant outcome
Restored checkbox-before-label ordering and added a scoped compact-sizing rule for new-entry tag checkboxes. This prevents the mobile global input-width rule from placing a checkbox on its own line. JavaScript syntax validation and the focused API test module passed with 35 tests.
### User
The checkbox takes the full width of the grid which forces the label to be printed underneath instead of directly next to it.
### Assistant outcome
Fixed the actual layout conflict: `.form-section label` uses a grid layout whose selector overrode the tag label's flex layout. Added the more specific `.form-section label.tag-checkbox` inline-flex rule and reset its checkbox margin, keeping each checkbox directly left of its tag text. The focused API test module passed with 35 tests and `git diff --check` passed.
### User
Only show the Mastodon publishing on new page if the user has Mastodon posting configured. Then default the checkbox to yes
### Assistant outcome
Added a safe `configured` status to the authenticated Mastodon configuration response. New Entry now hides its Mastodon publishing section unless the current user has both an instance and access token configured; when shown, its checkbox defaults to checked. Link creation accepts `post_to_mastodon`, allowing an unchecked control to skip Mastodon while preserving dispatch of other plugins. Added posting and configuration regression coverage.
### User
In the currently running contaier the user olaf has no mastodon configured but the mastodon checkbox is still visible
### Assistant outcome
Found that `.form-section { display: grid; }` appeared later in the stylesheet than `.hidden { display: none; }`, overriding the initial hidden state of the Mastodon fieldset. Added `.form-section.hidden { display: none; }`, so the publishing control stays hidden until the authenticated configuration check explicitly reveals it.
### User
When clicking on the logo always go to the home page
### Assistant outcome
Wrapped the header logo in each web template with an accessible home-page link. Extended the heading font selector for the new logo-link wrapper, preserving existing header styling. Confirmed all eight templates contain exactly one home-linked logo and the focused API test module passed with 36 tests.
### User
Add a red collor theme
### Assistant outcome
Added a Red theme to the theme catalog with a high-contrast crimson palette in the frontend stylesheet. It is enabled by default on new installations and is available to select under Admin > Available themes. Extended the theme-selection regression test to verify the public theme API returns it when enabled.
### User
Make the theme brighter and darker red
### Assistant outcome
Refined the Red theme palette with brighter white and red-tinted surfaces, plus deeper saturated crimson accents, borders, and shadows while preserving dark high-contrast text. The focused theme API test and whitespace validation passed.
### User
Since checkin d433a305f5cd8ccdafde8a0f7764462e8c167162 on the home page the filter toolbar moved so that the menu button and new entry are not in the top left anylonger - revert to the previous layout
### Assistant outcome
Confirmed the referenced commit did not change the feed header, then identified the current template had the toolbar outside its `.header-tools` wrapper. Restored the prior header structure: the New Entry and menu controls remain grouped above the filter toolbar on the right side of the home-page header. Added a rendered-page regression assertion for `.header-tools`.
### User
I want every user to filter on every available tag/label
### Assistant outcome
Separated feed filtering from label management: `/api/tags` now returns every tag/label to all callers, allowing complete filtering of the public feed. `/api/user/labels` remains ownership-scoped, so users still cannot manage other users' labels. Updated tag visibility regression coverage for authenticated and anonymous callers.
### User
tag filter doesn't seem to respond when pressed
### Assistant outcome
Updated the tag-filter change handler to pass the newly selected tag directly to the feed refresh instead of relying on the browser to persist and immediately reread the preference cookie. This makes filtering work even when cookie persistence is unavailable or delayed. Cache-busted the feed script to `feed.js?v=10` and added a regression assertion for the direct refresh path.
### User
The tag filter still does not allow me to select tags, even though the raw html contains the correct content. Also the user filter and the sort functionality work too
### Assistant outcome
Verified the live running container with Chromium and Playwright: selecting `#AI` changes the tag dropdown value, writes the preference cookie, and renders only matching feed entries. The deployed script already contains the direct-refresh handler, so cache-busted it again to `feed.js?v=11` and rebuilt the Compose service. Confirmed the live page serves the new asset version.
### User
I believe tag selection was still working for v0.1.0 - it is still broken
### Assistant outcome
Found the actual regression in the direct-refresh update: `Promise.all([loadUsers(), loadTags()]).then(loadFeed)` passed its results array into the new `selectedTag` parameter. The feed then attempted to call `toLowerCase()` on that array during initialization. Restored the v0.1.0 callback shape with `.then(() => loadFeed())`, retained direct selected-tag refreshes, added a regression assertion, and cache-busted the feed asset to `feed.js?v=12`.
### User
Don't let the frontend and plugin pull from the google foundry but make sure any necessary fonts are served from the linklog server. I would prefer the fonts to be updated at docker image building time.
### Assistant outcome
Removed the web frontend's Google Fonts import and added a Docker build-time font bundling script. Image builds now download pinned Asset, DM Sans, and Space Grotesk files into `frontend/static/fonts`, generate a local `fonts.css`, and serve them through LinkLog at `/static/fonts`. The Firefox extension did not make Google Font requests and continues to use bundled assets with local fallback fonts. A clean image build confirmed all nine local font assets are present.
### User
On the new-entry page follow the logic for existing pages that already exists in the plugin and display "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered." when the link exists. Also assess if the Auto-fill title button is necessary, or if the functionality can be automated while the URL is entered.
### Assistant outcome
Added a duplicate-check request (`GET /api/links/check`) to `new-entry.js`, triggered on URL/title blur, that shows the requested warning in a new `#duplicate-status` element and clears it as the fields are edited. Replaced the manual "Auto-fill Title" button with automatic scraping on URL blur (only filling the title when it is still empty and the URL actually changed), removing the now-unused button and CSS.
### User
Also: detect as duplicate when the URL has arguments (not already stripped). And: add a button to re-fetch the title for if the URL has been fetched but the user still edits the field.
### Assistant outcome
Added client-side stripping of known tracking parameters (`utm_*`, `gclid`, `fbclid`, etc.) mirroring the browser extension, applied consistently to the scrape lookup, duplicate check, and submission. Added a "Re-fetch Title" button next to the title field that force-refreshes the scraped title regardless of the auto-fill guard.
### User
If the link already exist with URL arguments then also display the warning, but add that the link has been stored additional parameters.
### Assistant outcome
Extended the duplicate warning to note when the stored link had additional URL parameters stripped (e.g. tracking parameters) compared to the entered URL.
### User
I want this last change to be more precise: I do not want to be warned when parameters are stripped, but when the URL entered has arguments/parameters and the URL in the database has none or different ones (even after tracking parameters are stripped).
### Assistant outcome
Added `find_owned_link_by_title` in `link_service.py` and extended `GET /api/links/check` to return `{exists, url_matches, stored_url}`, detecting a title match with a differing URL in addition to an exact match. `new-entry.js` now only warns about a differing stored URL when `url_matches` is false, no longer warning solely because tracking parameters were stripped from an otherwise matching URL.
### User
In the check duplicate I have a `<br>` tag, but that shows as formatted text on the page, I want a real break to occur at that position.
### Assistant outcome
Reworked `setStatus` in `new-entry.js` to split messages on `\n` and build real `<br>` elements via DOM APIs instead of relying on `textContent` (which escaped the literal `<br>`) or unsafe `innerHTML`.
### User
Update VIBE and Changelog.
### Assistant outcome
Appended the new-entry duplicate-detection and title auto-fill work to `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`, and added a Version v0.1.3 section to `CHANGELOG.MD`.
### User
Make sure the webplugin has the same functionality as just implemented in the new-entry page. Increase its version number to 0.2.0.
### Assistant outcome
Brought `webextension/popup.js` to parity with `new-entry.js`: the duplicate check now distinguishes an exact title/URL match from a title match with a differing stored URL (using the same `/api/links/check` `url_matches`/`stored_url` fields) and shows an additional localized note in the latter case; added a "Re-fetch title" button that calls the backend `/api/scrape` endpoint (guarded by existing backend-permission checks) and auto-fills the title on URL blur when empty; reworked `setStatus` to render real `<br>` line breaks via DOM APIs instead of `textContent`. Added `duplicateLinkDifferentUrl`, `refetchTitle`, and `titleFetchFailed` strings to all five locale files, updated `popup.html` with the new button, and bumped `manifest.json` to version `0.2.0`. Full backend test suite (36 tests) passed.
### User
Add a feature to the Make file that updates the updates.json file based on available signed releases.
### Assistant outcome
Added `make update-updates`, which regenerates `webextension/updates.json` from valid versioned signed XPIs. The generator reads each packaged manifest, validates its version, add-on ID, and Firefox minimum version, and ignores non-release artifacts.
### User
Add sha hashes to the updates.json
### Assistant outcome
Added Firefox-compatible `sha256:<hex>` update hashes generated from each signed XPI's bytes. Release validation now rejects missing or mismatched hashes; the generated metadata and release validator passed for signed versions 0.2.0 and 0.1.0.
### User
Update changelog and VIBE
### Assistant outcome
Recorded the signed-XPI update metadata automation and SHA-256 integrity hashes in the v0.2.0 changelog and VIBE logs.
### User
Make sure that when the plugin is signed the version in the link it the about page is updated too
### Assistant outcome
Extended `make update-updates` to set the About page plugin download URL to the newest valid signed XPI. Release validation now also rejects an About page whose link does not match the latest signed artifact; verified with LinkLog 0.2.0.
### User
Release script fails because the runner's hashlib module has no file_digest attribute.
### Assistant outcome
Replaced Python 3.11-only `hashlib.file_digest` calls in signed-XPI metadata generation and release validation with streaming SHA-256 calculations compatible with older Python runners. Regenerated update metadata and verified release validation passes.
+44
View File
@@ -224,6 +224,50 @@
211. Don't put new entry in the hamburger menu but present it as a seperate button next to the style selector 211. Don't put new entry in the hamburger menu but present it as a seperate button next to the style selector
212. Put the new entry button left of the hamburger menu 212. Put the new entry button left of the hamburger menu
213. The style selection should move into the hamburger menu - but in such a way that it becomes a submenu so that it doesn't clutter the menu structure 213. The style selection should move into the hamburger menu - but in such a way that it becomes a submenu so that it doesn't clutter the menu structure
214. I want that the users is able to edit or delete labels(tags) that were created by the user itself. Also validate that any logged in user will only see the labels created by default, in the admin panel, and those by themselves, not by any other user. If this leads to an update in the database then if ownership of labels is unknown they may be grandfathered as-if created in the admin interface
215. Make sure that in the admin interface the labels can be edited
216. Make sure that the logs in VIBE are updated
217. Update Changelog too
218. In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
219. Make sure all setting-panels are collapsed when opening the page
218. In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
219. Give the header of each setting-panel a somewhat differing color.
220. Change the background of the header too.
221. Apply exactly the same functionality to the profile page
222. On the admin page under Available Themes, the page does not load available themes
218. Give the header of each setting-panel a somewhat differing color
218. In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
219. Clicking on the collapse button doesn't toggle
218. In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
223. On the new-entry page the checkbox should be following the labels - now they are positioned above.
224. The checkboxes should be immediately to the left of the label not below left
225. The checkbox takes the full width of the grid which forces the label to be printed underneath instead of directly next to it.
226. Only show the Mastodon publishing on new page if the user has Mastodon posting configured. Then default the checkbox to yes
227. In the currently running contaier the user olaf has no mastodon configured but the mastodon checkbox is still visible
228. When clicking on the logo always go to the home page
229. Add a red collor theme
230. Make the theme brighter and darker red
231. Since checkin d433a305f5cd8ccdafde8a0f7764462e8c167162 on the home page the filter toolbar moved so that the menu button and new entry are not in the top left anylonger - revert to the previous layout
232. I want every user to filter on every available tag/label
233. tag filter doesn't seem to respond when pressed
234. The tag filter still does not allow me to select tags, even though the raw html contains the correct content. Also the user filter and the sort functionality work too
235. I believe tag selection was still working for v0.1.0 - it is still broken
236. Don't let the frontend and plugin pull from the google foundry but make sure any necessary fonts are served from the linklog server. I would prefer the fonts to be updated at docker image building time.
## 2026-08-28
237. On the new-entry page follow the logic for existing pages that already exists in the plugin and display "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered." when the link exists. Also assess if the Auto-fill title button is necessary, or if the functionality can be automated while the URL is entered.
238. Also: detect as duplicate when the URL has arguments (not already stripped). And: add a button to re-fetch the title for if the URL has been fetched but the user still edits the field.
239. If the link already exist with URL arguments then also display the warning, but add that the link has been stored additional parameters.
240. I want this last change to be more precise: I do not want to be warned when parameters are stripped, but when the URL entered has arguments/parameters and the URL in the database has none or different ones (even after tracking parameters are stripped).
241. In the check duplicate I have a `<br>` tag, but that shows as formatted text on the page, I want a real break to occur at that position.
242. Update VIBE and Changelog.
243. Make sure the webplugin has the same functionality as just implemented in the new-entry page. Increase its version number to 0.2.0.
244. Add a feature to the Make file that updates the updates.json file based on available signed releases.
245. Add sha hashes to the updates.json
246. Update changelog and VIBE
247. Make sure that when the plugin is signed the version in the link it the about page is updated too
248. Release script fails because the runner's hashlib module has no file_digest attribute.
## Future entries ## Future entries
Binary file not shown.
Binary file not shown.
Binary file not shown.
+17 -1
View File
@@ -10,7 +10,7 @@ from pydantic import BaseModel
from backend.app.api.dependencies import require_admin from backend.app.api.dependencies import require_admin
from backend.app.database import get_connection, hash_password from backend.app.database import get_connection, hash_password
from backend.app.services.link_service import delete_label from backend.app.services.link_service import delete_label, update_label
from backend.app.services.email_service import ( from backend.app.services.email_service import (
get_smtp_settings, get_smtp_settings,
save_smtp_settings, save_smtp_settings,
@@ -35,6 +35,10 @@ class AdminPluginUpdate(BaseModel):
config: dict | None = None config: dict | None = None
class AdminLabelUpdate(BaseModel):
name: str
class AdminUserCreate(BaseModel): class AdminUserCreate(BaseModel):
username: str username: str
email: str email: str
@@ -304,6 +308,18 @@ def admin_delete_label(label_id: str, current_user: dict = Depends(require_admin
return {'status': 'deleted', 'id': label_id} return {'status': 'deleted', 'id': label_id}
@router.put('/labels/{label_id}')
def admin_edit_label(label_id: str, payload: AdminLabelUpdate, current_user: dict = Depends(require_admin)):
try:
result = update_label(label_id, user_id=current_user['id'], name=payload.name, is_admin=True)
except ValueError as error:
raise HTTPException(status_code=409, detail=str(error)) from error
if result is None:
raise HTTPException(status_code=404, detail='Label not found')
record_audit_event(current_user['id'], 'label_updated', 'label', label_id)
return result
@router.get('/labels') @router.get('/labels')
def admin_list_labels(_: dict = Depends(require_admin)): def admin_list_labels(_: dict = Depends(require_admin)):
with get_connection() as conn: with get_connection() as conn:
+16
View File
@@ -38,6 +38,22 @@ def get_current_user(
return dict(user) return dict(user)
def get_optional_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
) -> dict | None:
if credentials is None or credentials.scheme.lower() != 'bearer':
return None
token_data = validate_token(credentials.credentials)
if token_data is None:
return None
with get_connection() as conn:
user = conn.execute(
'SELECT * FROM users WHERE id = ?',
(token_data['user_id'],),
).fetchone()
return dict(user) if user else None
def require_admin(user: dict = Depends(get_current_user)): def require_admin(user: dict = Depends(get_current_user)):
if not user['is_admin']: if not user['is_admin']:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Administrator access required') raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Administrator access required')
+14 -4
View File
@@ -2,11 +2,11 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
import json import json
from fastapi import APIRouter, Header, HTTPException, Response, status from fastapi import APIRouter, Depends, Header, HTTPException, Response, status
import logging import logging
from pydantic import BaseModel from pydantic import BaseModel
from backend.app.services.link_service import create_link, delete_link, find_owned_link_by_title_url, get_link_tags, get_owned_link, list_public_links, list_tags, mark_mastodon_posted, update_link from backend.app.services.link_service import create_link, delete_link, find_owned_link_by_title, find_owned_link_by_title_url, get_link_tags, get_owned_link, list_public_links, list_tags, mark_mastodon_posted, update_link
from backend.app.database import get_connection from backend.app.database import get_connection
from backend.app.services.plugin_manager import plugin_manager from backend.app.services.plugin_manager import plugin_manager
from backend.app.services.token_service import validate_token from backend.app.services.token_service import validate_token
@@ -23,6 +23,7 @@ class LinkCreate(BaseModel):
comment: str = '' comment: str = ''
timestamp: str | None = None timestamp: str | None = None
tags: list[str] = [] tags: list[str] = []
post_to_mastodon: bool = True
class LinkUpdate(BaseModel): class LinkUpdate(BaseModel):
@@ -64,7 +65,12 @@ def check_existing_link(
if info is None: if info is None:
raise HTTPException(status_code=401, detail='Token expired or invalid') raise HTTPException(status_code=401, detail='Token expired or invalid')
record = find_owned_link_by_title_url(info['user_id'], title, url) record = find_owned_link_by_title_url(info['user_id'], title, url)
return {'exists': record is not None} if record is not None:
return {'exists': True, 'url_matches': True, 'stored_url': record['url']}
record = find_owned_link_by_title(info['user_id'], title)
if record is not None:
return {'exists': True, 'url_matches': False, 'stored_url': record['url']}
return {'exists': False, 'url_matches': None, 'stored_url': None}
@router.post('/links', status_code=status.HTTP_201_CREATED) @router.post('/links', status_code=status.HTTP_201_CREATED)
@@ -87,7 +93,11 @@ def create_link_endpoint(payload: LinkCreate, response: Response, authorization:
raise HTTPException(status_code=422, detail=str(error)) from error raise HTTPException(status_code=422, detail=str(error)) from error
if duplicate: if duplicate:
response.status_code = status.HTTP_200_OK response.status_code = status.HTTP_200_OK
plugin_results = plugin_manager.dispatch({'type': 'link_created', **record}) plugin_results = plugin_manager.dispatch({
'type': 'link_created',
'post_to_mastodon': payload.post_to_mastodon,
**record,
})
mastodon_result = next((result for result in plugin_results if result.get('plugin') == 'mastodon'), None) mastodon_result = next((result for result in plugin_results if result.get('plugin') == 'mastodon'), None)
if mastodon_result and mastodon_result.get('status') == 'posted': if mastodon_result and mastodon_result.get('status') == 'posted':
mark_mastodon_posted(record['id'], info['user_id'], mastodon_result.get('post_id')) mark_mastodon_posted(record['id'], info['user_id'], mastodon_result.get('post_id'))
+2
View File
@@ -390,6 +390,8 @@ def get_user_plugin_config(plugin_name: str, user: dict = Depends(get_current_us
return {} return {}
config = json.loads(row['config']) if row['config'] else {} config = json.loads(row['config']) if row['config'] else {}
if plugin_name == 'mastodon':
config['configured'] = bool(config.get('instance') and config.get('access_token'))
if config.get('access_token'): if config.get('access_token'):
config.pop('access_token') config.pop('access_token')
return config return config
+12 -2
View File
@@ -1,7 +1,8 @@
## Copyright © 2026 Olaf Kolkman ## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
from dataclasses import dataclass from dataclasses import dataclass, field
import json
import os import os
from pathlib import Path from pathlib import Path
@@ -10,6 +11,7 @@ from cryptography.fernet import Fernet
BASE_DIR = Path(__file__).resolve().parent.parent.parent BASE_DIR = Path(__file__).resolve().parent.parent.parent
DB_PATH = BASE_DIR / 'data' / 'linklog.db' DB_PATH = BASE_DIR / 'data' / 'linklog.db'
VERSION_FILE = BASE_DIR.parent / 'frontend' / 'version.json'
def normalize_public_url(value: str) -> str: def normalize_public_url(value: str) -> str:
@@ -20,11 +22,19 @@ def normalize_public_url(value: str) -> str:
return f'{scheme}://{value}' return f'{scheme}://{value}'
def load_version() -> str:
# frontend/version.json is the single source of truth for the app version, shared by backend and frontend.
try:
return json.loads(VERSION_FILE.read_text())['version']
except (OSError, KeyError, ValueError):
return '0.0.0'
@dataclass @dataclass
class Settings: class Settings:
app_env: str = os.getenv('APP_ENV', 'development').lower() app_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.1') version: str = field(default_factory=load_version)
database_url: str = os.getenv('LINKLOG_DATABASE_URL', f'sqlite:///{DB_PATH}') database_url: str = os.getenv('LINKLOG_DATABASE_URL', f'sqlite:///{DB_PATH}')
secret_key: str = os.getenv('LINKLOG_SECRET_KEY', 'dev-secret-key-change-me') secret_key: str = os.getenv('LINKLOG_SECRET_KEY', 'dev-secret-key-change-me')
data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '') data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
+30 -9
View File
@@ -27,7 +27,7 @@ def normalize_tags(tags: list[str] | None) -> list[str]:
return normalized return normalized
def save_link_tags(conn, link_id: str, tags: list[str]) -> None: def save_link_tags(conn, link_id: str, tags: list[str], user_id: str | None = None) -> list[str]:
canonical_tags = [] canonical_tags = []
for tag in tags: for tag in tags:
tag_row = conn.execute( tag_row = conn.execute(
@@ -36,8 +36,8 @@ def save_link_tags(conn, link_id: str, tags: list[str]) -> None:
).fetchone() ).fetchone()
if tag_row is None: if tag_row is None:
conn.execute( conn.execute(
'INSERT INTO tags (id, name) VALUES (?, ?)', 'INSERT INTO tags (id, name, created_by) VALUES (?, ?, ?)',
(str(uuid4()), tag), (str(uuid4()), tag, user_id),
) )
tag_row = conn.execute('SELECT id FROM tags WHERE name = ?', (tag,)).fetchone() tag_row = conn.execute('SELECT id FROM tags WHERE name = ?', (tag,)).fetchone()
conn.execute( conn.execute(
@@ -103,7 +103,7 @@ def create_link(
record['is_public'], record['is_public'],
), ),
) )
stored_tags = save_link_tags(conn, record['id'], normalized_tags) stored_tags = save_link_tags(conn, record['id'], normalized_tags, user_id=user_id)
conn.commit() conn.commit()
record['tags'] = stored_tags record['tags'] = stored_tags
return record return record
@@ -123,6 +123,19 @@ def find_owned_link_by_title_url(user_id: str, title: str, url: str) -> dict | N
return record return record
def find_owned_link_by_title(user_id: str, title: str) -> dict | None:
with get_connection() as conn:
row = conn.execute(
'SELECT * FROM links WHERE user_id = ? AND title = ? ORDER BY created_at DESC LIMIT 1',
(user_id, title),
).fetchone()
if row is None:
return None
record = dict(row)
record['tags'] = get_link_tags(conn, record['id'])
return record
def 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(
@@ -173,7 +186,7 @@ def update_link(
if cursor.rowcount == 0: if cursor.rowcount == 0:
return None return None
conn.execute('DELETE FROM link_tags WHERE link_id = ?', (link_id,)) conn.execute('DELETE FROM link_tags WHERE link_id = ?', (link_id,))
stored_tags = save_link_tags(conn, link_id, normalized_tags) stored_tags = save_link_tags(conn, link_id, normalized_tags, user_id=user_id)
conn.commit() conn.commit()
row = conn.execute('SELECT * FROM links WHERE id = ?', (link_id,)).fetchone() row = conn.execute('SELECT * FROM links WHERE id = ?', (link_id,)).fetchone()
record = dict(row) record = dict(row)
@@ -242,7 +255,15 @@ def list_tags():
def list_user_labels(user_id: str): def list_user_labels(user_id: str):
with get_connection() as conn: with get_connection() as conn:
rows = conn.execute( rows = conn.execute(
'SELECT id, name, created_by FROM tags WHERE created_by = ? ORDER BY name', '''
SELECT tags.id, tags.name, tags.created_by, users.username AS creator
FROM tags
LEFT JOIN users ON users.id = tags.created_by
WHERE tags.created_by IS NULL
OR tags.created_by = ?
OR users.is_admin = 1
ORDER BY tags.name
''',
(user_id,), (user_id,),
).fetchall() ).fetchall()
return [dict(row) for row in rows] return [dict(row) for row in rows]
@@ -268,7 +289,7 @@ def create_label(user_id: str, name: str):
return {'id': label_id, 'name': label, 'created_by': user_id} return {'id': label_id, 'name': label, 'created_by': user_id}
def update_label(label_id: str, user_id: str, name: str): def update_label(label_id: str, user_id: str | None = None, name: str = '', is_admin: bool = False):
normalized = normalize_tags([name]) normalized = normalize_tags([name])
if not normalized: if not normalized:
raise ValueError('Label cannot be empty') raise ValueError('Label cannot be empty')
@@ -276,7 +297,7 @@ def update_label(label_id: str, user_id: str, name: str):
current = conn.execute( current = conn.execute(
'SELECT id, name, created_by FROM tags WHERE id = ?', (label_id,) 'SELECT id, name, created_by FROM tags WHERE id = ?', (label_id,)
).fetchone() ).fetchone()
if current is None or current['created_by'] != user_id: if current is None or (not is_admin and current['created_by'] != user_id):
return None return None
duplicate = conn.execute( duplicate = conn.execute(
'SELECT id FROM tags WHERE lower(name) = lower(?) AND id != ?', 'SELECT id FROM tags WHERE lower(name) = lower(?) AND id != ?',
@@ -286,7 +307,7 @@ def update_label(label_id: str, user_id: str, name: str):
raise ValueError('Label already exists') raise ValueError('Label already exists')
conn.execute('UPDATE tags SET name = ? WHERE id = ?', (normalized[0], label_id)) conn.execute('UPDATE tags SET name = ? WHERE id = ?', (normalized[0], label_id))
conn.commit() conn.commit()
return {'id': label_id, 'name': normalized[0], 'created_by': user_id} return {'id': label_id, 'name': normalized[0], 'created_by': current['created_by']}
def delete_label(label_id: str, user_id: str | None = None, is_admin: bool = False): def delete_label(label_id: str, user_id: str | None = None, is_admin: bool = False):
+3
View File
@@ -34,6 +34,9 @@ class MastodonPlugin(BasePlugin):
return True return True
def handle_event(self, event): def handle_event(self, event):
if not event.get('post_to_mastodon', True):
return {'status': 'skipped', 'plugin': self.name, 'reason': 'not_requested'}
config = dict(self.config) config = dict(self.config)
user_id = event.get('user_id') user_id = event.get('user_id')
if user_id: if user_id:
+1
View File
@@ -16,6 +16,7 @@ THEMES = {
'dracula': {'label': 'Dracula', 'description': 'A vivid dark theme with high-contrast accents.'}, 'dracula': {'label': 'Dracula', 'description': 'A vivid dark theme with high-contrast accents.'},
'nord': {'label': 'Nord', 'description': 'A cool, muted blue-gray theme.'}, 'nord': {'label': 'Nord', 'description': 'A cool, muted blue-gray theme.'},
'solarized': {'label': 'Solarized', 'description': 'A balanced theme available in a light style.'}, 'solarized': {'label': 'Solarized', 'description': 'A balanced theme available in a light style.'},
'red': {'label': 'Red', 'description': 'A warm crimson theme with high-contrast surfaces.'},
} }
DEFAULT_ENABLED_THEMES = tuple(THEMES) DEFAULT_ENABLED_THEMES = tuple(THEMES)
+125 -16
View File
@@ -2,6 +2,7 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
import json import json
from pathlib import Path
import threading import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs from urllib.parse import parse_qs
@@ -11,7 +12,8 @@ from unittest.mock import MagicMock, patch
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from backend.app.main import app from backend.app.main import app
from backend.app.database import get_connection from backend.app.core.config import settings
from backend.app.database import get_connection, hash_password
from backend.app.services.email_service import get_smtp_settings from backend.app.services.email_service import get_smtp_settings
from backend.app.services.login_throttle import clear_login_failures from backend.app.services.login_throttle import clear_login_failures
from backend.app.services.otp_service import current_code from backend.app.services.otp_service import current_code
@@ -31,7 +33,7 @@ def login_headers(username='alice'):
def test_login_returns_token(): def test_login_returns_token():
assert app.version == '0.1.1' assert app.version == settings.version
response = client.post('/api/auth/login', json={ response = client.post('/api/auth/login', json={
'email': 'alice@example.com', 'email': 'alice@example.com',
'password': 'secret123', 'password': 'secret123',
@@ -150,10 +152,10 @@ def test_configuration_requires_authentication_and_admin_role():
def test_admin_can_select_multiple_themes(): def test_admin_can_select_multiple_themes():
headers = login_headers() headers = login_headers()
response = client.put('/api/admin/themes', headers=headers, json={ response = client.put('/api/admin/themes', headers=headers, json={
'themes': ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized'], 'themes': ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized', 'red'],
}) })
assert response.status_code == 200 assert response.status_code == 200
assert response.json()['enabled'] == ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized'] assert response.json()['enabled'] == ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized', 'red']
public_response = client.get('/api/public/themes') public_response = client.get('/api/public/themes')
assert public_response.status_code == 200 assert public_response.status_code == 200
assert [theme['id'] for theme in public_response.json()] == response.json()['enabled'] assert [theme['id'] for theme in public_response.json()] == response.json()['enabled']
@@ -490,25 +492,102 @@ def test_admin_can_toggle_privileges_without_removing_last_admin():
assert last_admin.status_code == 400 assert last_admin.status_code == 400
def test_users_manage_owned_labels_and_admin_can_delete_any_label(): def test_users_manage_owned_labels_and_admin_can_edit_and_delete_any_label():
alice_headers = login_headers('alice') alice_headers = login_headers('alice') # admin
created = client.post('/api/user/labels', headers=alice_headers, json={'name': 'My Label'}) bob_headers = login_headers('bob') # non-admin
created = client.post('/api/user/labels', headers=bob_headers, json={'name': 'Bob Label'})
assert created.status_code == 201 assert created.status_code == 201
label = created.json() label = created.json()
assert label['name'] == '#My Label' assert label['name'] == '#Bob Label'
edited = client.put(f"/api/user/labels/{label['id']}", headers=alice_headers, json={'name': '#Renamed'}) # Bob renames own label
edited = client.put(f"/api/user/labels/{label['id']}", headers=bob_headers, json={'name': '#RenamedByBob'})
assert edited.status_code == 200 assert edited.status_code == 200
assert edited.json()['name'] == '#Renamed' assert edited.json()['name'] == '#RenamedByBob'
denied = client.put(f"/api/user/labels/{label['id']}", headers=login_headers('bob'), json={'name': '#Nope'}) # Non-owner Alice can edit it via admin endpoint, but NOT user endpoint
assert denied.status_code == 404 user_denied = client.put(f"/api/user/labels/{label['id']}", headers=alice_headers, json={'name': '#NopeUser'})
assert client.delete(f"/api/user/labels/{label['id']}", headers=login_headers('bob')).status_code == 404 assert user_denied.status_code == 404
admin_edited = client.put(f"/api/admin/labels/{label['id']}", headers=alice_headers, json={'name': '#AdminRenamed'})
assert admin_edited.status_code == 200
assert admin_edited.json()['name'] == '#AdminRenamed'
# Non-admin Bob cannot access admin edit endpoint
bob_admin_denied = client.put(f"/api/admin/labels/{label['id']}", headers=bob_headers, json={'name': '#NopeAdmin'})
assert bob_admin_denied.status_code == 403
# Admin delete
admin_delete = client.delete(f"/api/admin/labels/{label['id']}", headers=alice_headers) admin_delete = client.delete(f"/api/admin/labels/{label['id']}", headers=alice_headers)
assert admin_delete.status_code == 200 assert admin_delete.status_code == 200
def test_label_visibility_isolation_and_grandfathering():
alice_headers = login_headers('alice')
bob_headers = login_headers('bob')
# Create non-admin user charlie
with get_connection() as conn:
conn.execute(
'''INSERT OR IGNORE INTO users (id, username, email, password_hash, is_admin, email_verified)
VALUES (?, ?, ?, ?, 0, 1)''',
('user-3', 'charlie', 'charlie@example.com', hash_password('secret123')),
)
conn.commit()
charlie_headers = login_headers('charlie')
# Create Bob label (non-admin)
created_bob = client.post('/api/user/labels', headers=bob_headers, json={'name': 'BobOnlyLabel'}).json()
# Create Charlie label (non-admin)
created_charlie = client.post('/api/user/labels', headers=charlie_headers, json={'name': 'CharlieOnlyLabel'}).json()
# Grandfathered label in DB with NULL created_by
from uuid import uuid4
grandfathered_id = str(uuid4())
with get_connection() as conn:
conn.execute('INSERT INTO tags (id, name, created_by) VALUES (?, ?, NULL)', (grandfathered_id, '#GrandfatheredLabel'))
conn.commit()
# Bob views /api/user/labels: sees default tags, grandfathered tag, and Bob tag, NOT Charlie tag
bob_labels = client.get('/api/user/labels', headers=bob_headers).json()
bob_label_names = [l['name'] for l in bob_labels]
assert '#BobOnlyLabel' in bob_label_names
assert '#GrandfatheredLabel' in bob_label_names
assert '#Cybersecurity' in bob_label_names
assert '#CharlieOnlyLabel' not in bob_label_names
# Charlie views /api/user/labels: sees default tags, grandfathered tag, and Charlie tag, NOT Bob tag
charlie_labels = client.get('/api/user/labels', headers=charlie_headers).json()
charlie_label_names = [l['name'] for l in charlie_labels]
assert '#CharlieOnlyLabel' in charlie_label_names
assert '#GrandfatheredLabel' in charlie_label_names
assert '#Cybersecurity' in charlie_label_names
assert '#BobOnlyLabel' not in charlie_label_names
# Every user can filter by every available tag, including another user's label.
bob_tags = client.get('/api/tags', headers=bob_headers).json()
assert '#BobOnlyLabel' in bob_tags
assert '#GrandfatheredLabel' in bob_tags
assert '#CharlieOnlyLabel' in bob_tags
# The public feed filter has the same complete tag catalog.
anon_tags = client.get('/api/tags').json()
assert '#GrandfatheredLabel' in anon_tags
assert '#BobOnlyLabel' in anon_tags
assert '#CharlieOnlyLabel' in anon_tags
# Bob cannot edit or delete grandfathered label
assert client.put(f"/api/user/labels/{grandfathered_id}", headers=bob_headers, json={'name': '#RenamedGrandfathered'}).status_code == 404
assert client.delete(f"/api/user/labels/{grandfathered_id}", headers=bob_headers).status_code == 404
# Clean up created labels
client.delete(f"/api/user/labels/{created_bob['id']}", headers=bob_headers)
client.delete(f"/api/user/labels/{created_charlie['id']}", headers=charlie_headers)
client.delete(f"/api/admin/labels/{grandfathered_id}", headers=alice_headers)
def test_labels_page_renders_authenticated_management_shell(): def test_labels_page_renders_authenticated_management_shell():
page = client.get('/labels') page = client.get('/labels')
assert page.status_code == 200 assert page.status_code == 200
@@ -715,6 +794,7 @@ def test_public_and_admin_pages_render_html():
assert 'alice' in user_page assert 'alice' in user_page
assert 'data-user-filter="alice"' in user_page assert 'data-user-filter="alice"' in user_page
assert 'profile-summary' in user_page assert 'profile-summary' in user_page
assert '<div class="header-tools">' in user_page
feed_script = TestClient(app).get('/static/feed.js?v=4').text feed_script = TestClient(app).get('/static/feed.js?v=4').text
assert 'window.location.assign(selectedUser ? `/${encodeURIComponent(selectedUser)}/` : \'/\')' in feed_script assert 'window.location.assign(selectedUser ? `/${encodeURIComponent(selectedUser)}/` : \'/\')' in feed_script
assert client.get('/login').status_code == 200 assert client.get('/login').status_code == 200
@@ -728,7 +808,9 @@ def test_public_and_admin_pages_render_html():
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 '<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 updates = json.loads((Path(__file__).resolve().parents[2] / 'webextension' / 'updates.json').read_text())
latest_update = updates['addons']['linklog@kolkman.org']['updates'][0]
assert latest_update['update_link'] in about_page.text
assert 'id="auth-about-link" href="/about"' in about_page.text assert 'id="auth-about-link" href="/about"' in about_page.text
assert client.get('/admin').status_code == 200 assert client.get('/admin').status_code == 200
admin_page = client.get('/admin').text admin_page = client.get('/admin').text
@@ -738,12 +820,23 @@ def test_public_and_admin_pages_render_html():
assert 'id="auth-menu" class="auth-menu hidden"' in admin_page assert 'id="auth-menu" class="auth-menu hidden"' in admin_page
assert 'id="auth-home-link" href="/">Home</a>' in admin_page assert 'id="auth-home-link" href="/">Home</a>' in admin_page
assert '<a id="auth-username" class="user-name" href="/">' in admin_page assert '<a id="auth-username" class="user-name" href="/">' in admin_page
assert 'admin.js?v=5' in admin_page assert 'class="panel-toggle-btn"' in admin_page
assert 'admin.js?v=7' in admin_page
assert client.get('/profile').status_code == 200
profile_page = client.get('/profile').text
assert 'Profile' in profile_page
assert 'class="link-item settings-panel minimized"' in profile_page
assert 'class="panel-toggle-btn"' in profile_page
assert 'profile.js?v=6' in profile_page
feed_script = client.get('/static/feed.js?v=7').text feed_script = client.get('/static/feed.js?v=7').text
assert 'if (item.is_owner && !showIdentity)' in feed_script assert 'if (item.is_owner && !showIdentity)' in feed_script
assert 'deleteEntry(item, deleteButton)' in feed_script assert 'deleteEntry(item, deleteButton)' in feed_script
assert 'postToMastodon(item, mastodonButton)' in feed_script assert 'postToMastodon(item, mastodonButton)' in feed_script
assert 'tag.toLowerCase() === pref.tag.toLowerCase()' in feed_script assert 'tag.toLowerCase() === activeTag.toLowerCase()' in feed_script
assert 'loadFeed(event.target.value)' in feed_script
assert 'Promise.all([loadUsers(), loadTags()]).then(() => loadFeed())' in feed_script
assert "fetch('/api/tags', {" in feed_script
assert 'Authorization: `Bearer ${accessToken}`' in feed_script
assert 'return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`' in feed_script assert 'return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`' in feed_script
assert "entryMeta.className = 'entry-meta'" in feed_script assert "entryMeta.className = 'entry-meta'" in feed_script
assert "meta.className = 'meta'" in feed_script assert "meta.className = 'meta'" in feed_script
@@ -752,6 +845,9 @@ def test_public_and_admin_pages_render_html():
assert 'edit-tag-options' in feed_script assert 'edit-tag-options' in feed_script
assert 'new_tags' in feed_script assert 'new_tags' in feed_script
assert 'A link can have at most 10 tags.' in feed_script assert 'A link can have at most 10 tags.' in feed_script
style_sheet = client.get('/static/style.css').text
assert "@import url('/static/fonts/fonts.css');" in style_sheet
assert 'fonts.googleapis.com' not in style_sheet
def test_link_submission_posts_to_enabled_mastodon_plugin(): def test_link_submission_posts_to_enabled_mastodon_plugin():
@@ -805,6 +901,18 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
server.server_close() server.server_close()
def test_link_submission_can_skip_mastodon_posting():
with patch('backend.app.api.links.plugin_manager.dispatch', return_value=[]) as dispatch:
response = client.post('/api/links', headers=login_headers(), json={
'title': 'Private share',
'url': 'https://example.com/private-share',
'post_to_mastodon': False,
})
assert response.status_code == 201
assert dispatch.call_args.args[0]['post_to_mastodon'] is False
def test_mastodon_post_without_title_omits_source_line(): def test_mastodon_post_without_title_omits_source_line():
from backend.app.services.plugin_manager import MastodonPlugin from backend.app.services.plugin_manager import MastodonPlugin
@@ -838,6 +946,7 @@ def test_plugin_config_can_be_saved_for_mastodon():
payload = client.get('/api/user/plugins/mastodon', headers=headers).json() payload = client.get('/api/user/plugins/mastodon', headers=headers).json()
assert payload['instance'] == 'mastodon.social' assert payload['instance'] == 'mastodon.social'
assert payload['post_prefix'] == 'From my #LinkLog: ' assert payload['post_prefix'] == 'From my #LinkLog: '
assert payload['configured'] is True
admin_update = client.put('/api/admin/plugins/mastodon', headers=headers, json={ admin_update = client.put('/api/admin/plugins/mastodon', headers=headers, json={
'enabled': True, 'enabled': True,
+1 -1
View File
@@ -2,7 +2,7 @@
services: services:
app: app:
image: git.kolkman.org/olaf/link-log:development # or :latest or a version-tag image: git.kolkman.org/olaf/link-log:${LINKLOG_VERSION:-latest} # or :development or a :version-tag
container_name: ${APP_CONTAINER_NAME:-linklog-app} container_name: ${APP_CONTAINER_NAME:-linklog-app}
volumes: volumes:
- ./linklog_data:/app/backend/data - ./linklog_data:/app/backend/data
+116 -7
View File
@@ -12,7 +12,7 @@ const smtpForm = document.querySelector('#smtp-form');
const smtpTestButton = document.querySelector('#smtp-test-button'); const smtpTestButton = document.querySelector('#smtp-test-button');
const smtpStatus = document.querySelector('#smtp-status'); const smtpStatus = document.querySelector('#smtp-status');
const themesForm = document.querySelector('#themes-form'); const themesForm = document.querySelector('#themes-form');
const themeOptions = document.querySelector('#theme-options'); const themeOptions = document.querySelector('#admin-theme-options');
const themeStatus = document.querySelector('#theme-status'); const themeStatus = document.querySelector('#theme-status');
let smtpNextAllowedAt = null; let smtpNextAllowedAt = null;
let smtpTimerHandle = null; let smtpTimerHandle = null;
@@ -57,21 +57,85 @@ function renderLabels(labels) {
adminLabelList.replaceChildren(...labels.map((label) => { adminLabelList.replaceChildren(...labels.map((label) => {
const row = document.createElement('div'); const row = document.createElement('div');
row.className = 'plugin-row'; row.className = 'plugin-row';
const text = document.createElement('span'); const text = document.createElement('span');
text.textContent = `${label.name}${label.creator ? ` (${label.creator})` : ' (default)'}`; text.textContent = `${label.name}${label.creator ? ` (${label.creator})` : ' (default)'}`;
const button = document.createElement('button');
button.type = 'button'; const actions = document.createElement('div');
button.className = 'danger-button'; actions.style.display = 'flex';
button.textContent = 'Delete'; actions.style.gap = '8px';
button.addEventListener('click', async () => {
const editButton = document.createElement('button');
editButton.type = 'button';
editButton.textContent = 'Edit';
editButton.addEventListener('click', () => {
showAdminInlineLabelEdit(row, label);
});
const deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.className = 'danger-button';
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', async () => {
if (!confirm(`Are you sure you want to delete "${label.name}"?`)) return;
const response = await fetch(`/api/admin/labels/${label.id}`, {method: 'DELETE', headers: authHeaders()}); const response = await fetch(`/api/admin/labels/${label.id}`, {method: 'DELETE', headers: authHeaders()});
if (response.ok) loadLabels(); if (response.ok) loadLabels();
}); });
row.append(text, button);
actions.append(editButton, deleteButton);
row.append(text, actions);
return row; return row;
})); }));
} }
function showAdminInlineLabelEdit(rowContainer, label) {
rowContainer.replaceChildren();
const editForm = document.createElement('form');
editForm.style.display = 'flex';
editForm.style.gap = '8px';
editForm.style.width = '100%';
editForm.style.alignItems = 'center';
const input = document.createElement('input');
input.type = 'text';
input.value = label.name;
input.required = true;
input.style.flex = '1';
const saveButton = document.createElement('button');
saveButton.type = 'submit';
saveButton.textContent = 'Save';
const cancelButton = document.createElement('button');
cancelButton.type = 'button';
cancelButton.textContent = 'Cancel';
cancelButton.addEventListener('click', () => {
loadLabels();
});
editForm.append(input, saveButton, cancelButton);
editForm.addEventListener('submit', async (e) => {
e.preventDefault();
const newName = input.value.trim();
if (!newName) return;
const response = await fetch(`/api/admin/labels/${label.id}`, {
method: 'PUT',
headers: authHeaders(true),
body: JSON.stringify({ name: newName }),
});
if (response.ok) {
loadLabels();
} else {
alert(await responseError(response, 'Could not update label'));
}
});
rowContainer.appendChild(editForm);
input.focus();
}
async function loadLabels() { async function loadLabels() {
const response = await fetch('/api/admin/labels', {headers: authHeaders()}); const response = await fetch('/api/admin/labels', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load labels'); if (!response.ok) throw new Error('Could not load labels');
@@ -195,9 +259,51 @@ async function loadUsers() {
renderUsers(await response.json()); renderUsers(await response.json());
} }
function initPanelToggles() {
const panels = document.querySelectorAll('#admin-controls .settings-panel');
panels.forEach((panel) => {
panel.classList.add('minimized');
const h2 = panel.querySelector('h2');
if (!h2) return;
let btn = h2.querySelector('.panel-toggle-btn');
if (!btn) {
const titleText = h2.textContent.trim();
h2.replaceChildren();
btn = document.createElement('button');
btn.type = 'button';
btn.className = 'panel-toggle-btn';
btn.setAttribute('aria-expanded', 'false');
const textSpan = document.createElement('span');
textSpan.textContent = titleText;
const iconSpan = document.createElement('span');
iconSpan.className = 'panel-toggle-icon';
iconSpan.setAttribute('aria-hidden', 'true');
iconSpan.textContent = '▼';
btn.append(textSpan, iconSpan);
h2.appendChild(btn);
} else {
btn.setAttribute('aria-expanded', 'false');
}
if (h2.dataset.initialized) return;
h2.dataset.initialized = 'true';
h2.addEventListener('click', (e) => {
e.preventDefault();
const isMinimized = panel.classList.toggle('minimized');
if (btn) {
btn.setAttribute('aria-expanded', String(!isMinimized));
}
});
});
}
function showAdminState(isAdmin) { function showAdminState(isAdmin) {
adminControls.classList.toggle('hidden', !isAdmin); adminControls.classList.toggle('hidden', !isAdmin);
adminAuthNotice.classList.toggle('hidden', isAdmin); adminAuthNotice.classList.toggle('hidden', isAdmin);
if (isAdmin) {
initPanelToggles();
}
} }
function showSignedOutState() { function showSignedOutState() {
@@ -382,4 +488,7 @@ loadAdminState().catch((error) => {
smtpForm.reset(); smtpForm.reset();
themesForm.reset(); themesForm.reset();
}); });
document.addEventListener('DOMContentLoaded', initPanelToggles);
initPanelToggles();
})(); })();
+9 -6
View File
@@ -73,7 +73,9 @@ async function loadUsers() {
} }
async function loadTags() { async function loadTags() {
const response = await fetch('/api/tags'); const response = await fetch('/api/tags', {
headers: accessToken ? {Authorization: `Bearer ${accessToken}`} : {},
});
if (!response.ok) throw new Error('Could not load tags'); if (!response.ok) throw new Error('Could not load tags');
const tags = await response.json(); const tags = await response.json();
availableTags = tags; availableTags = tags;
@@ -254,7 +256,7 @@ function showEditForm(article, item) {
article.appendChild(form); article.appendChild(form);
} }
async function loadFeed() { async function loadFeed(selectedTag = null) {
const routeUser = document.body.dataset.userFilter; const routeUser = document.body.dataset.userFilter;
const endpoint = routeUser const endpoint = routeUser
? `/api/public/feed/${encodeURIComponent(routeUser)}` ? `/api/public/feed/${encodeURIComponent(routeUser)}`
@@ -266,13 +268,14 @@ async function loadFeed() {
let items = data || []; let items = data || [];
const pref = readPreferences(); const pref = readPreferences();
const activeTag = selectedTag ?? pref.tag;
if (pref.user && !routeUser) { if (pref.user && !routeUser) {
items = items.filter((item) => (item.user?.username || '').toLowerCase() === pref.user.toLowerCase()); items = items.filter((item) => (item.user?.username || '').toLowerCase() === pref.user.toLowerCase());
} }
if (pref.tag) { if (activeTag) {
items = items.filter((item) => item.tags?.some((tag) => tag.toLowerCase() === pref.tag.toLowerCase())); items = items.filter((item) => item.tags?.some((tag) => tag.toLowerCase() === activeTag.toLowerCase()));
} }
if (pref.sort === 'oldest') { if (pref.sort === 'oldest') {
@@ -304,9 +307,9 @@ function syncPreferences() {
tagFilter.addEventListener('change', (event) => { tagFilter.addEventListener('change', (event) => {
const next = { ...readPreferences(), tag: event.target.value }; const next = { ...readPreferences(), tag: event.target.value };
writePreferences(next); writePreferences(next);
loadFeed(); loadFeed(event.target.value);
}); });
} }
syncPreferences(); syncPreferences();
Promise.all([loadUsers(), loadTags()]).then(loadFeed).catch(() => loadFeed()); Promise.all([loadUsers(), loadTags()]).then(() => loadFeed()).catch(() => loadFeed());
+209
View File
@@ -0,0 +1,209 @@
// Copyright © 2026 Olaf Kolkman
// SPDX-License-Identifier: GPL-3.0-or-later
(() => {
const labelAuthNotice = document.querySelector('#label-auth-notice');
const labelControls = document.querySelector('#label-controls');
const labelForm = document.querySelector('#label-form');
const labelNameInput = document.querySelector('#label-name');
const labelStatus = document.querySelector('#label-status');
const labelList = document.querySelector('#label-list');
const accessToken = localStorage.getItem('linklogAccessToken');
let currentUserId = null;
function authHeaders(includeJson = false) {
return {
...(includeJson ? {'Content-Type': 'application/json'} : {}),
...(accessToken ? {Authorization: `Bearer ${accessToken}`} : {}),
};
}
function setStatus(message, isError = false) {
if (!labelStatus) return;
labelStatus.textContent = message;
labelStatus.style.color = isError ? '#b91c1c' : '#166534';
}
async function responseError(response, fallback) {
try {
const result = await response.json();
return result.detail || result.message || fallback;
} catch {
return fallback;
}
}
function renderLabels(labels) {
if (!labelList) return;
if (!labels || labels.length === 0) {
labelList.innerHTML = '<p>No labels found.</p>';
return;
}
labelList.replaceChildren(...labels.map((label) => {
const row = document.createElement('div');
row.className = 'plugin-row';
const isOwned = label.created_by === currentUserId;
const contentContainer = document.createElement('div');
contentContainer.style.display = 'flex';
contentContainer.style.alignItems = 'center';
contentContainer.style.justifySpaceBetween = 'space-between';
contentContainer.style.width = '100%';
const text = document.createElement('span');
text.textContent = `${label.name}${isOwned ? '' : (label.creator ? ` (${label.creator})` : ' (default)')}`;
contentContainer.appendChild(text);
if (isOwned) {
const actions = document.createElement('div');
actions.style.display = 'flex';
actions.style.gap = '8px';
const editButton = document.createElement('button');
editButton.type = 'button';
editButton.textContent = 'Edit';
editButton.addEventListener('click', () => {
showInlineEdit(row, label);
});
const deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.className = 'danger-button';
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', async () => {
if (!confirm(`Are you sure you want to delete "${label.name}"?`)) return;
setStatus('');
const response = await fetch(`/api/user/labels/${label.id}`, {
method: 'DELETE',
headers: authHeaders(),
});
if (response.ok) {
setStatus(`Deleted label ${label.name}`);
loadLabels();
} else {
setStatus(await responseError(response, 'Could not delete label'), true);
}
});
actions.append(editButton, deleteButton);
contentContainer.appendChild(actions);
}
row.appendChild(contentContainer);
return row;
}));
}
function showInlineEdit(rowContainer, label) {
rowContainer.replaceChildren();
const editForm = document.createElement('form');
editForm.style.display = 'flex';
editForm.style.gap = '8px';
editForm.style.width = '100%';
editForm.style.alignItems = 'center';
const input = document.createElement('input');
input.type = 'text';
input.value = label.name;
input.required = true;
input.style.flex = '1';
const saveButton = document.createElement('button');
saveButton.type = 'submit';
saveButton.textContent = 'Save';
const cancelButton = document.createElement('button');
cancelButton.type = 'button';
cancelButton.textContent = 'Cancel';
cancelButton.addEventListener('click', () => {
loadLabels();
});
editForm.append(input, saveButton, cancelButton);
editForm.addEventListener('submit', async (e) => {
e.preventDefault();
const newName = input.value.trim();
if (!newName) return;
setStatus('');
const response = await fetch(`/api/user/labels/${label.id}`, {
method: 'PUT',
headers: authHeaders(true),
body: JSON.stringify({ name: newName }),
});
if (response.ok) {
setStatus(`Updated label to ${newName}`);
loadLabels();
} else {
setStatus(await responseError(response, 'Could not update label'), true);
}
});
rowContainer.appendChild(editForm);
input.focus();
}
async function loadLabels() {
try {
const response = await fetch('/api/user/labels', { headers: authHeaders() });
if (!response.ok) throw new Error('Could not load labels');
const labels = await response.json();
renderLabels(labels);
} catch (error) {
setStatus('Error loading labels', true);
}
}
async function init() {
if (!accessToken) {
if (labelAuthNotice) labelAuthNotice.classList.remove('hidden');
if (labelControls) labelControls.classList.add('hidden');
return;
}
if (labelAuthNotice) labelAuthNotice.classList.add('hidden');
if (labelControls) labelControls.classList.remove('hidden');
try {
const meResponse = await fetch('/api/auth/me', { headers: authHeaders() });
if (meResponse.ok) {
const me = await meResponse.json();
currentUserId = me.id;
}
} catch {
// Proceed if me fails
}
await loadLabels();
if (labelForm) {
labelForm.addEventListener('submit', async (e) => {
e.preventDefault();
const name = labelNameInput.value.trim();
if (!name) return;
setStatus('');
const response = await fetch('/api/user/labels', {
method: 'POST',
headers: authHeaders(true),
body: JSON.stringify({ name }),
});
if (response.ok) {
labelNameInput.value = '';
setStatus(`Added label ${name}`);
loadLabels();
} else {
setStatus(await responseError(response, 'Could not add label'), true);
}
});
}
}
document.addEventListener('DOMContentLoaded', init);
if (document.readyState !== 'loading') {
init();
}
})();
+102 -16
View File
@@ -9,9 +9,11 @@
const commentInput = document.getElementById('comment-input'); const commentInput = document.getElementById('comment-input');
const newTagsInput = document.getElementById('new-tags-input'); const newTagsInput = document.getElementById('new-tags-input');
const existingTagsEl = document.getElementById('existing-tags'); const existingTagsEl = document.getElementById('existing-tags');
const mastodonPublishing = document.getElementById('mastodon-publishing');
const mastodonEnabledCheckbox = document.getElementById('mastodon-enabled'); const mastodonEnabledCheckbox = document.getElementById('mastodon-enabled');
const scrapeButton = document.getElementById('scrape-button');
const scrapeStatus = document.getElementById('scrape-status'); const scrapeStatus = document.getElementById('scrape-status');
const duplicateStatus = document.getElementById('duplicate-status');
const refetchTitleButton = document.getElementById('refetch-title-button');
const submitButton = document.getElementById('submit-button'); const submitButton = document.getElementById('submit-button');
const submitStatus = document.getElementById('submit-status'); const submitStatus = document.getElementById('submit-status');
@@ -20,9 +22,14 @@
let selectedTags = new Set(); let selectedTags = new Set();
let currentUser = null; let currentUser = null;
// Utility function to add status messages // Utility function to add status messages; splits on \n into real <br> line breaks without using innerHTML.
function setStatus(statusEl, message, isError = false) { function setStatus(statusEl, message, isError = false) {
statusEl.textContent = message; const lines = message.split('\n');
statusEl.replaceChildren(
...lines.flatMap((line, index) => (
index === 0 ? [document.createTextNode(line)] : [document.createElement('br'), document.createTextNode(line)]
)),
);
statusEl.className = `status ${isError ? 'error' : 'success'}`; statusEl.className = `status ${isError ? 'error' : 'success'}`;
statusEl.classList.remove('hidden'); statusEl.classList.remove('hidden');
if (!isError) { if (!isError) {
@@ -46,7 +53,7 @@
.then((user) => { .then((user) => {
currentUser = user; currentUser = user;
entryForm.classList.remove('hidden'); entryForm.classList.remove('hidden');
loadTags(); Promise.all([loadTags(), loadMastodonPublishing()]);
}) })
.catch(() => { .catch(() => {
localStorage.removeItem('linklogAccessToken'); localStorage.removeItem('linklogAccessToken');
@@ -66,6 +73,20 @@
} }
} }
async function loadMastodonPublishing() {
try {
const response = await fetch('/api/user/plugins/mastodon', {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) return;
const config = await response.json();
mastodonEnabledCheckbox.checked = Boolean(config.configured);
mastodonPublishing.classList.toggle('hidden', !config.configured);
} catch (error) {
console.error('Could not load Mastodon configuration:', error);
}
}
// Render tag checkboxes // Render tag checkboxes
function renderTags() { function renderTags() {
existingTagsEl.innerHTML = ''; existingTagsEl.innerHTML = '';
@@ -91,17 +112,29 @@
}); });
} }
// Scrape URL for title // Strip known tracking parameters so duplicate detection and scraping ignore them, mirroring the browser extension.
scrapeButton.addEventListener('click', async (e) => { function removeKnownTrackingParams(urlString) {
e.preventDefault(); try {
const url = urlInput.value.trim(); const url = new URL(urlString);
if (!url) { const known = new Set([
setStatus(scrapeStatus, 'Please enter a URL', true); 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',
return; 'utm_id', 'utm_name', 'gclid', 'fbclid', 'dclid', 'msclkid',
]);
for (const key of known) {
url.searchParams.delete(key);
}
return url.toString();
} catch (error) {
return urlString;
} }
}
scrapeButton.disabled = true; // Fetch the page title for the given URL and fill it in, unless the user already typed one.
setStatus(scrapeStatus, 'Scraping...', false); let lastScrapedUrl = null;
async function fetchTitle(url, { force = false } = {}) {
if (!url || (!force && (titleInput.value.trim() || url === lastScrapedUrl))) return;
setStatus(scrapeStatus, 'Looking up title...', false);
try { try {
const response = await fetch(`/api/scrape?url=${encodeURIComponent(url)}`, { const response = await fetch(`/api/scrape?url=${encodeURIComponent(url)}`, {
@@ -117,6 +150,7 @@
throw new Error(`HTTP ${response.status}`); throw new Error(`HTTP ${response.status}`);
} }
lastScrapedUrl = url;
const data = await response.json(); const data = await response.json();
if (data.title) { if (data.title) {
titleInput.value = data.title; titleInput.value = data.title;
@@ -127,16 +161,67 @@
} catch (error) { } catch (error) {
console.error('Scrape error:', error); console.error('Scrape error:', error);
setStatus(scrapeStatus, `Error: ${error.message}`, true); setStatus(scrapeStatus, `Error: ${error.message}`, true);
} finally {
scrapeButton.disabled = false;
} }
}
urlInput.addEventListener('blur', async () => {
await fetchTitle(removeKnownTrackingParams(urlInput.value.trim()));
checkDuplicate();
}); });
refetchTitleButton.addEventListener('click', (e) => {
e.preventDefault();
const url = removeKnownTrackingParams(urlInput.value.trim());
if (!url) {
setStatus(scrapeStatus, 'Please enter a URL', true);
return;
}
titleInput.value = '';
fetchTitle(url, { force: true });
});
// Warn when the URL/title combination already exists for this user, mirroring the browser extension.
titleInput.addEventListener('blur', checkDuplicate);
urlInput.addEventListener('input', () => duplicateStatus.classList.add('hidden'));
titleInput.addEventListener('input', () => duplicateStatus.classList.add('hidden'));
async function checkDuplicate() {
const url = removeKnownTrackingParams(urlInput.value.trim());
const title = titleInput.value.trim();
if (!url || !title) return;
try {
const response = await fetch(`/api/links/check?${new URLSearchParams({ title, url })}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) return;
const data = await response.json();
if (data.exists) {
// Re-derive the match locally: browser URL normalization (e.g. trailing slashes) can
// make the server's raw string comparison disagree even when the URLs are equivalent.
const urlMatches = data.url_matches || (data.stored_url && removeKnownTrackingParams(data.stored_url) === url);
let message = 'This link already exists. ';
if (!urlMatches) {
message += 'But, the stored link has a different URL (missing or different parameters).';
message += '\nWhen you save the entry you risk a duplicate entry.';
} else {
message += '\nYou can still save the entry, which will update the existing entry\'s comment and or tags.';
}
setStatus(duplicateStatus, message, true);
} else {
duplicateStatus.classList.add('hidden');
}
} catch (error) {
// Duplicate checking is advisory; submission remains available.
}
}
// Handle form submission // Handle form submission
entryForm.addEventListener('submit', async (e) => { entryForm.addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
const url = urlInput.value.trim(); const url = removeKnownTrackingParams(urlInput.value.trim());
const title = titleInput.value.trim(); const title = titleInput.value.trim();
const comment = commentInput.value.trim(); const comment = commentInput.value.trim();
const newTags = newTagsInput.value.trim(); const newTags = newTagsInput.value.trim();
@@ -171,6 +256,7 @@
url, url,
comment, comment,
tags, tags,
post_to_mastodon: mastodonEnabledCheckbox.checked,
}), }),
}); });
+42
View File
@@ -310,6 +310,48 @@ passwordForm.addEventListener('submit', async (event) => {
if (response.ok) passwordForm.reset(); if (response.ok) passwordForm.reset();
}); });
function initPanelToggles() {
const panels = document.querySelectorAll('.settings-panel');
panels.forEach((panel) => {
panel.classList.add('minimized');
const h2 = panel.querySelector('h2');
if (!h2) return;
let btn = h2.querySelector('.panel-toggle-btn');
if (!btn) {
const titleText = h2.textContent.trim();
h2.replaceChildren();
btn = document.createElement('button');
btn.type = 'button';
btn.className = 'panel-toggle-btn';
btn.setAttribute('aria-expanded', 'false');
const textSpan = document.createElement('span');
textSpan.textContent = titleText;
const iconSpan = document.createElement('span');
iconSpan.className = 'panel-toggle-icon';
iconSpan.setAttribute('aria-hidden', 'true');
iconSpan.textContent = '▼';
btn.append(textSpan, iconSpan);
h2.appendChild(btn);
} else {
btn.setAttribute('aria-expanded', 'false');
}
if (h2.dataset.initialized) return;
h2.dataset.initialized = 'true';
h2.addEventListener('click', (e) => {
e.preventDefault();
const isMinimized = panel.classList.toggle('minimized');
if (btn) {
btn.setAttribute('aria-expanded', String(!isMinimized));
}
});
});
}
document.addEventListener('DOMContentLoaded', initPanelToggles);
initPanelToggles();
Promise.all([loadProfile(), loadMastodonConfig(), loadOtp(), loadEmailAddresses()]).catch((error) => { Promise.all([loadProfile(), loadMastodonConfig(), loadOtp(), loadEmailAddresses()]).catch((error) => {
setStatus('#profile-status', accessToken ? error.message : 'Please sign in first.', true); setStatus('#profile-status', accessToken ? error.message : 'Please sign in first.', true);
}); });
+126 -20
View File
@@ -1,7 +1,7 @@
/* Copyright © 2026 Olaf Kolkman */ /* Copyright © 2026 Olaf Kolkman */
/* SPDX-License-Identifier: GPL-3.0-or-later */ /* SPDX-License-Identifier: GPL-3.0-or-later */
@import url('https://fonts.googleapis.com/css2?family=Asset&family=DM+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap'); @import url('/static/fonts/fonts.css');
:root { :root {
--base: #1e1e2e; --base: #1e1e2e;
@@ -95,6 +95,15 @@
--border: rgba(7, 54, 66, 0.18); --shadow: 0 18px 50px rgba(7, 54, 66, 0.14); --border: rgba(7, 54, 66, 0.18); --shadow: 0 18px 50px rgba(7, 54, 66, 0.14);
} }
:root[data-theme='red'] {
--base: #fffafa; --mantle: #ffedef; --crust: #fbd6da;
--surface-0: #ffffff; --surface-1: #ffe2e6; --surface-2: #f4bbc4;
--text: #350810; --subtext: #5c1724; --muted: #8c4653;
--mauve: #9e1737; --lavender: #86132d; --blue: #216f91;
--teal: #087567; --peach: #b84324; --red: #a70d2d;
--border: rgba(83, 10, 25, 0.2); --shadow: 0 18px 50px rgba(122, 8, 33, 0.2);
}
*, *,
*::before, *::before,
*::after { *::after {
@@ -169,7 +178,7 @@ body::selection {
object-position: left center; object-position: left center;
} }
.site-header .site-logo + h1, .site-header .site-logo-link + h1,
.feed-link { .feed-link {
font-family: 'Asset', 'Space Grotesk', sans-serif; font-family: 'Asset', 'Space Grotesk', sans-serif;
} }
@@ -451,6 +460,108 @@ main.container {
margin-bottom: 0; margin-bottom: 0;
} }
#admin-controls {
display: grid;
gap: 16px;
}
.settings-panel + .settings-panel {
margin-top: 16px;
}
.settings-panel h2 {
margin: 0 0 12px;
padding: 10px 14px;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.2s ease, margin 0.2s ease;
}
.settings-panel h2:hover {
filter: brightness(1.08);
}
.settings-panel:nth-of-type(5n+1) h2 {
color: var(--mauve);
background: var(--surface-1);
background: color-mix(in srgb, var(--mauve) 14%, transparent);
border-left: 4px solid var(--mauve);
}
.settings-panel:nth-of-type(5n+2) h2 {
color: var(--teal);
background: var(--surface-1);
background: color-mix(in srgb, var(--teal) 14%, transparent);
border-left: 4px solid var(--teal);
}
.settings-panel:nth-of-type(5n+3) h2 {
color: var(--peach);
background: var(--surface-1);
background: color-mix(in srgb, var(--peach) 14%, transparent);
border-left: 4px solid var(--peach);
}
.settings-panel:nth-of-type(5n+4) h2 {
color: var(--blue);
background: var(--surface-1);
background: color-mix(in srgb, var(--blue) 14%, transparent);
border-left: 4px solid var(--blue);
}
.settings-panel:nth-of-type(5n+5) h2 {
color: var(--lavender);
background: var(--surface-1);
background: color-mix(in srgb, var(--lavender) 14%, transparent);
border-left: 4px solid var(--lavender);
}
.settings-panel.minimized h2 {
margin: 0;
}
.panel-toggle-btn {
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
width: 100% !important;
min-width: 0 !important;
padding: 0 !important;
border: none !important;
background: transparent !important;
color: inherit !important;
font: inherit !important;
font-size: 1rem !important;
font-weight: inherit !important;
cursor: pointer !important;
text-align: left !important;
box-shadow: none !important;
}
.panel-toggle-btn > * {
pointer-events: none;
}
.panel-toggle-btn:focus-visible {
outline: 2px solid var(--lavender) !important;
outline-offset: 2px !important;
}
.panel-toggle-icon {
font-size: 0.75rem;
transition: transform 0.2s ease;
margin-left: 8px;
color: var(--subtext);
}
.settings-panel.minimized .panel-toggle-icon {
transform: rotate(-90deg);
}
.settings-panel.minimized > *:not(h2) {
display: none !important;
}
.toolbar label, .toolbar label,
.settings-panel label { .settings-panel label {
display: grid; display: grid;
@@ -904,6 +1015,10 @@ button:disabled {
gap: 8px; gap: 8px;
} }
.form-section.hidden {
display: none;
}
.form-section label { .form-section label {
display: grid; display: grid;
gap: 6px; gap: 6px;
@@ -963,7 +1078,15 @@ button:disabled {
user-select: none; user-select: none;
} }
.form-section label.tag-checkbox {
display: inline-flex;
}
.tag-checkbox input { .tag-checkbox input {
width: auto;
min-width: 0;
flex: 0 0 auto;
margin: 0;
cursor: pointer; cursor: pointer;
} }
@@ -1010,8 +1133,7 @@ button:disabled {
transition: all 0.2s ease; transition: all 0.2s ease;
} }
.form-actions button[type='submit'], .form-actions button[type='submit'] {
#scrape-button:not(:disabled) {
background: var(--mauve); background: var(--mauve);
border: 1px solid var(--mauve); border: 1px solid var(--mauve);
color: var(--crust); color: var(--crust);
@@ -1027,22 +1149,6 @@ button:disabled {
cursor: not-allowed; cursor: not-allowed;
} }
#scrape-button {
background: var(--surface-1);
border: 1px solid var(--border);
color: var(--text);
}
#scrape-button:not(:disabled):hover {
background: var(--surface-2);
border-color: var(--text);
}
#scrape-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.form-actions a { .form-actions a {
background: var(--surface-1); background: var(--surface-1);
border: 1px solid var(--border); border: 1px solid var(--border);
+2 -2
View File
@@ -13,7 +13,7 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>About</h1> <h1>About</h1>
<p>A quiet place for the links worth keeping.</p> <p>A quiet place for the links worth keeping.</p>
</div> </div>
@@ -60,7 +60,7 @@
<section class="link-item"> <section class="link-item">
<h2>Plugin</h2> <h2>Plugin</h2>
<p>Install the Firefox plugin to save links directly from your browser. <a <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" href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.2.0.xpi"
download>Download and install the Plugin</a>.</p> download>Download and install the Plugin</a>.</p>
</section> </section>
</main> </main>
+38 -13
View File
@@ -13,7 +13,7 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>Admin</h1> <h1>Admin</h1>
<p>Manage users and plugin configuration</p> <p>Manage users and plugin configuration</p>
</div> </div>
@@ -44,8 +44,13 @@
<main class="container"> <main class="container">
<p id="admin-auth-notice" class="auth-notice hidden"></p> <p id="admin-auth-notice" class="auth-notice hidden"></p>
<div id="admin-controls" class="hidden"> <div id="admin-controls" class="hidden">
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Users</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Users</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<form id="user-form"> <form id="user-form">
<label> <label>
Username Username
@@ -69,16 +74,31 @@
<div id="user-list" class="plugin-list" aria-live="polite">Loading users...</div> <div id="user-list" class="plugin-list" aria-live="polite">Loading users...</div>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Plugins</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Plugins</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<div id="plugin-list" class="plugin-list" aria-live="polite">Loading plugins...</div> <div id="plugin-list" class="plugin-list" aria-live="polite">Loading plugins...</div>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Labels</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Labels</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<div id="admin-label-list" class="plugin-list" aria-live="polite">Loading labels...</div> <div id="admin-label-list" class="plugin-list" aria-live="polite">Loading labels...</div>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>SMTP settings</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>SMTP settings</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<form id="smtp-form"> <form id="smtp-form">
<label> <label>
SMTP host SMTP host
@@ -109,11 +129,16 @@
</form> </form>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Available themes</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Available themes</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<p>Choose the themes visitors may use.</p> <p>Choose the themes visitors may use.</p>
<form id="themes-form"> <form id="themes-form">
<div id="theme-options" class="theme-options" aria-live="polite">Loading themes...</div> <div id="admin-theme-options" class="theme-options" aria-live="polite">Loading themes...</div>
<button type="submit">Save themes</button> <button type="submit">Save themes</button>
<p id="theme-status" class="status" role="status"></p> <p id="theme-status" class="status" role="status"></p>
</form> </form>
@@ -124,6 +149,6 @@
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=2"></script> <script src="/static/logout.js?v=2"></script>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
<script src="/static/admin.js?v=5"></script> <script src="/static/admin.js?v=7"></script>
</body> </body>
</html> </html>
+2 -2
View File
@@ -13,7 +13,7 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<p>Public link feed</p> <p>Public link feed</p>
</div> </div>
<div class="header-tools"> <div class="header-tools">
@@ -86,6 +86,6 @@
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=3"></script> <script src="/static/logout.js?v=3"></script>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
<script src="/static/feed.js?v=9"></script> <script src="/static/feed.js?v=12"></script>
</body> </body>
</html> </html>
+1 -1
View File
@@ -13,7 +13,7 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>Labels</h1> <h1>Labels</h1>
<p>Manage your link labels</p> <p>Manage your link labels</p>
</div> </div>
+1 -1
View File
@@ -13,7 +13,7 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<p>Access your LinkLog settings</p> <p>Access your LinkLog settings</p>
</div> </div>
<div class="header-actions"> <div class="header-actions">
+9 -8
View File
@@ -13,11 +13,10 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<p>New Entry</p> <p>New Entry</p>
</div> </div>
<div class="header-tools"> <div class="header-actions">
<div class="header-actions">
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button> <button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
@@ -53,7 +52,6 @@
<span>URL</span> <span>URL</span>
<input id="url-input" name="url" type="url" required placeholder="https://example.com" /> <input id="url-input" name="url" type="url" required placeholder="https://example.com" />
</label> </label>
<button id="scrape-button" class="secondary" type="button">Auto-fill Title</button>
<div id="scrape-status" class="status hidden" aria-live="polite"></div> <div id="scrape-status" class="status hidden" aria-live="polite"></div>
</div> </div>
@@ -62,8 +60,11 @@
<span>Title</span> <span>Title</span>
<input id="title-input" name="title" type="text" required /> <input id="title-input" name="title" type="text" required />
</label> </label>
<button id="refetch-title-button" class="secondary" type="button">Re-fetch Title</button>
</div> </div>
<div id="duplicate-status" class="status hidden" aria-live="polite"></div>
<div class="form-section"> <div class="form-section">
<label> <label>
<span>Comment</span> <span>Comment</span>
@@ -80,11 +81,11 @@
</label> </label>
</fieldset> </fieldset>
<fieldset class="form-section"> <fieldset id="mastodon-publishing" class="form-section hidden">
<legend>Mastodon Publishing</legend> <legend>Mastodon Publishing</legend>
<label> <label>
<input id="mastodon-enabled" type="checkbox" /> <input id="mastodon-enabled" type="checkbox" checked />
Post to Mastodon (if configured) Post to Mastodon
</label> </label>
</fieldset> </fieldset>
@@ -102,6 +103,6 @@
</footer> </footer>
<script src="/static/auth-header.js"></script> <script src="/static/auth-header.js"></script>
<script src="/static/new-entry.js"></script> <script src="/static/new-entry.js?v=8"></script>
</body> </body>
</html> </html>
+1 -1
View File
@@ -13,7 +13,7 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>Configure LinkLog</h1> <h1>Configure LinkLog</h1>
<p>Create the first administrator and test email delivery.</p> <p>Create the first administrator and test email delivery.</p>
</div> </div>
+37 -12
View File
@@ -15,7 +15,7 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>Profile</h1> <h1>Profile</h1>
</div> </div>
<div class="header-actions"> <div class="header-actions">
@@ -43,8 +43,13 @@
</header> </header>
<main class="container"> <main class="container">
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Profile Settings</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Profile Settings</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<form id="profile-form"> <form id="profile-form">
<label> <label>
Username Username
@@ -69,8 +74,13 @@
</form> </form>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Email addresses</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Email addresses</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<div id="email-address-list" class="email-address-list" aria-live="polite">Loading email addresses...</div> <div id="email-address-list" class="email-address-list" aria-live="polite">Loading email addresses...</div>
<form id="additional-email-form"> <form id="additional-email-form">
<label> <label>
@@ -82,8 +92,13 @@
</form> </form>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Password</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Password</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<form id="password-form"> <form id="password-form">
<label> <label>
Current password Current password
@@ -102,8 +117,13 @@
</form> </form>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>One-time password</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>One-time password</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<p>Use an authenticator app to add a second sign-in step.</p> <p>Use an authenticator app to add a second sign-in step.</p>
<div id="otp-disabled"> <div id="otp-disabled">
<button id="otp-setup" type="button">Set up one-time password</button> <button id="otp-setup" type="button">Set up one-time password</button>
@@ -131,8 +151,13 @@
<p id="otp-status" class="status" role="status"></p> <p id="otp-status" class="status" role="status"></p>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Mastodon</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Mastodon</span>
<span class="panel-toggle-icon" aria-hidden="true"></span>
</button>
</h2>
<form id="mastodon-form"> <form id="mastodon-form">
<label> <label>
Mastodon server Mastodon server
@@ -155,7 +180,7 @@
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=2"></script> <script src="/static/logout.js?v=2"></script>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
<script src="/static/profile.js?v=5"></script> <script src="/static/profile.js?v=6"></script>
</body> </body>
</html> </html>
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"version": "0.1.1" "version": "0.2.0"
} }
+95
View File
@@ -0,0 +1,95 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from pathlib import Path
from urllib.request import urlopen
FONT_SOURCES = {
'Asset-Regular.ttf': 'https://fonts.gstatic.com/s/asset/v30/SLXGc1na-mM4cWIm.ttf',
'DMSans-Regular.ttf': 'https://fonts.gstatic.com/s/dmsans/v17/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwAopxhTg.ttf',
'DMSans-Medium.ttf': 'https://fonts.gstatic.com/s/dmsans/v17/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwAkJxhTg.ttf',
'DMSans-SemiBold.ttf': 'https://fonts.gstatic.com/s/dmsans/v17/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwAfJthTg.ttf',
'DMSans-Bold.ttf': 'https://fonts.gstatic.com/s/dmsans/v17/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwARZthTg.ttf',
'SpaceGrotesk-Medium.ttf': 'https://fonts.gstatic.com/s/spacegrotesk/v22/V8mQoQDjQSkFtoMM3T6r8E7mF71Q-gOoraIAEj7aUUsj.ttf',
'SpaceGrotesk-SemiBold.ttf': 'https://fonts.gstatic.com/s/spacegrotesk/v22/V8mQoQDjQSkFtoMM3T6r8E7mF71Q-gOoraIAEj42Vksj.ttf',
'SpaceGrotesk-Bold.ttf': 'https://fonts.gstatic.com/s/spacegrotesk/v22/V8mQoQDjQSkFtoMM3T6r8E7mF71Q-gOoraIAEj4PVksj.ttf',
}
FONT_CSS = """@font-face {
font-family: 'Asset';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('Asset-Regular.ttf') format('truetype');
}
@font-face {
font-family: 'DM Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('DMSans-Regular.ttf') format('truetype');
}
@font-face {
font-family: 'DM Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url('DMSans-Medium.ttf') format('truetype');
}
@font-face {
font-family: 'DM Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url('DMSans-SemiBold.ttf') format('truetype');
}
@font-face {
font-family: 'DM Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('DMSans-Bold.ttf') format('truetype');
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url('SpaceGrotesk-Medium.ttf') format('truetype');
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url('SpaceGrotesk-SemiBold.ttf') format('truetype');
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('SpaceGrotesk-Bold.ttf') format('truetype');
}
"""
def main() -> None:
target_dir = Path('frontend/static/fonts')
target_dir.mkdir(parents=True, exist_ok=True)
for filename, url in FONT_SOURCES.items():
with urlopen(url, timeout=30) as response:
(target_dir / filename).write_bytes(response.read())
(target_dir / 'fonts.css').write_text(FONT_CSS, encoding='utf-8')
if __name__ == '__main__':
main()
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Generate Firefox update metadata from LinkLog signed XPI artifacts."""
import hashlib
import json
import re
import sys
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SIGNED_DIR = ROOT / 'XPI' / 'signed'
MANIFEST_PATH = ROOT / 'webextension' / 'manifest.json'
UPDATES_PATH = ROOT / 'webextension' / 'updates.json'
ABOUT_TEMPLATE_PATH = ROOT / 'frontend' / 'templates' / 'about.html'
RAW_BASE_URL = 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main'
XPI_NAME_RE = re.compile(r'LinkLog-(\d+\.\d+\.\d+)\.xpi')
ABOUT_XPI_URL_RE = re.compile(rf'{re.escape(RAW_BASE_URL)}/XPI/signed/LinkLog-\d+\.\d+\.\d+\.xpi')
def fail(message: str) -> None:
raise SystemExit(f'update metadata generation failed: {message}')
def version_key(version: str) -> tuple[int, int, int]:
return tuple(int(part) for part in version.split('.'))
def read_packaged_manifest(xpi_path: Path) -> dict:
try:
with zipfile.ZipFile(xpi_path) as archive:
if archive.testzip() is not None:
fail(f'{xpi_path.relative_to(ROOT)} contains a corrupt member')
return json.loads(archive.read('manifest.json'))
except (OSError, KeyError, json.JSONDecodeError, zipfile.BadZipFile) as error:
fail(f'could not read {xpi_path.relative_to(ROOT)}: {error}')
def sha256_digest(xpi_path: Path) -> str:
digest = hashlib.sha256()
with xpi_path.open('rb') as xpi_file:
for block in iter(lambda: xpi_file.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def update_about_plugin_link(xpi_path: Path) -> None:
about_template = ABOUT_TEMPLATE_PATH.read_text()
latest_xpi_url = f'{RAW_BASE_URL}/{xpi_path.relative_to(ROOT).as_posix()}'
updated_template, replacements = ABOUT_XPI_URL_RE.subn(latest_xpi_url, about_template)
if replacements != 1:
fail(f'expected one signed XPI link in {ABOUT_TEMPLATE_PATH.relative_to(ROOT)}; found {replacements}')
ABOUT_TEMPLATE_PATH.write_text(updated_template)
def main() -> None:
source_manifest = json.loads(MANIFEST_PATH.read_text())
addon_id = source_manifest.get('browser_specific_settings', {}).get('gecko', {}).get('id')
if not addon_id:
fail('webextension/manifest.json is missing browser_specific_settings.gecko.id')
releases = []
for xpi_path in SIGNED_DIR.glob('LinkLog-*.xpi'):
match = XPI_NAME_RE.fullmatch(xpi_path.name)
if not match:
continue
version = match.group(1)
manifest = read_packaged_manifest(xpi_path)
if manifest.get('version') != version:
fail(f'{xpi_path.relative_to(ROOT)} manifest version does not match its filename')
gecko = manifest.get('browser_specific_settings', {}).get('gecko', {})
if gecko.get('id') != addon_id:
fail(f'{xpi_path.relative_to(ROOT)} add-on id does not match webextension/manifest.json')
strict_min_version = gecko.get('strict_min_version')
if not strict_min_version:
fail(f'{xpi_path.relative_to(ROOT)} is missing browser_specific_settings.gecko.strict_min_version')
releases.append((version, xpi_path, strict_min_version, sha256_digest(xpi_path)))
if not releases:
fail(f'no signed LinkLog release artifacts found in {SIGNED_DIR.relative_to(ROOT)}')
releases.sort(key=lambda release: version_key(release[0]), reverse=True)
updates = [
{
'version': version,
'update_link': f'{RAW_BASE_URL}/{xpi_path.relative_to(ROOT).as_posix()}',
'update_hash': f'sha256:{digest}',
'applications': {
'gecko': {
'strict_min_version': strict_min_version,
},
},
}
for version, xpi_path, strict_min_version, digest in releases
]
UPDATES_PATH.write_text(json.dumps({'addons': {addon_id: {'updates': updates}}}, indent=2) + '\n')
update_about_plugin_link(releases[0][1])
print(f'updated {UPDATES_PATH.relative_to(ROOT)} with {len(updates)} signed release(s)')
if __name__ == '__main__':
main()
+70 -6
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Validate the version and checked-in artifacts for a LinkLog release.""" """Validate the version and checked-in artifacts for a LinkLog release."""
import hashlib
import json import json
import re import re
import sys import sys
@@ -9,9 +10,12 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
SETTINGS_PATH = ROOT / 'backend' / 'app' / 'core' / 'config.py' VERSION_FILE = ROOT / 'frontend' / 'version.json'
SIGNED_DIR = ROOT / 'XPI' / 'signed' SIGNED_DIR = ROOT / 'XPI' / 'signed'
MANIFEST_PATH = ROOT / 'webextension' / 'manifest.json' MANIFEST_PATH = ROOT / 'webextension' / 'manifest.json'
UPDATES_PATH = ROOT / 'webextension' / 'updates.json'
ABOUT_TEMPLATE_PATH = ROOT / 'frontend' / 'templates' / 'about.html'
RAW_BASE_URL = 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main'
VERSION_RE = re.compile(r'\d+\.\d+\.\d+') VERSION_RE = re.compile(r'\d+\.\d+\.\d+')
@@ -34,12 +38,69 @@ def find_latest_signed_xpi() -> tuple[str, Path]:
return max(candidates, key=lambda candidate: version_key(candidate[0])) return max(candidates, key=lambda candidate: version_key(candidate[0]))
def sha256_digest(xpi_path: Path) -> str:
digest = hashlib.sha256()
with xpi_path.open('rb') as xpi_file:
for block in iter(lambda: xpi_file.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def validate_self_update(source_manifest: dict, extension_version: str, xpi_path: Path) -> None:
gecko_settings = source_manifest.get('browser_specific_settings', {}).get('gecko', {})
addon_id = gecko_settings.get('id')
strict_min_version = gecko_settings.get('strict_min_version')
if not addon_id:
fail('webextension/manifest.json is missing browser_specific_settings.gecko.id')
updates_data = json.loads(UPDATES_PATH.read_text())
addon_entry = updates_data.get('addons', {}).get(addon_id)
if not addon_entry:
fail(f'{UPDATES_PATH.relative_to(ROOT)} has no entry for add-on id {addon_id!r}')
entry = next((u for u in addon_entry.get('updates', []) if u.get('version') == extension_version), None)
if entry is None:
fail(
f'{UPDATES_PATH.relative_to(ROOT)} has no update entry for version {extension_version!r}; '
'add one alongside the signed XPI so the self-update mechanism can find it'
)
expected_link = f'{RAW_BASE_URL}/{xpi_path.relative_to(ROOT).as_posix()}'
if entry.get('update_link') != expected_link:
fail(
f'{UPDATES_PATH.relative_to(ROOT)} update_link {entry.get("update_link")!r} does not match '
f'the expected raw signed XPI URL {expected_link!r}'
)
expected_hash = f'sha256:{sha256_digest(xpi_path)}'
if entry.get('update_hash') != expected_hash:
fail(
f'{UPDATES_PATH.relative_to(ROOT)} update_hash {entry.get("update_hash")!r} does not match '
f'the SHA-256 hash of {xpi_path.relative_to(ROOT)}'
)
entry_min_version = entry.get('applications', {}).get('gecko', {}).get('strict_min_version')
if entry_min_version != strict_min_version:
fail(
f'{UPDATES_PATH.relative_to(ROOT)} applications.gecko.strict_min_version {entry_min_version!r} '
f'does not match webextension/manifest.json strict_min_version {strict_min_version!r}'
)
def validate_about_plugin_link(xpi_path: Path) -> None:
expected_link = f'{RAW_BASE_URL}/{xpi_path.relative_to(ROOT).as_posix()}'
if expected_link not in ABOUT_TEMPLATE_PATH.read_text():
fail(
f'{ABOUT_TEMPLATE_PATH.relative_to(ROOT)} does not link to the latest signed XPI '
f'{xpi_path.relative_to(ROOT)}'
)
def main() -> None: def main() -> None:
settings = SETTINGS_PATH.read_text() version_data = json.loads(VERSION_FILE.read_text())
match = re.search(r"version: str = os\.getenv\('LINKLOG_VERSION', '([^']+)'\)", settings) backend_version = version_data.get('version')
if not match: if not backend_version:
fail('backend version default could not be found') fail(f'version could not be found in {VERSION_FILE.relative_to(ROOT)}')
backend_version = match.group(1)
if not VERSION_RE.fullmatch(backend_version): if not VERSION_RE.fullmatch(backend_version):
fail(f'backend version {backend_version} is not a valid three-part version') fail(f'backend version {backend_version} is not a valid three-part version')
@@ -64,6 +125,9 @@ def main() -> None:
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')
validate_self_update(source_manifest, extension_version, xpi_path)
validate_about_plugin_link(xpi_path)
signed_xpi = xpi_path.relative_to(ROOT) signed_xpi = xpi_path.relative_to(ROOT)
if len(sys.argv) == 3 and sys.argv[1] == '--github-output': if len(sys.argv) == 3 and sys.argv[1] == '--github-output':
with Path(sys.argv[2]).open('a') as output: with Path(sys.argv[2]).open('a') as output:
+4 -1
View File
@@ -42,7 +42,10 @@
"submissionFailed": {"message": "Senden fehlgeschlagen"}, "submissionFailed": {"message": "Senden fehlgeschlagen"},
"linkSaved": {"message": "Link auf $URL$ gespeichert.", "placeholders": {"url": {"content": "$1"}}}, "linkSaved": {"message": "Link auf $URL$ gespeichert.", "placeholders": {"url": {"content": "$1"}}},
"linkAlreadyExists": {"message": "Dieser Link existiert bereits. Kommentar und Tags wurden aktualisiert und die Veröffentlichung erneut ausgelöst."}, "linkAlreadyExists": {"message": "Dieser Link existiert bereits. Kommentar und Tags wurden aktualisiert und die Veröffentlichung erneut ausgelöst."},
"duplicateLinkWarning": {"message": "Dieser Link existiert bereits. Kommentar und Tags können aktualisiert werden; beim Absenden wird die Veröffentlichung erneut ausgelöst."}, "duplicateLinkSameUrl": {"message": "Dieser Link existiert bereits.\nDu kannst den Eintrag trotzdem speichern; dabei werden Kommentar und Tags des bestehenden Eintrags aktualisiert."},
"duplicateLinkDifferentUrl": {"message": "Dieser Link existiert bereits. Der gespeicherte Link hat jedoch eine andere URL (fehlende oder andere Parameter).\nWenn du den Eintrag speicherst, riskierst du einen doppelten Eintrag."},
"refetchTitle": {"message": "Titel erneut abrufen"},
"titleFetchFailed": {"message": "Titel konnte nicht abgerufen werden"},
"publishingErrors": {"message": "Fehler bei der Veröffentlichung: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}}, "publishingErrors": {"message": "Fehler bei der Veröffentlichung: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
"submissionFailedConnection": {"message": "Senden fehlgeschlagen. Überprüfe die Verbindung zum Backend."}, "submissionFailedConnection": {"message": "Senden fehlgeschlagen. Überprüfe die Verbindung zum Backend."},
"loggedInAt": {"message": "$USERNAME$ ist bei $BACKEND$ angemeldet", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}}, "loggedInAt": {"message": "$USERNAME$ ist bei $BACKEND$ angemeldet", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
+11 -2
View File
@@ -133,8 +133,17 @@
"linkAlreadyExists": { "linkAlreadyExists": {
"message": "This link already exists. Comment and tags were updated, and publishing was retriggered." "message": "This link already exists. Comment and tags were updated, and publishing was retriggered."
}, },
"duplicateLinkWarning": { "duplicateLinkSameUrl": {
"message": "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered." "message": "This link already exists.\nYou can still save the entry, which will update the existing entry's comment and or tags."
},
"duplicateLinkDifferentUrl": {
"message": "This link already exists. But, the stored link has a different URL (missing or different parameters).\nWhen you save the entry you risk a duplicate entry."
},
"refetchTitle": {
"message": "Re-fetch title"
},
"titleFetchFailed": {
"message": "Could not fetch title"
}, },
"publishingErrors": { "publishingErrors": {
"message": "Publishing errors: $ERRORS$", "message": "Publishing errors: $ERRORS$",
+4 -1
View File
@@ -42,7 +42,10 @@
"submissionFailed": {"message": "Error al enviar"}, "submissionFailed": {"message": "Error al enviar"},
"linkSaved": {"message": "Enlace guardado en $URL$.", "placeholders": {"url": {"content": "$1"}}}, "linkSaved": {"message": "Enlace guardado en $URL$.", "placeholders": {"url": {"content": "$1"}}},
"linkAlreadyExists": {"message": "Este enlace ya existe. Se actualizaron el comentario y las etiquetas, y se volvió a activar la publicación."}, "linkAlreadyExists": {"message": "Este enlace ya existe. Se actualizaron el comentario y las etiquetas, y se volvió a activar la publicación."},
"duplicateLinkWarning": {"message": "Este enlace ya existe. Puedes actualizar el comentario y las etiquetas; al enviarlo se volverá a activar la publicación."}, "duplicateLinkSameUrl": {"message": "Este enlace ya existe.\nAún puedes guardar la entrada, lo que actualizará el comentario y las etiquetas de la entrada existente."},
"duplicateLinkDifferentUrl": {"message": "Este enlace ya existe. Pero el enlace guardado tiene una URL diferente (parámetros ausentes o distintos).\nSi guardas la entrada, corres el riesgo de crear una entrada duplicada."},
"refetchTitle": {"message": "Volver a obtener el título"},
"titleFetchFailed": {"message": "No se pudo obtener el título"},
"publishingErrors": {"message": "Errores de publicación: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}}, "publishingErrors": {"message": "Errores de publicación: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
"submissionFailedConnection": {"message": "Error al enviar. Comprueba la conexión con el servidor."}, "submissionFailedConnection": {"message": "Error al enviar. Comprueba la conexión con el servidor."},
"loggedInAt": {"message": "$USERNAME$ ha iniciado sesión en $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}}, "loggedInAt": {"message": "$USERNAME$ ha iniciado sesión en $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
+4 -1
View File
@@ -42,7 +42,10 @@
"submissionFailed": {"message": "Échec de lenvoi"}, "submissionFailed": {"message": "Échec de lenvoi"},
"linkSaved": {"message": "Lien enregistré sur $URL$.", "placeholders": {"url": {"content": "$1"}}}, "linkSaved": {"message": "Lien enregistré sur $URL$.", "placeholders": {"url": {"content": "$1"}}},
"linkAlreadyExists": {"message": "Ce lien existe déjà. Le commentaire et les étiquettes ont été mis à jour et la publication a été relancée."}, "linkAlreadyExists": {"message": "Ce lien existe déjà. Le commentaire et les étiquettes ont été mis à jour et la publication a été relancée."},
"duplicateLinkWarning": {"message": "Ce lien existe déjà. Le commentaire et les étiquettes peuvent être mis à jour ; lenvoi relancera la publication."}, "duplicateLinkSameUrl": {"message": "Ce lien existe déjà.\nVous pouvez tout de même enregistrer lentrée ; le commentaire et les étiquettes de lentrée existante seront mis à jour."},
"duplicateLinkDifferentUrl": {"message": "Ce lien existe déjà. Mais le lien enregistré a une URL différente (paramètres manquants ou différents).\nSi vous enregistrez lentrée, vous risquez de créer un doublon."},
"refetchTitle": {"message": "Récupérer à nouveau le titre"},
"titleFetchFailed": {"message": "Impossible de récupérer le titre"},
"publishingErrors": {"message": "Erreurs de publication : $ERRORS$", "placeholders": {"errors": {"content": "$1"}}}, "publishingErrors": {"message": "Erreurs de publication : $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
"submissionFailedConnection": {"message": "Échec de lenvoi. Vérifiez la connexion au serveur."}, "submissionFailedConnection": {"message": "Échec de lenvoi. 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"}}},
+4 -1
View File
@@ -42,7 +42,10 @@
"submissionFailed": {"message": "Verzenden mislukt"}, "submissionFailed": {"message": "Verzenden mislukt"},
"linkSaved": {"message": "Koppeling opgeslagen op $URL$.", "placeholders": {"url": {"content": "$1"}}}, "linkSaved": {"message": "Koppeling opgeslagen op $URL$.", "placeholders": {"url": {"content": "$1"}}},
"linkAlreadyExists": {"message": "Deze koppeling bestaat al. De opmerking en tags zijn bijgewerkt en publiceren is opnieuw gestart."}, "linkAlreadyExists": {"message": "Deze koppeling bestaat al. De opmerking en tags zijn bijgewerkt en publiceren is opnieuw gestart."},
"duplicateLinkWarning": {"message": "Deze koppeling bestaat al. De opmerking en tags kunnen worden bijgewerkt; na verzenden wordt publiceren opnieuw gestart."}, "duplicateLinkSameUrl": {"message": "Deze koppeling bestaat al.\nJe kunt de invoer nog steeds opslaan; de opmerking en tags van de bestaande koppeling worden dan bijgewerkt."},
"duplicateLinkDifferentUrl": {"message": "Deze koppeling bestaat al. De opgeslagen koppeling heeft echter een andere URL (ontbrekende of andere parameters).\nAls je de invoer opslaat, loop je het risico op een dubbele koppeling."},
"refetchTitle": {"message": "Titel opnieuw ophalen"},
"titleFetchFailed": {"message": "Titel kon niet worden opgehaald"},
"publishingErrors": {"message": "Publicatiefouten: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}}, "publishingErrors": {"message": "Publicatiefouten: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
"submissionFailedConnection": {"message": "Verzenden mislukt. Controleer de verbinding met de backend."}, "submissionFailedConnection": {"message": "Verzenden mislukt. Controleer de verbinding met de backend."},
"loggedInAt": {"message": "$USERNAME$ is ingelogd op $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}}, "loggedInAt": {"message": "$USERNAME$ is ingelogd op $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"manifest_version": 3, "manifest_version": 3,
"name": "__MSG_extensionName__", "name": "__MSG_extensionName__",
"version": "0.1.0", "version": "0.2.0",
"description": "__MSG_extensionDescription__", "description": "__MSG_extensionDescription__",
"default_locale": "en-US", "default_locale": "en-US",
"permissions": [ "permissions": [
+1
View File
@@ -26,6 +26,7 @@
<span data-i18n="titleLabel">Title</span> <span data-i18n="titleLabel">Title</span>
<input id="title" name="title" type="text" /> <input id="title" name="title" type="text" />
</label> </label>
<button type="button" id="refetch-title" class="secondary" data-i18n="refetchTitle">Re-fetch title</button>
<label> <label>
<span data-i18n="urlLabel">URL</span> <span data-i18n="urlLabel">URL</span>
+60 -4
View File
@@ -13,6 +13,7 @@ const feedLink = document.getElementById('feed-link');
const authWarning = document.getElementById('auth-warning'); const authWarning = document.getElementById('auth-warning');
const warningSettingsButton = document.getElementById('warning-settings'); const warningSettingsButton = document.getElementById('warning-settings');
const authSession = document.getElementById('auth-session'); const authSession = document.getElementById('auth-session');
const refetchTitleButton = document.getElementById('refetch-title');
const sessionStore = browser.storage.session; const sessionStore = browser.storage.session;
const t = window.linklogI18n; const t = window.linklogI18n;
@@ -35,8 +36,14 @@ async function hasBackendPermission(backendUrl) {
return browser.permissions.contains({origins: [`${origin}/*`]}); return browser.permissions.contains({origins: [`${origin}/*`]});
} }
// Splits on \n into real <br> line breaks without using innerHTML.
function setStatus(message, isError = false) { function setStatus(message, isError = false) {
statusEl.textContent = message; const lines = message.split('\n');
statusEl.replaceChildren(
...lines.flatMap((line, index) => (
index === 0 ? [document.createTextNode(line)] : [document.createElement('br'), document.createTextNode(line)]
)),
);
statusEl.classList.remove('hidden'); statusEl.classList.remove('hidden');
statusEl.classList.toggle('error', isError); statusEl.classList.toggle('error', isError);
statusEl.classList.toggle('success', !isError); statusEl.classList.toggle('success', !isError);
@@ -225,20 +232,54 @@ async function checkExistingLink() {
const settings = await getSettings(); const settings = await getSettings();
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl)) || !titleInput.value || !urlInput.value) return; if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl)) || !titleInput.value || !urlInput.value) return;
try { try {
const url = removeKnownTrackingParams(urlInput.value);
const response = await fetch(`${settings.backendUrl}/api/links/check?${new URLSearchParams({ const response = await fetch(`${settings.backendUrl}/api/links/check?${new URLSearchParams({
title: titleInput.value, title: titleInput.value,
url: removeKnownTrackingParams(urlInput.value), url,
})}`, { })}`, {
headers: {'Authorization': `Bearer ${settings.accessToken}`}, headers: {'Authorization': `Bearer ${settings.accessToken}`},
}); });
if (response.ok && (await response.json()).exists) { if (!response.ok) return;
setStatus(t('duplicateLinkWarning'), true); const data = await response.json();
if (data.exists) {
// Re-derive the match locally: browser URL normalization (e.g. trailing slashes) can
// make the server's raw string comparison disagree even when the URLs are equivalent.
const urlMatches = data.url_matches || (data.stored_url && removeKnownTrackingParams(data.stored_url) === url);
const message = urlMatches ? t('duplicateLinkSameUrl') : t('duplicateLinkDifferentUrl');
setStatus(message, true);
} }
} catch (error) { } catch (error) {
// Duplicate checking is advisory; submission remains available. // Duplicate checking is advisory; submission remains available.
} }
} }
// Re-fetch the title from the backend scraper, for when the URL was edited after the initial tab-based fill.
let lastScrapedUrl = null;
async function fetchTitle(url, { force = false } = {}) {
const settings = await getSettings();
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl))) return;
if (!url || (!force && (titleInput.value.trim() || url === lastScrapedUrl))) return;
try {
const response = await fetch(`${settings.backendUrl}/api/scrape?url=${encodeURIComponent(url)}`, {
headers: {'Authorization': `Bearer ${settings.accessToken}`},
});
if (!response.ok) {
if (force) setStatus(t('titleFetchFailed'), true);
return;
}
lastScrapedUrl = url;
const data = await response.json();
if (data.title) {
titleInput.value = data.title;
} else if (force) {
setStatus(t('titleFetchFailed'), true);
}
} catch (error) {
if (force) setStatus(t('titleFetchFailed'), true);
}
}
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault(); event.preventDefault();
setStatus(t('submitting'), false); setStatus(t('submitting'), false);
@@ -305,6 +346,21 @@ 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);
urlInput.addEventListener('blur', async () => {
await fetchTitle(removeKnownTrackingParams(urlInput.value.trim()));
checkExistingLink();
});
titleInput.addEventListener('blur', checkExistingLink);
refetchTitleButton.addEventListener('click', (e) => {
e.preventDefault();
const url = removeKnownTrackingParams(urlInput.value.trim());
if (!url) {
setStatus(t('titleFetchFailed'), true);
return;
}
titleInput.value = '';
fetchTitle(url, { force: true });
});
populateCurrentTab().then(checkExistingLink); populateCurrentTab().then(checkExistingLink);
loadExistingTags(); loadExistingTags();
updateFeedLink(); updateFeedLink();
+18 -2
View File
@@ -2,11 +2,27 @@
"addons": { "addons": {
"linklog@kolkman.org": { "linklog@kolkman.org": {
"updates": [ "updates": [
{
"version": "0.2.0",
"update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.2.0.xpi",
"update_hash": "sha256:86619ec9aa35345c5c2bcad8fa5701762b8bd237ad9457b131404ff68bc2ce6b",
"applications": {
"gecko": {
"strict_min_version": "142.0"
}
}
},
{ {
"version": "0.1.0", "version": "0.1.0",
"update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi" "update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi",
"update_hash": "sha256:d95e23339facfa2a499bb35f9130d41739f622a3c0ac197ac3fd8cb76d6d6110",
"applications": {
"gecko": {
"strict_min_version": "142.0"
}
}
} }
] ]
} }
} }
} }