Files
WatchedTogether/Jellyfin.Plugin.WatchedTogether/Auth/SharedAccountAuthenticationProvider.cs
T
dtourolleandClaude Opus 5 27cd2a3d37 Inherit parental restrictions on shared accounts, with a chosen rating cap
A shared account previously inherited its members' library access but
none of their content restrictions, so a child could log into "alice+kid"
with their own password and get around their own rating cap.

The shared account now gets the strictest member's parental rating,
unrated-item block, blocked tags and allowed tags, recomputed at
creation, on membership change and at startup. An admin can raise the
rating cap on a slider between the strictest and the loosest member;
unrated and tag rules stay strictest-wins.

What makes raising the cap safe is the unlock rule: after a member's
password matches, both users' live policies are compared and the login
is refused if the account is looser than the member on any field. So
raising the cap above the child's rating means the child's password no
longer opens the account, while the parent's still does. The same rule
bounds the slider - past the loosest member nobody could unlock the
account - so a chosen cap is clamped back into range whenever applied.

Allowed tags need care: Jellyfin reads an empty list as "no whitelist",
so an empty intersection of members' whitelists is written as a sentinel
tag no item carries. Access schedules and channels are not inherited yet.

The shared account is never an administrator. Groups created at the
login screen always inherit and are restricted before the first session
exists. The dashboard shows each member's cap, who a chosen cap shuts
out, and the restrictions in effect, and gains a per-group edit form for
the sync options.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-19 12:30:50 +02:00

212 lines
9.2 KiB
C#

