Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gstack-redact-allowlist
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
https://user:pw@ntfy.example.com:8443
https://user:password@ntfy.example.com
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ Treat the key as public. It ships in every `Jellyscribe.dll` and a decompiler sh
- `Api/LetterboxdController.cs` exposes the REST endpoints the dashboards call; `Api/SidebarController.cs` serves the static web assets (`sidebar.js`, `jellyscribe.js`, `jellyscribe.css`), the only anonymous routes. `LetterboxdController` also serves the read-only `ItemRating` endpoint the review modal uses to pre-fill its stars from the caller's stored Jellyfin rating.
- `POST Review` with text (not a rewatch, no date given, TMDb id known) holds `FilmSyncLock` for that user, account and film, then looks up the latest `Success`/`Rewatch` history row for that user, account and film. When one exists, `ILetterboxdService.AddReviewToDiaryEntryAsync` puts the review on Letterboxd's entry for that viewing date (API path: `GET /log-entries?member=&film=`, every page and read a second time after 3s when nothing is on that date because diary reads lag writes, then `PATCH /log-entry/{id}` with only `review` and `rating`; an entry that already has a review is never overwritten and the request is refused). The website session keeps the interface default, `Unsupported`, so it and a missing entry fall back to a new entry dated on the row's viewing date, never today, and the per-account reply carries a `note` saying so. Any other review is a new entry sent with an explicit date (today is the server's day, `Helpers.ToLocalViewingDate`). The review's history row records the real TMDb id, account and viewing date, so the diary sync's duplicate checks see it.
- `Api/LoginCheckLimiter.cs` rate-limits both Verify (login check) endpoints in memory: 5 failed checks per Jellyfin user, 20 checks of any outcome per user, and 20 failed checks server-wide, per service per 10 minutes, answering 429. `ControllerAuthorizationTests` pins which actions are anonymous and which are admin-only, so a new action has to be added there on purpose.
- Stored secrets (Letterboxd and Serializd passwords, raw cookies, the Seerr API key) are write-only: the plaintext properties are `[JsonIgnore]`, responses carry only `Has*`/`has*` flags, and `Configuration/SecretMerge.cs` turns every save back into the intended change (blank keeps, typed replaces, `ClearRawCookies`/`ClearJellyseerrApiKey` drop, and the write-only `Original*` fields carry secrets across a rename or an admin's owner change). `Plugin.UpdateConfiguration` applies it to Jellyfin's own plugin-config POST. Both Verify endpoints use the stored password when the field is blank, and `TestJellyseerr` sends the stored key only to the stored URL.
- Stored secrets (Letterboxd and Serializd passwords, raw cookies, the Seerr API key, the notification access token) are write-only: the plaintext properties are `[JsonIgnore]`, responses carry only `Has*`/`has*` flags, and `Configuration/SecretMerge.cs` turns every save back into the intended change (blank keeps, typed replaces, `ClearRawCookies`/`ClearJellyseerrApiKey`/`ClearNotificationToken` drop, the notification token is also dropped when its address changes with no token typed, and the write-only `Original*` fields carry secrets across a rename or an admin's owner change). `Plugin.UpdateConfiguration` applies it to Jellyfin's own plugin-config POST. Both Verify endpoints use the stored password when the field is blank, and `TestJellyseerr` sends the stored key only to the stored URL.
- Failure notifications (`Notifications/`): optional ntfy push notifications to the admin's `NotificationUrl`, off until one is saved. `NotificationSender` (a hosted singleton) does one POST with a 10 s limit, follows no redirects, logs the server's host only (the topic name is a secret on a public server) and never throws; static code reaches it through `Notifications.Notify`, a no-op until the sender starts. Each condition is raised at one choke point, so no sync entry point knows about it: a paused Letterboxd login inside `AuthBreaker.NotifyOpenedAsync` (once per pause), a Serializd login refused with 401 or 403 inside `SerializdServiceFactory.CreateAuthenticatedAsync` (once per account per 24 h through `NotificationLog`, lifted when a different password is saved but never below once an hour; Verify does not use the factory), and films just given up on through `GiveUpNotice.AfterRun`, called after the film loop in `LetterboxdSyncRunner` (after `SyncHistory.MarkOutage`, and before a cancellation is rethrown) and after a failed film in `PlaybackHandler`. `NotificationMessages` builds the text: header values are fixed ASCII, and no message carries a secret, a Serializd email or a service's error text. `Plugin.UpdateConfiguration` stores no address that is not `http`/`https`. The admin-only `POST Notifications/Test` sends the stored token only to the stored address and describes a failure in fixed words.
- `Api/LibrariesController.cs` lists the film, TV, and mixed libraries the caller can access, for the per-account "Excluded libraries" checklist on both settings pages (Jellyfin's own `/Library/VirtualFolders` is admin-only).
- `Web/*.html`, `Web/*.js` and `Web/*.css` are embedded resources (see `LetterboxdSync.csproj`). `configPage.html` and `userPage.html` are the plugin's config pages; what they share (most of the code, every common style, and the bundled WS Sans/WS Mono fonts) lives in `jellyscribe.js` and `jellyscribe.css`, which `SidebarController` serves anonymously as static files. Each page loads them with `?v=<version>`, reuses a loaded copy only under that version, and starts with the factory `jellyscribe.js` registered under it, so after an upgrade a page never runs against an older shared script left in the tab. The build stamps the version into both pages and `jellyscribe.js` (the `StampWebAssetVersion` target replaces `@@JELLYSCRIBE_VERSION@@`; a Debug build stamps `<version>-dev`), and the server caches the files for good only under this build's version. A fix to shared behaviour goes in `jellyscribe.js` once; page-specific code (how each page talks to the server, its own sections) stays in the page. Both dashboards scope every CSS rule to their root (never `html`/`body`), pick their light or dark palette from the background Jellyfin's theme paints (`applyTheme`; the OS setting only outside Jellyfin), and use native `<dialog>` modals opened with `showModal()`. `DashboardMarkupTests` pins their contrast (4.5:1 in both palettes), scoping, phone layout and keyboard markup.
- Telemetry and log bundles (`Telemetry/TelemetryService.cs`, the `Telemetry/*` actions in `LetterboxdController`): the admin page previews the exact ping (`Telemetry/Preview`) and log bundle (`Telemetry/PreviewLogs`, built by the same method as the send) before anything leaves the server, and `Telemetry/RegenerateId` replaces the instance id. Never log a Serializd email: name the account with `LogRedaction.AccountTag`. The shared log reader masks emails with `LogRedaction.RedactEmails` (encoded forms too) and cuts review-reply bodies older releases logged, so the Logs tab, the preview and the upload match. Error counts in the payload stay exact integers (the ingest Worker drops non-numbers); the docs say so.
Expand Down
6 changes: 3 additions & 3 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<Version>2.15.2.0</Version>
<AssemblyVersion>2.15.2.0</AssemblyVersion>
<FileVersion>2.15.2.0</FileVersion>
<Version>2.16.0.0</Version>
<AssemblyVersion>2.16.0.0</AssemblyVersion>
<FileVersion>2.16.0.0</FileVersion>
</PropertyGroup>
</Project>
1 change: 1 addition & 0 deletions LetterboxdSync.Tests/ControllerAuthorizationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public class ControllerAuthorizationTests
"LetterboxdController.RegenerateTelemetryId",
"LetterboxdController.SendLogs",
"LetterboxdController.TestJellyseerr",
"LetterboxdController.TestNotification",
};

private sealed record ActionInfo(string Name, bool Anonymous, bool Authorized, bool AdminOnly, bool Routed);
Expand Down
68 changes: 68 additions & 0 deletions LetterboxdSync.Tests/DashboardMarkupTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,74 @@ public void AdminPage_OffersThePromisedTelemetryAndLogBundlePreviews()
Assert.DoesNotContain("exact numbers", page, StringComparison.Ordinal);
}

[Fact]
public void AdminPage_NotificationsPanel_IsLabelledScopedAndShowsServerTextAsText()
{
var page = Read("configPage.html");
var start = page.IndexOf("<h2>Notifications</h2>", StringComparison.Ordinal);
Assert.True(start >= 0, "no Notifications panel");
var panel = page.Substring(start, page.IndexOf("<h2>Anonymous telemetry</h2>", start, StringComparison.Ordinal) - start);

// It sits on the Integrations tab, after Seerr, and is saved by that tab's one Save button.
Assert.True(page.IndexOf("<h2>Seerr</h2>", StringComparison.Ordinal) < start);
Assert.True(page.IndexOf("<!-- INTEGRATIONS -->", StringComparison.Ordinal) < start);
Assert.DoesNotContain("primary", panel, StringComparison.Ordinal);

// Every field has a label, in the order a keyboard reaches them: address, token, remove, test.
Assert.Contains("<label class=\"ws-field\" for=\"notificationUrl\">", panel, StringComparison.Ordinal);
Assert.Contains("<label class=\"ws-field\" for=\"notificationToken\">", panel, StringComparison.Ordinal);
var order = new[] { "id=\"notificationUrl\"", "id=\"notificationToken\"", "id=\"notificationTokenClear\"", "id=\"testNotificationBtn\"" }
.Select(id => panel.IndexOf(id, StringComparison.Ordinal)).ToList();
Assert.All(order, at => Assert.True(at >= 0));
Assert.Equal(order.OrderBy(at => at), order);
Assert.DoesNotContain("tabindex", panel, StringComparison.Ordinal);

// The token is a password field the browser must not fill, with the shared "Saved" badge
// and "Remove saved ..." row that fillSecret drives by id.
Assert.Contains("<input type=\"password\" class=\"ws-input\" id=\"notificationToken\" autocomplete=\"new-password\"", panel, StringComparison.Ordinal);
Assert.Contains("<span class=\"ws-saved\" id=\"notificationTokenSaved\" hidden>Saved</span>", panel, StringComparison.Ordinal);
Assert.Contains("id=\"notificationTokenClearRow\"", panel, StringComparison.Ordinal);
Assert.Contains("Remove saved token", panel, StringComparison.Ordinal);

// The address error is tied to its field and announced; the test result is a status.
Assert.Contains("aria-describedby=\"notificationUrlError\"", panel, StringComparison.Ordinal);
Assert.Matches("id=\"notificationUrlError\" role=\"alert\"", panel);
Assert.Matches("id=\"notificationTestStatus\"[^>]* role=\"status\"", panel);

// The help text names the three conditions and that nothing is sent by default.
Assert.Contains("Letterboxd login is paused", panel, StringComparison.Ordinal);
Assert.Contains("Serializd rejects a login", panel, StringComparison.Ordinal);
Assert.Contains("gives up on a film", panel, StringComparison.Ordinal);
Assert.Contains("Nothing is sent until an address is saved", panel, StringComparison.Ordinal);
Assert.Contains("rel=\"noopener noreferrer\"", panel, StringComparison.Ordinal);

// Colours come from the shared classes (whose contrast is pinned above), never inline.
Assert.DoesNotMatch("color:\\s*#", panel);

// Script: lookups go through the page root, the address is checked before the save is sent,
// and what the server says is written as text, never as HTML.
Assert.Contains("byId('testNotificationBtn').addEventListener", page, StringComparison.Ordinal);
Assert.Contains("Notifications/Test'), type: 'POST'", page, StringComparison.Ordinal);
var saveAt = page.IndexOf("saveIntegrations: function", StringComparison.Ordinal);
var checkAt = page.IndexOf("!self.isNotificationUrl(notifyUrl)", saveAt, StringComparison.Ordinal);
var sendAt = page.IndexOf("self.saveConfig(function (c)", saveAt, StringComparison.Ordinal);
Assert.True(checkAt > saveAt && checkAt < sendAt, "the address must be checked before the save is sent");
Assert.Contains("c.ClearNotificationToken = !c.NotificationToken && g('notificationTokenClear').checked;", page, StringComparison.Ordinal);
// The page only passes the plain scheme://host form, which the server's stricter check also takes.
Assert.Contains("/^https?:\\/\\/[^\\s\\/?#@\\\\]+(\\/|$|\\?|#)/i.test(value)", page, StringComparison.Ordinal);

var testAt = page.IndexOf("testNotification: function", StringComparison.Ordinal);
var testBody = page.Substring(testAt, page.IndexOf("loadLogs: function", testAt, StringComparison.Ordinal) - testAt);
Assert.DoesNotContain("innerHTML", testBody, StringComparison.Ordinal);
Assert.DoesNotContain("document.", testBody, StringComparison.Ordinal);
Assert.Contains("st.textContent = text", testBody, StringComparison.Ordinal);
var errorAt = page.IndexOf("notificationUrlError: function", StringComparison.Ordinal);
Assert.Contains("el.textContent = message", page.Substring(errorAt, testAt - errorAt), StringComparison.Ordinal);

// Nothing about notifications is on the user page.
Assert.DoesNotContain("otification", Read("userPage.html"), StringComparison.Ordinal);
}

[Fact]
public void ReviewResult_SaysWhenAReviewJoinedTheExistingEntry_AndShowsTheServersNoteAsText()
{
Expand Down
168 changes: 168 additions & 0 deletions LetterboxdSync.Tests/NotificationLogTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace LetterboxdSync.Tests;

[Collection("Plugin")]
public class NotificationLogTests : IDisposable
{
private static readonly TimeSpan Day = TimeSpan.FromHours(24);
private readonly string _path;
private DateTime _now = new(2026, 12, 3, 9, 0, 0, DateTimeKind.Utc);

public NotificationLogTests()
{
_path = Path.Combine(Path.GetTempPath(), "lbs-notify-" + Guid.NewGuid().ToString("N") + ".json");
NotificationLog.DataPathOverride = _path;
NotificationLog.UtcNow = () => _now;
NotificationLog.ResetForTesting();
}

public void Dispose()
{
NotificationLog.UtcNow = () => DateTime.UtcNow;
NotificationLog.DataPathOverride = null;
NotificationLog.ResetForTesting();
try { if (File.Exists(_path)) File.Delete(_path); } catch { }
}

[Fact]
public void SentKey_IsHeldForTheWindow_ThenAllowedAgain()
{
var key = NotificationLog.SerializdRejectedKey("me@example.com");

Assert.True(NotificationLog.TryBegin(key, Day));
NotificationLog.Sent(key);

_now = _now.AddHours(23);
Assert.False(NotificationLog.TryBegin(key, Day));

_now = _now.AddHours(2);
Assert.True(NotificationLog.TryBegin(key, Day));
}

[Fact]
public void Window_SurvivesARestart()
{
var key = NotificationLog.SerializdRejectedKey("me@example.com");
Assert.True(NotificationLog.TryBegin(key, Day));
NotificationLog.Sent(key);

NotificationLog.ResetForTesting();

Assert.False(NotificationLog.TryBegin(key, Day));
}

[Fact]
public void FailedSend_IsNotRecorded()
{
var key = NotificationLog.SerializdRejectedKey("me@example.com");

Assert.True(NotificationLog.TryBegin(key, Day));
NotificationLog.Failed(key);

Assert.True(NotificationLog.TryBegin(key, Day));
Assert.False(File.Exists(_path));
}

[Fact]
public void Clear_LiftsTheLimit()
{
var key = NotificationLog.SerializdRejectedKey("me@example.com");
Assert.True(NotificationLog.TryBegin(key, Day));
NotificationLog.Sent(key);

NotificationLog.Clear(key);

Assert.True(NotificationLog.TryBegin(key, Day));
}

[Fact]
public void Clear_DoesNotLiftTheFloor()
{
var floor = TimeSpan.FromHours(1);
Assert.True(NotificationLog.TryBegin("k", Day, floor));
NotificationLog.Sent("k");

for (var i = 0; i < 5; i++)
{
_now = _now.AddMinutes(10);
NotificationLog.Clear("k");
Assert.False(NotificationLog.TryBegin("k", Day, floor));
}

_now = _now.AddMinutes(15);
Assert.True(NotificationLog.TryBegin("k", Day, floor));
}

[Fact]
public void Clear_WhileASendIsUnderWay_KeepsTheWindowLifted()
{
Assert.True(NotificationLog.TryBegin("k", Day));
NotificationLog.Clear("k");
NotificationLog.Sent("k");

Assert.True(NotificationLog.TryBegin("k", Day));
NotificationLog.Sent("k");
Assert.False(NotificationLog.TryBegin("k", Day));
}

[Fact]
public void KeyAndFile_HoldNoEmailAddress()
{
var key = NotificationLog.SerializdRejectedKey("Person@Example.com");
Assert.True(NotificationLog.TryBegin(key, Day));
NotificationLog.Sent(key);

var text = File.ReadAllText(_path);
Assert.DoesNotContain("example.com", text, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("person", text, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("@", text);
Assert.Equal(key, NotificationLog.SerializdRejectedKey(" person@example.COM "));
Assert.NotEqual(key, NotificationLog.SerializdRejectedKey("other@example.com"));
}

[Fact]
public void OldEntries_AreDroppedOnWrite()
{
Assert.True(NotificationLog.TryBegin("old", Day));
NotificationLog.Sent("old");

_now = _now.AddDays(31);
Assert.True(NotificationLog.TryBegin("new", Day));
NotificationLog.Sent("new");

var text = File.ReadAllText(_path);
Assert.DoesNotContain("\"old\"", text);
Assert.Contains("\"new\"", text);
}

[Fact]
public async Task ConcurrentBegins_ForOneKey_LetExactlyOneThrough()
{
using var start = new ManualResetEventSlim();
var tasks = Enumerable.Range(0, 16).Select(_ => Task.Run(() =>
{
start.Wait();
return NotificationLog.TryBegin("same-key", Day);
})).ToArray();

start.Set();
var results = await Task.WhenAll(tasks);

Assert.Equal(1, results.Count(won => won));
}

[Fact]
public void UnreadableFile_CountsAsEmpty()
{
File.WriteAllText(_path, "{ this is not json");
NotificationLog.ResetForTesting();

Assert.True(NotificationLog.TryBegin("k", Day));
}
}
Loading
Loading