Files
WatchedTogether/Jellyfin.Plugin.WatchedTogether/Services/DynamicGroupService.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

243 lines
9.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Data;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Plugin.WatchedTogether.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Cryptography;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.WatchedTogether.Services;
/// <summary>
/// Creates a shared account the first time someone logs in as "alice+bob".
/// </summary>
/// <remarks>
/// <para>
/// Jellyfin only routes a login to the providers with a null resolved user when <em>no</em> local
/// user matches the typed name. A real account named "alice+bob" therefore always wins, and this
/// code never sees it - the ambiguity between a group and a same-named user resolves in favour of
/// the real user automatically.
/// </para>
/// <para>
/// Every named member must exist and none may be a shared account, so an unrelated username
/// containing the separator simply fails to resolve and is rejected.
/// </para>
/// </remarks>
public class DynamicGroupService : IDynamicGroupService
{
private readonly IUserManager _userManager;
private readonly IProvisioningService _provisioningService;
private readonly IRestrictionService _restrictionService;
private readonly ICryptoProvider _cryptoProvider;
private readonly ILogger<DynamicGroupService> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="DynamicGroupService"/> class.
/// </summary>
/// <param name="userManager">The user manager.</param>
/// <param name="provisioningService">The provisioning service.</param>
/// <param name="restrictionService">The content restriction service.</param>
/// <param name="cryptoProvider">The crypto provider.</param>
/// <param name="logger">The logger.</param>
public DynamicGroupService(
IUserManager userManager,
IProvisioningService provisioningService,
IRestrictionService restrictionService,
ICryptoProvider cryptoProvider,
ILogger<DynamicGroupService> logger)
{
_userManager = userManager;
_provisioningService = provisioningService;
_restrictionService = restrictionService;
_cryptoProvider = cryptoProvider;
_logger = logger;
}
/// <inheritdoc />
public async Task<DynamicGroupResult?> TryCreateFromLoginAsync(string enteredUsername, string password)
{
var config = Plugin.Instance?.Configuration;
if (config is null || !config.EnableDynamicGroups)
{
return null;
}
if (string.IsNullOrWhiteSpace(enteredUsername))
{
return null;
}
var separator = string.IsNullOrEmpty(config.NameSeparator) ? "+" : config.NameSeparator;
var parts = enteredUsername
.Split(separator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.ToList();
// Needs at least two names to be a group at all.
if (parts.Count < 2)
{
return null;
}
// Every part must name a real, non-shared, enabled user. Anything else means this is not a
// group login, so fall through and let the attempt fail normally.
var members = new List<User>(parts.Count);
foreach (var part in parts)
{
var member = _userManager.GetUserByName(part);
if (member is null)
{
_logger.LogDebug("Dynamic group login rejected: no user named {Part}", part);
return null;
}
if (config.Groups.Any(g => g.SharedUserId == member.Id))
{
_logger.LogWarning(
"Dynamic group login rejected: {Part} is itself a shared account",
part);
return null;
}
if (member.HasPermission(PermissionKind.IsDisabled))
{
_logger.LogWarning("Dynamic group login rejected: {Part} is disabled", part);
return null;
}
if (members.Any(m => m.Id == member.Id))
{
_logger.LogWarning("Dynamic group login rejected: {Part} named more than once", part);
return null;
}
members.Add(member);
}
// The password must belong to one of the named members. Without this any visitor could
// conjure a shared account out of two usernames they happened to know.
//
// Members are tried in the order they were typed and the loop stops at the first match, so
// whoever types their own name first has their password checked first. Verification is a
// deliberately slow hash comparison, so the ordering is worth having.
var matched = members.FirstOrDefault(m => VerifyPassword(m, password));
if (matched is null)
{
_logger.LogWarning(
"Dynamic group login for {Username} rejected: no named member's password matched",
enteredUsername);
return null;
}
var memberIds = members.Select(m => m.Id).ToList();
// The same people in a different order are the same group: someone typing "john+jane" must
// land on the existing "jane+john" account rather than creating a second one. Jellyfin only
// reaches this code when no account matches the typed name, so without this check every
// ordering would spawn its own account.
var existing = FindGroupWithSameMembers(config, memberIds);
if (existing is not null)
{
if (existing.IsDisabled)
{
_logger.LogWarning(
"Login for {Username} rejected: the matching group is disabled",
enteredUsername);
return null;
}
var existingUser = _userManager.GetUserById(existing.SharedUserId);
if (existingUser is null)
{
_logger.LogWarning(
"Group for {Username} references a shared account that no longer exists",
enteredUsername);
return null;
}
// The same unlock rule the authentication provider applies to a resolved account: an
// existing group may have had its rating cap raised in the dashboard since it was created.
if (!_restrictionService.IsAtLeastAsStrict(existingUser, matched))
{
_logger.LogInformation(
"Rejected login for {Username} by member {MemberUsername}: the shared account is less restricted than the member",
existingUser.Username,
matched.Username);
return null;
}
_logger.LogInformation(
"Login as {Entered} resolved to the existing shared account {Username}",
enteredUsername,
existingUser.Username);
return new DynamicGroupResult(existing, existingUser.Username);
}
// Passing no name lets provisioning generate the canonical alphabetically-sorted one, so
// the account is named the same whichever order the members were typed in.
// The account is limited to the libraries all named members share and inherits their
// strictest restrictions before this returns, so creating one at the login screen cannot
// grant anybody access they did not already have - not even for the session it creates.
var group = await _provisioningService.CreateGroupAsync(memberIds, null).ConfigureAwait(false);
var sharedUser = _userManager.GetUserById(group.SharedUserId);
if (sharedUser is null)
{
return null;
}
_logger.LogInformation(
"Created shared account {Username} on demand for {MemberCount} members",
sharedUser.Username,
members.Count);
return new DynamicGroupResult(group, sharedUser.Username);
}
/// <summary>
/// Finds a configured group whose members are exactly the given set, ignoring order.
/// </summary>
/// <param name="config">The plugin configuration to search.</param>
/// <param name="memberIds">The member identifiers to match.</param>
/// <returns>The matching group, or <c>null</c> if no group has that membership.</returns>
private static SharedGroup? FindGroupWithSameMembers(
PluginConfiguration config,
IReadOnlyList<Guid> memberIds)
{
var wanted = memberIds.ToHashSet();
return config.Groups.FirstOrDefault(g =>
g.MemberUserIds.Count == wanted.Count && wanted.SetEquals(g.MemberUserIds));
}
/// <summary>
/// Verifies a submitted password against a member's live stored hash.
/// </summary>
/// <param name="member">The member 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))
{
return false;
}
try
{
return _cryptoProvider.Verify(PasswordHash.Parse(member.Password), 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}", member.Id);
return false;
}
}
}