using System;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations.Entities;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Model.Cryptography;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.WatchedTogether.Auth;
/// <summary>
/// Authenticates a shared account against the passwords of each of its members.
/// </summary>
/// <remarks>
/// <para>
/// Jellyfin selects a provider per user via <c>User.AuthenticationProviderId</c>, so this provider
/// only ever sees shared accounts that provisioning assigned to it. Implementing
/// <see cref="IRequiresResolvedUser"/> means Jellyfin hands us the already-resolved shared account
/// rather than us having to look it up by name.
/// </para>
/// <para>
/// Verification reads each member's stored hash directly instead of calling
/// <c>IUserManager.AuthenticateUser</c>. Going through the normal flow would trip every member's
/// failed-attempt counter each time a <em>different</em> member's password was the one that
/// matched, eventually locking out members who did nothing wrong. Reading the live hash also means
/// member password changes take effect immediately, with no second copy of any credential stored.
/// </para>
/// <para>
/// A matching password is not the whole story: the member may only unlock an account that is at
/// least as restricted as they are. That is checked here against both users' <em>live</em>
/// policies, so it holds even when the shared account's stored policy has drifted from its
/// members', and it is what makes choosing a cap safe - the child's password stops opening an
/// account the parent raised above the child's rating.
/// </para>
/// </remarks>
public class SharedAccountAuthenticationProvider : IAuthenticationProvider, IRequiresResolvedUser
{
private readonly ICryptoProvider _cryptoProvider;
private readonly Lazy<Services.IGroupService> _groupService;
private readonly Lazy<Services.IDynamicGroupService> _dynamicGroupService;
private readonly Lazy<Services.IRestrictionService> _restrictionService;
private readonly ILogger<SharedAccountAuthenticationProvider> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="SharedAccountAuthenticationProvider"/> class.
/// </summary>
/// <param name="cryptoProvider">The crypto provider used to verify stored password hashes.</param>
/// <param name="groupService">A deferred handle to the group service.</param>
/// <param name="dynamicGroupService">A deferred handle to the on-demand group creation service.</param>
/// <param name="restrictionService">A deferred handle to the content restriction service.</param>
/// <param name="logger">The logger.</param>
/// <remarks>
/// The group services are taken as <see cref="Lazy{T}"/> to break a container-level cycle.
/// Jellyfin's <c>UserManager</c> constructor-injects every <see cref="IAuthenticationProvider"/>,
/// so resolving those services eagerly here would require <c>IUserManager</c> while it is still
/// being built and the host would refuse to start. Deferring the lookup to the first
/// authentication is safe: nobody can log in until the host is fully up.
/// </remarks>
public SharedAccountAuthenticationProvider(
ICryptoProvider cryptoProvider,
Lazy<Services.IGroupService> groupService,
Lazy<Services.IDynamicGroupService> dynamicGroupService,
Lazy<Services.IRestrictionService> restrictionService,
ILogger<SharedAccountAuthenticationProvider> logger)
{
_cryptoProvider = cryptoProvider;
_groupService = groupService;
_dynamicGroupService = dynamicGroupService;
_restrictionService = restrictionService;
_logger = logger;
}
/// <inheritdoc />
public string Name => "Watched Together Shared Account";
/// <inheritdoc />
public bool IsEnabled => true;
/// <inheritdoc />
/// <remarks>
/// Jellyfin calls the <see cref="IRequiresResolvedUser"/> overload instead, so this exists only
/// to satisfy the interface.
/// </remarks>
public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
=> Authenticate(username, password, null);
/// <inheritdoc />
public async Task<ProviderAuthenticationResult> Authenticate(string username, string password, User? resolvedUser)
{
// Jellyfin passes a null user when no account matches the typed name, and offers the login
// to every enabled provider. That is the hook for "type alice+bob and the account appears":
// a real user with that exact name always resolves first and never reaches this branch.
if (resolvedUser is null)
{
var created = await _dynamicGroupService.Value
.TryCreateFromLoginAsync(username, password)
.ConfigureAwait(false);
if (created is null)
{
throw new AuthenticationException("Invalid username or password.");
}
return new ProviderAuthenticationResult { Username = created.SharedUsername };
}
var group = _groupService.Value.GetGroupForSharedUser(resolvedUser.Id);
if (group is null)
{
// Either not one of ours, or the group is disabled. Either way this account has no
// member passwords to check, so it cannot be unlocked.
_logger.LogWarning(
"Rejected login for {Username}: no enabled Watched Together group owns this account",
resolvedUser.Username);
throw new AuthenticationException("Invalid username or password.");
}
var members = _groupService.Value.GetEligibleMembers(group);
if (members.Count == 0)
{
_logger.LogWarning(
"Rejected login for {Username}: group has no eligible members",
resolvedUser.Username);
throw new AuthenticationException("Invalid username or password.");
}
foreach (var member in members)
{
if (!VerifyPassword(member, password))
{
continue;
}
// Information, not Warning: a child trying their password on the family account after
// the parent raised its cap is expected, not an incident.
if (!_restrictionService.Value.IsAtLeastAsStrict(resolvedUser, member))
{
_logger.LogInformation(
"Rejected login for {Username} by member {MemberUsername}: the shared account is less restricted than the member",
resolvedUser.Username,
member.Username);
throw new AuthenticationException("Invalid username or password.");
}
_logger.LogInformation(
"Shared account {SharedUsername} unlocked by member {MemberUsername}",
resolvedUser.Username,
member.Username);
return new ProviderAuthenticationResult
{
Username = resolvedUser.Username
};
}
_logger.LogWarning(
"Rejected login for {Username}: no member password matched",
resolvedUser.Username);
throw new AuthenticationException("Invalid username or password.");
}
#if !JELLYFIN_12
/// <inheritdoc />
/// <remarks>
/// A shared account always has a password in the sense that matters to Jellyfin: some member
/// credential is required. Returning <c>false</c> would let clients offer a passwordless login.
/// Jellyfin 12 removed this hook from the provider contract along with passwordless logins.
/// </remarks>
public bool HasPassword(User user) => true;
#endif
/// <inheritdoc />
/// <remarks>
/// Shared accounts have no password of their own to change - members change their own passwords
/// in the normal way and the effect is picked up on the next login.
/// </remarks>
public Task ChangePassword(User user, string newPassword)
{
throw new NotSupportedException(
"A Watched Together shared account has no password of its own. Members change their own passwords instead.");
}
/// <summary>
/// Verifies a submitted password against a member's live stored hash.
/// </summary>
/// <param name="member">The member whose stored credential to check.</param>
/// <param name="password">The submitted password.</param>
/// <returns><c>true</c> if the password matches.</returns>
private bool VerifyPassword(User member, string password)
{
if (string.IsNullOrEmpty(member.Password))
{
// A member with no password set cannot contribute a credential to the group.
return false;
}
try
{
var hash = PasswordHash.Parse(member.Password);
return _cryptoProvider.Verify(hash, password);
}
catch (Exception ex) when (ex is FormatException or ArgumentException)
{
// Never log the hash or the submitted password.
_logger.LogError(
ex,
"Could not parse the stored password hash for member {MemberId}; skipping",
member.Id);
return false;
}
}
}