From 8313bbd7024f0888298d99041456eaea6deab8d9 Mon Sep 17 00:00:00 2001 From: Mihai Date: Sat, 7 Nov 2026 17:18:46 +0200 Subject: [PATCH] feat: current plan on every request, AI consent, lap status, Turnstile (H-12, HCR-015, H-17) - H-12: PlanClaimsTransformation replaces the JWT's Plan claim with the user's plan from the database (PlanLookup, cached 60 s; cleared on upgrade/downgrade); the telemetry socket uses it too. - HCR-015 (consent part): AiConsent table + AddAiConsent migration, GET/PUT /api/me/ai-consent (versioned, off until granted); "Your data" card on /link. - Session page: GET /api/simracing/sessions/{id}/validations and a card showing which laps count for the leaderboards and why others don't. - H-17: Cloudflare Turnstile on sign-up (TurnstileVerifier; skipped when Turnstile:SecretKey is unset). Not on forgot-password: the mobile app calls it natively; the rate limit protects it. Site key and secret are passed through docker-compose and the client Dockerfile. --- docker-compose.yml | 3 + docker/client/Dockerfile | 2 + .../API/Controllers/AiConsentController.cs | 68 + .../API/Controllers/AuthController.cs | 6 +- .../Controllers/SimLeaderboardsController.cs | 25 + .../API/Controllers/SubscriptionController.cs | 6 +- .../TelemetryWebSocketMiddleware.cs | 6 +- turn-one-backend/API/Program.cs | 6 + turn-one-backend/API/Security/PlanClaims.cs | 83 + .../API/Security/TurnstileVerifier.cs | 50 + .../Application/DTOs/RegisterDto.cs | 3 + turn-one-backend/Domain/Entities/AiConsent.cs | 28 + .../20261107151213_AddAiConsent.Designer.cs | 1903 +++++++++++++++++ .../Migrations/20261107151213_AddAiConsent.cs | 45 + .../TurnOneDbContextModelSnapshot.cs | 34 + .../Infrastructure/TurnOneDbContext.cs | 8 + .../Tests/API/PhaseOneHubTests.cs | 119 ++ turn-one-client/app/(dashboard)/link/page.tsx | 39 +- .../simracing/sessions/[id]/page.tsx | 2 + turn-one-client/app/auth/signup/page.tsx | 8 +- turn-one-client/components/auth/turnstile.tsx | 69 + .../dashboard/simracing/lap-eligibility.tsx | 47 + turn-one-client/lib/simracing/leaderboards.ts | 46 + turn-one-client/types/auth-types.ts | 2 + 24 files changed, 2601 insertions(+), 7 deletions(-) create mode 100644 turn-one-backend/API/Controllers/AiConsentController.cs create mode 100644 turn-one-backend/API/Security/PlanClaims.cs create mode 100644 turn-one-backend/API/Security/TurnstileVerifier.cs create mode 100644 turn-one-backend/Domain/Entities/AiConsent.cs create mode 100644 turn-one-backend/Infrastructure/Migrations/20261107151213_AddAiConsent.Designer.cs create mode 100644 turn-one-backend/Infrastructure/Migrations/20261107151213_AddAiConsent.cs create mode 100644 turn-one-backend/Tests/API/PhaseOneHubTests.cs create mode 100644 turn-one-client/components/auth/turnstile.tsx create mode 100644 turn-one-client/components/dashboard/simracing/lap-eligibility.tsx diff --git a/docker-compose.yml b/docker-compose.yml index 46973c1..a068b29 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,6 +12,8 @@ services: - JWT__Key=${JWT__Key} - SmtpSettings__Username=${SmtpSettings__Username} - SmtpSettings__Password=${SmtpSettings__Password} + # H-17: sign-up requires a Turnstile token only when this is set (keep it in step with the site key below). + - Turnstile__SecretKey=${Turnstile__SecretKey:-} - APP_BASE_URL=${APP_BASE_URL} - CORS_ALLOWED_ORIGINS=${CORS_ALLOWED_ORIGINS} - F1_LIVETIMING_URL=${F1_LIVETIMING_URL} @@ -71,6 +73,7 @@ services: args: - NEXT_PUBLIC_BACKEND_URL=${NEXT_PUBLIC_BACKEND_URL} - NEXT_PUBLIC_F1_PROXY_URL=${NEXT_PUBLIC_F1_PROXY_URL} + - NEXT_PUBLIC_TURNSTILE_SITE_KEY=${NEXT_PUBLIC_TURNSTILE_SITE_KEY:-} ports: - "${CLIENT_PORT:-3000}:3000" environment: diff --git a/docker/client/Dockerfile b/docker/client/Dockerfile index 880f70a..b7a7f0a 100644 --- a/docker/client/Dockerfile +++ b/docker/client/Dockerfile @@ -26,6 +26,8 @@ ARG NEXT_PUBLIC_BACKEND_URL ENV NEXT_PUBLIC_BACKEND_URL=$NEXT_PUBLIC_BACKEND_URL ARG NEXT_PUBLIC_F1_PROXY_URL ENV NEXT_PUBLIC_F1_PROXY_URL=$NEXT_PUBLIC_F1_PROXY_URL +ARG NEXT_PUBLIC_TURNSTILE_SITE_KEY +ENV NEXT_PUBLIC_TURNSTILE_SITE_KEY=$NEXT_PUBLIC_TURNSTILE_SITE_KEY COPY --from=deps /app/node_modules ./node_modules COPY turn-one-client/ ./ diff --git a/turn-one-backend/API/Controllers/AiConsentController.cs b/turn-one-backend/API/Controllers/AiConsentController.cs new file mode 100644 index 0000000..e183026 --- /dev/null +++ b/turn-one-backend/API/Controllers/AiConsentController.cs @@ -0,0 +1,68 @@ +using System.Security.Claims; +using Domain.Entities; +using Infrastructure; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace API.Controllers; + +/// +/// HCR-015 (consent part) — GET/PUT /api/me/ai-consent. Only the consent record for now; the dataset +/// export and coach feedback come with the coach in Phase 2. +/// +[ApiController] +[Route("api/me/ai-consent")] +[Authorize] +public class AiConsentController : ControllerBase +{ + private readonly TurnOneDbContext _db; + + public AiConsentController(TurnOneDbContext db) + { + _db = db; + } + + public sealed class ConsentRequest + { + public bool Granted { get; set; } + /// The version of the text the user saw; a stale one is refused so nobody agrees to an old purpose. + public string Version { get; set; } = ""; + } + + [HttpGet] + public async Task Get() + { + var userId = UserId(); + var row = await _db.AiConsents.AsNoTracking().FirstOrDefaultAsync(c => c.UserId == userId); + var granted = row is { Granted: true } && row.Version == AiConsent.CurrentVersion; + return Ok(new { granted, version = AiConsent.CurrentVersion, grantedAt = granted ? row!.GrantedAt : null }); + } + + [HttpPut] + public async Task Put([FromBody] ConsentRequest body) + { + if (body.Version != AiConsent.CurrentVersion) + return BadRequest(new { message = "The consent text has changed — reload the page.", version = AiConsent.CurrentVersion }); + + var userId = UserId(); + var row = await _db.AiConsents.FirstOrDefaultAsync(c => c.UserId == userId); + if (row == null) + { + row = new AiConsent { Id = Guid.NewGuid(), UserId = userId }; + _db.AiConsents.Add(row); + } + + var now = DateTime.UtcNow; + row.Version = AiConsent.CurrentVersion; + row.UpdatedAt = now; + if (body.Granted && !row.Granted) row.GrantedAt = now; + if (!body.Granted && row.Granted) row.WithdrawnAt = now; + row.Granted = body.Granted; + + await _db.SaveChangesAsync(); + return NoContent(); + } + + private Guid UserId() => Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); +} diff --git a/turn-one-backend/API/Controllers/AuthController.cs b/turn-one-backend/API/Controllers/AuthController.cs index 850c644..3cb751c 100644 --- a/turn-one-backend/API/Controllers/AuthController.cs +++ b/turn-one-backend/API/Controllers/AuthController.cs @@ -33,8 +33,11 @@ public AuthController( [EnableRateLimiting(RateLimits.Auth)] [HttpPost("register")] - public async Task> Register(RegisterDto registerDto) + public async Task> Register(RegisterDto registerDto, [FromServices] TurnstileVerifier turnstile) { + if (!await turnstile.VerifyAsync(registerDto.TurnstileToken, RateLimits.ClientIp(HttpContext))) + return BadRequest(new AuthResponseDto { Success = false, Message = "Please complete the security check and try again." }); + var response = await _authService.Register(registerDto); if (!response.Success) @@ -127,6 +130,7 @@ public async Task> ConfirmEmail([FromQuery] string token) [HttpPost("forgot-password")] public async Task ForgotPassword([FromBody] ForgotPasswordDto forgotPasswordDto) { + // No Turnstile here: the mobile app calls this endpoint natively; the rate limit protects it. if (string.IsNullOrEmpty(forgotPasswordDto.Email)) { return BadRequest(new { success = false, message = "Email is required" }); diff --git a/turn-one-backend/API/Controllers/SimLeaderboardsController.cs b/turn-one-backend/API/Controllers/SimLeaderboardsController.cs index e351eb0..745dd8f 100644 --- a/turn-one-backend/API/Controllers/SimLeaderboardsController.cs +++ b/turn-one-backend/API/Controllers/SimLeaderboardsController.cs @@ -63,6 +63,31 @@ public async Task Validation(Guid lapId) }); } + /// Per-lap leaderboard eligibility for a whole session (session page, HF-02/HF-04). + [HttpGet("sessions/{sessionId:guid}/validations")] + [AllowAnonymous] + public async Task SessionValidations(Guid sessionId) + { + var session = await _db.TelemetrySessions.AsNoTracking() + .Where(s => s.Id == sessionId).Select(s => new { s.UserId, s.Visibility }).FirstOrDefaultAsync(); + if (session == null) return NotFound(); + if (session.Visibility != Domain.Enums.TelemetryVisibility.Public && session.UserId != ViewerId()) return NotFound(); + + var rows = await _db.LapValidations.AsNoTracking() + .Where(v => v.Lap.SessionId == sessionId) + .Select(v => new { v.Lap.LapNumber, v.LapId, v.Eligible, v.Reasons }) + .OrderBy(v => v.LapNumber) + .ToListAsync(); + + return Ok(rows.Select(v => new + { + lapNumber = v.LapNumber, + lapId = v.LapId, + eligible = v.Eligible, + reasons = v.Reasons.Split(',', StringSplitOptions.RemoveEmptyEntries), + })); + } + [HttpGet("drivers/{username}/pbs")] [AllowAnonymous] public async Task PersonalBests(string username) diff --git a/turn-one-backend/API/Controllers/SubscriptionController.cs b/turn-one-backend/API/Controllers/SubscriptionController.cs index 565f0b5..0f5b010 100644 --- a/turn-one-backend/API/Controllers/SubscriptionController.cs +++ b/turn-one-backend/API/Controllers/SubscriptionController.cs @@ -13,9 +13,11 @@ namespace API.Controllers; public class SubscriptionController : ControllerBase { private readonly ISubscriptionService _subscriptionService; + private readonly API.Security.PlanLookup _plans; - public SubscriptionController(ISubscriptionService subscriptionService) + public SubscriptionController(ISubscriptionService subscriptionService, API.Security.PlanLookup plans) { + _plans = plans; _subscriptionService = subscriptionService; } @@ -30,6 +32,7 @@ public async Task> UpgradePlan([FromBody] PlanType newPlan) { var userId = GetUserId(); var user = await _subscriptionService.UpgradePlanAsync(userId, newPlan); + _plans.Forget(userId); // the new plan applies on the next request, not after re-login return Ok(user); } catch (InvalidOperationException ex) @@ -50,6 +53,7 @@ public async Task> DowngradePlan([FromBody] PlanType newPlan) { var userId = GetUserId(); var user = await _subscriptionService.DowngradePlanAsync(userId, newPlan); + _plans.Forget(userId); return Ok(user); } catch (InvalidOperationException ex) diff --git a/turn-one-backend/API/Middleware/TelemetryWebSocketMiddleware.cs b/turn-one-backend/API/Middleware/TelemetryWebSocketMiddleware.cs index 51f935f..716aa16 100644 --- a/turn-one-backend/API/Middleware/TelemetryWebSocketMiddleware.cs +++ b/turn-one-backend/API/Middleware/TelemetryWebSocketMiddleware.cs @@ -71,8 +71,10 @@ public async Task InvokeAsync(HttpContext context, TelemetryIngestionService ing return; } - var planClaim = principal.FindFirst("Plan")?.Value; - var plan = Enum.TryParse(planClaim, out var p) ? p : PlanType.BASIC; + // The plan as it is now (H-12), not as it was when the token was issued. + var plans = context.RequestServices.GetRequiredService(); + var plan = await plans.GetAsync(userId) + ?? (Enum.TryParse(principal.FindFirst("Plan")?.Value, out var p) ? p : PlanType.BASIC); var modeQuery = context.Request.Query["mode"].ToString().ToLower(); var mode = modeQuery == "live" ? TelemetryMode.ExtremeLive : TelemetryMode.Normal; diff --git a/turn-one-backend/API/Program.cs b/turn-one-backend/API/Program.cs index 8ce9954..cea3690 100644 --- a/turn-one-backend/API/Program.cs +++ b/turn-one-backend/API/Program.cs @@ -327,6 +327,12 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + +// H-12: every request sees the user's current plan, not the one baked into the JWT. +builder.Services.AddMemoryCache(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/turn-one-backend/API/Security/PlanClaims.cs b/turn-one-backend/API/Security/PlanClaims.cs new file mode 100644 index 0000000..6a4b63f --- /dev/null +++ b/turn-one-backend/API/Security/PlanClaims.cs @@ -0,0 +1,83 @@ +using System.Security.Claims; +using Domain.Enums; +using Infrastructure; +using Microsoft.AspNetCore.Authentication; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Memory; + +namespace API.Security; + +/// +/// H-12 — the user's plan as it is in the database now, cached for a minute. The JWT's "Plan" claim +/// is only what the plan was at sign-in (7 days ago at worst), so upgrades and downgrades lagged. +/// +public sealed class PlanLookup +{ + private static readonly TimeSpan CacheFor = TimeSpan.FromSeconds(60); + + private readonly IMemoryCache _cache; + private readonly IServiceScopeFactory _scopes; + + public PlanLookup(IMemoryCache cache, IServiceScopeFactory scopes) + { + _cache = cache; + _scopes = scopes; + } + + /// The current plan, or null when the user doesn't exist (deleted account). + public async Task GetAsync(Guid userId) + { + if (_cache.TryGetValue(CacheKey(userId), out PlanType? cached)) return cached; + + using var scope = _scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var plan = await db.Users.AsNoTracking().Where(u => u.Id == userId) + .Select(u => (PlanType?)u.Plan).FirstOrDefaultAsync(); + + _cache.Set(CacheKey(userId), plan, CacheFor); + return plan; + } + + /// Call after changing a user's plan so the next request sees it immediately. + public void Forget(Guid userId) => _cache.Remove(CacheKey(userId)); + + private static string CacheKey(Guid userId) => $"plan:{userId}"; +} + +/// +/// Replaces the token's "Plan" claim with 's value on every authenticated +/// request, so every existing User.FindFirstValue("Plan") check uses the current plan. +/// +public sealed class PlanClaimsTransformation : IClaimsTransformation +{ + private const string PlanClaim = "Plan"; + private const string MarkerClaim = "PlanFromDatabase"; + + private readonly PlanLookup _plans; + + public PlanClaimsTransformation(PlanLookup plans) + { + _plans = plans; + } + + public async Task TransformAsync(ClaimsPrincipal principal) + { + if (principal.HasClaim(c => c.Type == MarkerClaim)) return principal; // already done this request + if (!Guid.TryParse(principal.FindFirstValue(ClaimTypes.NameIdentifier), out var userId)) return principal; + + var plan = await _plans.GetAsync(userId); + if (plan == null) return principal; + + return WithPlan(principal, plan.Value); + } + + public static ClaimsPrincipal WithPlan(ClaimsPrincipal principal, PlanType plan) + { + var copy = principal.Clone(); + var identity = (ClaimsIdentity)copy.Identity!; + foreach (var old in identity.FindAll(PlanClaim).ToList()) identity.RemoveClaim(old); + identity.AddClaim(new Claim(PlanClaim, plan.ToString())); + identity.AddClaim(new Claim(MarkerClaim, "1")); + return copy; + } +} diff --git a/turn-one-backend/API/Security/TurnstileVerifier.cs b/turn-one-backend/API/Security/TurnstileVerifier.cs new file mode 100644 index 0000000..8b47b2f --- /dev/null +++ b/turn-one-backend/API/Security/TurnstileVerifier.cs @@ -0,0 +1,50 @@ +using System.Text.Json; + +namespace API.Security; + +/// +/// H-17 — Cloudflare Turnstile check for sign-up and password reset. With no +/// Turnstile:SecretKey configured (local development) every request passes. +/// +public sealed class TurnstileVerifier +{ + private const string VerifyUrl = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; + + private readonly IHttpClientFactory _http; + private readonly IConfiguration _config; + private readonly ILogger _logger; + + public TurnstileVerifier(IHttpClientFactory http, IConfiguration config, ILogger logger) + { + _http = http; + _config = config; + _logger = logger; + } + + public bool Enabled => !string.IsNullOrWhiteSpace(_config["Turnstile:SecretKey"]); + + public async Task VerifyAsync(string? token, string? remoteIp) + { + var secret = _config["Turnstile:SecretKey"]; + if (string.IsNullOrWhiteSpace(secret)) return true; + if (string.IsNullOrWhiteSpace(token)) return false; + + try + { + var form = new Dictionary { ["secret"] = secret, ["response"] = token }; + if (!string.IsNullOrWhiteSpace(remoteIp)) form["remoteip"] = remoteIp; + + using var client = _http.CreateClient(); + client.Timeout = TimeSpan.FromSeconds(10); + using var response = await client.PostAsync(VerifyUrl, new FormUrlEncodedContent(form)); + using var json = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync()); + return json.RootElement.TryGetProperty("success", out var ok) && ok.GetBoolean(); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException) + { + // Cloudflare unreachable: fail closed for these two forms (rate limits still apply), but log it. + _logger.LogWarning(ex, "Turnstile verification unavailable"); + return false; + } + } +} diff --git a/turn-one-backend/Application/DTOs/RegisterDto.cs b/turn-one-backend/Application/DTOs/RegisterDto.cs index 20befcf..8392d04 100644 --- a/turn-one-backend/Application/DTOs/RegisterDto.cs +++ b/turn-one-backend/Application/DTOs/RegisterDto.cs @@ -19,4 +19,7 @@ public class RegisterDto [Required] [Compare("Password")] public string ConfirmPassword { get; set; } = string.Empty; + + /// Cloudflare Turnstile response from the sign-up form (H-17); checked when Turnstile is configured. + public string? TurnstileToken { get; set; } } diff --git a/turn-one-backend/Domain/Entities/AiConsent.cs b/turn-one-backend/Domain/Entities/AiConsent.cs new file mode 100644 index 0000000..c08385b --- /dev/null +++ b/turn-one-backend/Domain/Entities/AiConsent.cs @@ -0,0 +1,28 @@ +using System.ComponentModel.DataAnnotations; + +namespace Domain.Entities; + +/// +/// HCR-015 — a driver's separate, opt-in consent to their laps and coaching feedback being used to +/// train Turn One's own model later (plan D8 / D12). Off unless granted; versioned so a changed +/// purpose needs a new yes. +/// +public class AiConsent +{ + /// Bump when what the data is used for changes; older grants then no longer count. + public const string CurrentVersion = "2026-11"; + + [Key] + public Guid Id { get; set; } + + public Guid UserId { get; set; } + + [Required, MaxLength(20)] + public string Version { get; set; } = CurrentVersion; + + public bool Granted { get; set; } + + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + public DateTime? GrantedAt { get; set; } + public DateTime? WithdrawnAt { get; set; } +} diff --git a/turn-one-backend/Infrastructure/Migrations/20261107151213_AddAiConsent.Designer.cs b/turn-one-backend/Infrastructure/Migrations/20261107151213_AddAiConsent.Designer.cs new file mode 100644 index 0000000..10f8072 --- /dev/null +++ b/turn-one-backend/Infrastructure/Migrations/20261107151213_AddAiConsent.Designer.cs @@ -0,0 +1,1903 @@ +// +using System; +using Infrastructure; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Infrastructure.Migrations +{ + [DbContext(typeof(TurnOneDbContext))] + [Migration("20261107151213_AddAiConsent")] + partial class AddAiConsent + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Domain.Entities.AiConsent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Granted") + .HasColumnType("boolean"); + + b.Property("GrantedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("WithdrawnAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("AiConsents"); + }); + + modelBuilder.Entity("Domain.Entities.ApiWishlist", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddress") + .HasColumnType("text"); + + b.Property("IsNotified") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("SubscribedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("SubscribedAt"); + + b.ToTable("ApiWishlists"); + }); + + modelBuilder.Entity("Domain.Entities.Car", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CarClassId") + .HasColumnType("uuid"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Status") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CarClassId"); + + b.HasIndex("Slug") + .IsUnique(); + + b.ToTable("Cars"); + }); + + modelBuilder.Entity("Domain.Entities.CarAlias", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CarId") + .HasColumnType("uuid"); + + b.Property("SimCarId") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Source") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CarId"); + + b.HasIndex("Source", "SimCarId") + .IsUnique(); + + b.ToTable("CarAliases"); + }); + + modelBuilder.Entity("Domain.Entities.CarClass", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.HasKey("Id"); + + b.HasIndex("Slug") + .IsUnique(); + + b.ToTable("CarClasses"); + }); + + modelBuilder.Entity("Domain.Entities.CoinTransaction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Amount") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("PredictionId") + .HasColumnType("uuid"); + + b.Property("TriviaAttemptId") + .HasColumnType("uuid"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.ToTable("CoinTransactions"); + }); + + modelBuilder.Entity("Domain.Entities.Device", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AppVersion") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Devices"); + }); + + modelBuilder.Entity("Domain.Entities.DevicePairing", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AppVersion") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ApprovedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ApprovedByUserId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceCodeHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("DeviceId") + .HasColumnType("uuid"); + + b.Property("DeviceName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastPolledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UserCode") + .IsRequired() + .HasMaxLength(9) + .HasColumnType("character varying(9)"); + + b.HasKey("Id"); + + b.HasIndex("DeviceCodeHash") + .IsUnique(); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("UserCode"); + + b.ToTable("DevicePairings"); + }); + + modelBuilder.Entity("Domain.Entities.DeviceRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceId") + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReplacedById") + .HasColumnType("uuid"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("DeviceId"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("DeviceRefreshTokens"); + }); + + modelBuilder.Entity("Domain.Entities.ExportPreset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ChartKeys") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OutputSizes") + .IsRequired() + .HasColumnType("text"); + + b.Property("SessionType") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("SessionType"); + + b.HasIndex("UpdatedAt"); + + b.ToTable("ExportPresets"); + }); + + modelBuilder.Entity("Domain.Entities.LapCorner", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApexM") + .HasColumnType("real"); + + b.Property("BrakeReleaseM") + .HasColumnType("real"); + + b.Property("BrakeToThrottleMs") + .HasColumnType("integer"); + + b.Property("BrakingPointM") + .HasColumnType("real"); + + b.Property("CornerIndex") + .HasColumnType("smallint"); + + b.Property("Direction") + .HasColumnType("smallint"); + + b.Property("EntryM") + .HasColumnType("real"); + + b.Property("EntrySpeedKmh") + .HasColumnType("real"); + + b.Property("ExitM") + .HasColumnType("real"); + + b.Property("ExitSpeedKmh") + .HasColumnType("real"); + + b.Property("FullThrottleM") + .HasColumnType("real"); + + b.Property("GearAtApex") + .HasColumnType("smallint"); + + b.Property("IsKink") + .HasColumnType("boolean"); + + b.Property("MinGear") + .HasColumnType("smallint"); + + b.Property("MinSpeedKmh") + .HasColumnType("real"); + + b.Property("PeakBrake") + .HasColumnType("real"); + + b.Property("PeakGLat") + .HasColumnType("real"); + + b.Property("ProfileVersion") + .HasColumnType("integer"); + + b.Property("RefCornerIndex") + .HasColumnType("smallint"); + + b.Property("SessionId") + .HasColumnType("uuid"); + + b.Property("Source") + .HasColumnType("integer"); + + b.Property("TelemetryLapId") + .HasColumnType("uuid"); + + b.Property("ThrottleOnM") + .HasColumnType("real"); + + b.Property("TimeInCornerMs") + .HasColumnType("integer"); + + b.Property("TrackProfileId") + .HasColumnType("uuid"); + + b.Property("TrailBrakeM") + .HasColumnType("real"); + + b.HasKey("Id"); + + b.HasIndex("TelemetryLapId", "CornerIndex") + .IsUnique(); + + b.HasIndex("TrackProfileId", "RefCornerIndex"); + + b.ToTable("LapCorners"); + }); + + modelBuilder.Entity("Domain.Entities.LapTelemetry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ChannelIndex") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Codec") + .HasColumnType("smallint"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Data") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("DistanceSource") + .HasColumnType("integer"); + + b.Property("ProcessorVersion") + .HasColumnType("integer"); + + b.Property("SampleCount") + .HasColumnType("integer"); + + b.Property("SessionId") + .HasColumnType("uuid"); + + b.Property("StepM") + .HasColumnType("real"); + + b.Property("TelemetryLapId") + .HasColumnType("uuid"); + + b.Property("UncompressedBytes") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SessionId"); + + b.HasIndex("TelemetryLapId") + .IsUnique(); + + b.ToTable("LapTelemetries"); + }); + + modelBuilder.Entity("Domain.Entities.LapUpload", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ContentHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("DeviceId") + .HasColumnType("uuid"); + + b.Property("Error") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("IdempotencyKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("LapNumber") + .HasColumnType("integer"); + + b.Property("ReceivedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SessionId") + .HasColumnType("uuid"); + + b.Property("SizeBytes") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("TickCount") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("SessionId", "LapNumber"); + + b.HasIndex("UserId", "IdempotencyKey") + .IsUnique(); + + b.ToTable("LapUploads"); + }); + + modelBuilder.Entity("Domain.Entities.LapValidation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CarClassId") + .HasColumnType("uuid"); + + b.Property("CarId") + .HasColumnType("uuid"); + + b.Property("CheckedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ConditionKey") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Eligible") + .HasColumnType("boolean"); + + b.Property("LapId") + .HasColumnType("uuid"); + + b.Property("LapTimeMs") + .HasColumnType("integer"); + + b.Property("Reasons") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("RecordedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Source") + .HasColumnType("integer"); + + b.Property("TrackLayoutId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("ValidatorVersion") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("LapId") + .IsUnique(); + + b.HasIndex("UserId"); + + b.HasIndex("Source", "TrackLayoutId", "CarClassId", "Eligible", "LapTimeMs"); + + b.HasIndex("Source", "TrackLayoutId", "CarId", "Eligible", "LapTimeMs"); + + b.ToTable("LapValidations"); + }); + + modelBuilder.Entity("Domain.Entities.Leaderboard", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CorrectPredictions") + .HasColumnType("integer"); + + b.Property("CurrentStreak") + .HasColumnType("integer"); + + b.Property("GlobalRank") + .HasColumnType("integer"); + + b.Property("LastUpdated") + .HasColumnType("timestamp with time zone"); + + b.Property("LongestStreak") + .HasColumnType("integer"); + + b.Property("Season") + .IsRequired() + .HasColumnType("text"); + + b.Property("SeasonRank") + .HasColumnType("integer"); + + b.Property("TotalCoinsEarned") + .HasColumnType("integer"); + + b.Property("TotalPointsEarned") + .HasColumnType("integer"); + + b.Property("TotalPredictions") + .HasColumnType("integer"); + + b.Property("TriviaAttempts") + .HasColumnType("integer"); + + b.Property("TriviaCorrect") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GlobalRank"); + + b.HasIndex("Season"); + + b.HasIndex("UserId"); + + b.ToTable("Leaderboards"); + }); + + modelBuilder.Entity("Domain.Entities.Media", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AltText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue(""); + + b.Property("FileName") + .IsRequired() + .HasColumnType("text"); + + b.Property("FilePath") + .IsRequired() + .HasColumnType("text"); + + b.Property("FileSize") + .HasColumnType("bigint"); + + b.Property("FileType") + .IsRequired() + .HasColumnType("text"); + + b.Property("OriginalFileName") + .IsRequired() + .HasColumnType("text"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UploadedByUserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("FileName"); + + b.HasIndex("UploadedAt"); + + b.ToTable("Media"); + }); + + modelBuilder.Entity("Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedById") + .HasColumnType("uuid"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("Message") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetAudience") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetPlans") + .HasColumnType("text"); + + b.Property("TargetRoles") + .HasColumnType("text"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CreatedById"); + + b.ToTable("Notifications"); + }); + + modelBuilder.Entity("Domain.Entities.OverlayShareToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Label") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scopes") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Token") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("OverlayShareTokens"); + }); + + modelBuilder.Entity("Domain.Entities.PageStatus", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IsDisabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("MaintenanceMessage") + .HasColumnType("text"); + + b.Property("PageSlug") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedByUsername") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("PageSlug") + .IsUnique(); + + b.ToTable("PageStatuses"); + }); + + modelBuilder.Entity("Domain.Entities.Prediction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CoinsEarned") + .HasColumnType("integer"); + + b.Property("CoinsWagered") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FastestLapDriver") + .HasColumnType("text"); + + b.Property("FirstRetirementLap") + .HasColumnType("integer"); + + b.Property("NumberOfDnfs") + .HasColumnType("integer"); + + b.Property("PodiumP1") + .HasColumnType("text"); + + b.Property("PodiumP2") + .HasColumnType("text"); + + b.Property("PodiumP3") + .HasColumnType("text"); + + b.Property("PointsEarned") + .HasColumnType("integer"); + + b.Property("PolePositionDriver") + .HasColumnType("text"); + + b.Property("PotentialPayout") + .HasColumnType("integer"); + + b.Property("RaceDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("RaceId") + .IsRequired() + .HasColumnType("text"); + + b.Property("RaceName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Season") + .IsRequired() + .HasColumnType("text"); + + b.Property("SettledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WillThereBeASafetyCar") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("UserId"); + + b.ToTable("Predictions"); + }); + + modelBuilder.Entity("Domain.Entities.SimUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("HighestSpeedKmh") + .HasColumnType("real"); + + b.Property("LastSessionAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LeaderboardVisibility") + .HasColumnType("integer"); + + b.Property("TotalDistanceKm") + .HasColumnType("double precision"); + + b.Property("TotalLaps") + .HasColumnType("integer"); + + b.Property("TotalPlayTimeSeconds") + .HasColumnType("integer"); + + b.Property("TotalSessions") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SimUsers"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetryGenerationRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Drivers") + .HasColumnType("text"); + + b.Property("DurationMs") + .HasColumnType("integer"); + + b.Property("ErrorMessage") + .HasColumnType("text"); + + b.Property("EventName") + .IsRequired() + .HasColumnType("text"); + + b.Property("PlotType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Session") + .IsRequired() + .HasColumnType("text"); + + b.Property("Success") + .HasColumnType("boolean"); + + b.Property("TokensUsed") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Year") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.ToTable("TelemetryGenerationRequests"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetryLap", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AverageBrake") + .HasColumnType("real"); + + b.Property("AverageSpeedKmh") + .HasColumnType("real"); + + b.Property("AverageThrottle") + .HasColumnType("real"); + + b.Property("BrakingPct") + .HasColumnType("real"); + + b.Property("BrakingScore") + .HasColumnType("real"); + + b.Property("CoastingPct") + .HasColumnType("real"); + + b.Property("ConsistencyScore") + .HasColumnType("real"); + + b.Property("FuelUsed") + .HasColumnType("real"); + + b.Property("FullThrottlePct") + .HasColumnType("real"); + + b.Property("GearShifts") + .HasColumnType("integer"); + + b.Property("IsValid") + .HasColumnType("boolean"); + + b.Property("Kind") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("LapDistanceM") + .HasColumnType("real"); + + b.Property("LapNumber") + .HasColumnType("integer"); + + b.Property("LapStartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LapTimeMs") + .HasColumnType("integer"); + + b.Property("MaxRpm") + .HasColumnType("integer"); + + b.Property("MaxSpeedKmh") + .HasColumnType("real"); + + b.Property("MinSpeedKmh") + .HasColumnType("real"); + + b.Property("PeakGLat") + .HasColumnType("real"); + + b.Property("PeakGLong") + .HasColumnType("real"); + + b.Property("ProcessingError") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProcessingStatus") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ProcessorVersion") + .HasColumnType("integer"); + + b.Property("RecordedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Sector1Ms") + .HasColumnType("integer"); + + b.Property("Sector2Ms") + .HasColumnType("integer"); + + b.Property("Sector3Ms") + .HasColumnType("integer"); + + b.Property("SessionId") + .HasColumnType("uuid"); + + b.Property("ThrottleScore") + .HasColumnType("real"); + + b.HasKey("Id"); + + b.HasIndex("SessionId", "LapNumber") + .IsUnique(); + + b.HasIndex("SessionId", "IsValid", "LapTimeMs"); + + b.ToTable("TelemetryLaps"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetryLogSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AutoDeleteEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("RetentionDays") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(90); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("TelemetryLogSettings"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetrySession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BestLapMs") + .HasColumnType("integer"); + + b.Property("CarId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CarModel") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ClientVersion") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("DriverName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("EndedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("LapCount") + .HasColumnType("integer"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Mode") + .HasColumnType("integer"); + + b.Property("SchemaVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SectorCount") + .HasColumnType("integer"); + + b.Property("SessionKind") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SessionType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Source") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TickRateHz") + .HasColumnType("integer"); + + b.Property("Track") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("TrackId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("TrackLengthM") + .HasColumnType("real"); + + b.Property("TrackProfileId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Visibility") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("StartedAt"); + + b.HasIndex("TrackProfileId"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "TrackProfileId", "StartedAt"); + + b.ToTable("TelemetrySessions"); + }); + + modelBuilder.Entity("Domain.Entities.TrackAlias", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("SimTrackId") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Source") + .HasColumnType("integer"); + + b.Property("TrackLayoutId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TrackLayoutId"); + + b.HasIndex("Source", "SimTrackId") + .IsUnique(); + + b.ToTable("TrackAliases"); + }); + + modelBuilder.Entity("Domain.Entities.TrackLayout", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Country") + .HasMaxLength(60) + .HasColumnType("character varying(60)"); + + b.Property("LengthM") + .HasColumnType("real"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("Status") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Slug") + .IsUnique(); + + b.ToTable("TrackLayouts"); + }); + + modelBuilder.Entity("Domain.Entities.TrackProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Centerline") + .HasColumnType("bytea"); + + b.Property("CornerSamples") + .HasColumnType("jsonb"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectorOverrides") + .HasColumnType("jsonb"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("LapSampleCount") + .HasColumnType("integer"); + + b.Property("LengthM") + .HasColumnType("real"); + + b.Property("ReferenceCorners") + .IsRequired() + .HasColumnType("jsonb"); + + b.PrimitiveCollection("SectorBoundariesM") + .IsRequired() + .HasColumnType("real[]"); + + b.Property("SectorCount") + .HasColumnType("smallint"); + + b.Property("Source") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TrackId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Source", "TrackId") + .IsUnique(); + + b.ToTable("TrackProfiles"); + }); + + modelBuilder.Entity("Domain.Entities.Trivia", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("CoinsReward") + .HasColumnType("integer"); + + b.Property("CorrectAnswer") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Difficulty") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExperienceReward") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("LastModifiedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("OptionA") + .IsRequired() + .HasColumnType("text"); + + b.Property("OptionB") + .IsRequired() + .HasColumnType("text"); + + b.Property("OptionC") + .IsRequired() + .HasColumnType("text"); + + b.Property("OptionD") + .IsRequired() + .HasColumnType("text"); + + b.Property("Question") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Trivias"); + }); + + modelBuilder.Entity("Domain.Entities.TriviaAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AttemptedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CoinsEarned") + .HasColumnType("integer"); + + b.Property("ExperienceEarned") + .HasColumnType("integer"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("SelectedAnswer") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriviaId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriviaId"); + + b.HasIndex("UserId"); + + b.ToTable("TriviaAttempts"); + }); + + modelBuilder.Entity("Domain.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AutoRenew") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("AvatarUrl") + .HasColumnType("text"); + + b.Property("Coins") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatorTokenAllowance") + .HasColumnType("integer"); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("EmailConfirmationToken") + .HasColumnType("text"); + + b.Property("EmailConfirmationTokenExpires") + .HasColumnType("timestamp with time zone"); + + b.Property("Experience") + .HasColumnType("integer"); + + b.Property("HasClaimedStarterPack") + .HasColumnType("boolean"); + + b.Property("IsEmailConfirmed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("LastDailyGiftDate") + .HasColumnType("timestamp with time zone"); + + b.Property("LastLogin") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTokenRefillDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Level") + .HasColumnType("integer"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.Property("PasswordResetToken") + .HasColumnType("text"); + + b.Property("PasswordResetTokenExpires") + .HasColumnType("timestamp with time zone"); + + b.Property("Plan") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("PlanEndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("PlanStartDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Role") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("Tokens") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(30); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Domain.Entities.UserNotification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("NotificationId") + .HasColumnType("uuid"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReceivedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("NotificationId"); + + b.HasIndex("UserId"); + + b.ToTable("UserNotifications"); + }); + + modelBuilder.Entity("Domain.Entities.Car", b => + { + b.HasOne("Domain.Entities.CarClass", "CarClass") + .WithMany() + .HasForeignKey("CarClassId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CarClass"); + }); + + modelBuilder.Entity("Domain.Entities.CarAlias", b => + { + b.HasOne("Domain.Entities.Car", "Car") + .WithMany() + .HasForeignKey("CarId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Car"); + }); + + modelBuilder.Entity("Domain.Entities.CoinTransaction", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.Device", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.DeviceRefreshToken", b => + { + b.HasOne("Domain.Entities.Device", "Device") + .WithMany() + .HasForeignKey("DeviceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Device"); + }); + + modelBuilder.Entity("Domain.Entities.ExportPreset", b => + { + b.HasOne("Domain.Entities.User", "CreatedBy") + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CreatedBy"); + }); + + modelBuilder.Entity("Domain.Entities.LapCorner", b => + { + b.HasOne("Domain.Entities.TelemetryLap", "Lap") + .WithMany("Corners") + .HasForeignKey("TelemetryLapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lap"); + }); + + modelBuilder.Entity("Domain.Entities.LapTelemetry", b => + { + b.HasOne("Domain.Entities.TelemetryLap", "Lap") + .WithOne("Telemetry") + .HasForeignKey("Domain.Entities.LapTelemetry", "TelemetryLapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lap"); + }); + + modelBuilder.Entity("Domain.Entities.LapValidation", b => + { + b.HasOne("Domain.Entities.TelemetryLap", "Lap") + .WithMany() + .HasForeignKey("LapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lap"); + }); + + modelBuilder.Entity("Domain.Entities.Leaderboard", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.Notification", b => + { + b.HasOne("Domain.Entities.User", "CreatedBy") + .WithMany() + .HasForeignKey("CreatedById") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CreatedBy"); + }); + + modelBuilder.Entity("Domain.Entities.OverlayShareToken", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.Prediction", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.SimUser", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithOne() + .HasForeignKey("Domain.Entities.SimUser", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetryGenerationRequest", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetryLap", b => + { + b.HasOne("Domain.Entities.TelemetrySession", "Session") + .WithMany("Laps") + .HasForeignKey("SessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Session"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetrySession", b => + { + b.HasOne("Domain.Entities.TrackProfile", "TrackProfile") + .WithMany() + .HasForeignKey("TrackProfileId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("TrackProfile"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.TrackAlias", b => + { + b.HasOne("Domain.Entities.TrackLayout", "TrackLayout") + .WithMany() + .HasForeignKey("TrackLayoutId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("TrackLayout"); + }); + + modelBuilder.Entity("Domain.Entities.TriviaAttempt", b => + { + b.HasOne("Domain.Entities.Trivia", "Trivia") + .WithMany("Attempts") + .HasForeignKey("TriviaId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Trivia"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.UserNotification", b => + { + b.HasOne("Domain.Entities.Notification", "Notification") + .WithMany("UserNotifications") + .HasForeignKey("NotificationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Notification"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.Notification", b => + { + b.Navigation("UserNotifications"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetryLap", b => + { + b.Navigation("Corners"); + + b.Navigation("Telemetry"); + }); + + modelBuilder.Entity("Domain.Entities.TelemetrySession", b => + { + b.Navigation("Laps"); + }); + + modelBuilder.Entity("Domain.Entities.Trivia", b => + { + b.Navigation("Attempts"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/turn-one-backend/Infrastructure/Migrations/20261107151213_AddAiConsent.cs b/turn-one-backend/Infrastructure/Migrations/20261107151213_AddAiConsent.cs new file mode 100644 index 0000000..e4e29b0 --- /dev/null +++ b/turn-one-backend/Infrastructure/Migrations/20261107151213_AddAiConsent.cs @@ -0,0 +1,45 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Infrastructure.Migrations +{ + /// + public partial class AddAiConsent : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AiConsents", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + Version = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + Granted = table.Column(type: "boolean", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false), + GrantedAt = table.Column(type: "timestamp with time zone", nullable: true), + WithdrawnAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AiConsents", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_AiConsents_UserId", + table: "AiConsents", + column: "UserId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AiConsents"); + } + } +} diff --git a/turn-one-backend/Infrastructure/Migrations/TurnOneDbContextModelSnapshot.cs b/turn-one-backend/Infrastructure/Migrations/TurnOneDbContextModelSnapshot.cs index 9318312..2e3b4b7 100644 --- a/turn-one-backend/Infrastructure/Migrations/TurnOneDbContextModelSnapshot.cs +++ b/turn-one-backend/Infrastructure/Migrations/TurnOneDbContextModelSnapshot.cs @@ -22,6 +22,40 @@ protected override void BuildModel(ModelBuilder modelBuilder) NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + modelBuilder.Entity("Domain.Entities.AiConsent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Granted") + .HasColumnType("boolean"); + + b.Property("GrantedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("WithdrawnAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("AiConsents"); + }); + modelBuilder.Entity("Domain.Entities.ApiWishlist", b => { b.Property("Id") diff --git a/turn-one-backend/Infrastructure/TurnOneDbContext.cs b/turn-one-backend/Infrastructure/TurnOneDbContext.cs index 08186c0..7335b20 100644 --- a/turn-one-backend/Infrastructure/TurnOneDbContext.cs +++ b/turn-one-backend/Infrastructure/TurnOneDbContext.cs @@ -47,6 +47,9 @@ public TurnOneDbContext(DbContextOptions options) : base(optio public DbSet CarAliases { get; set; } = null!; public DbSet LapValidations { get; set; } = null!; + // AI dataset consent (HCR-015) + public DbSet AiConsents { get; set; } = null!; + // Telemetry token-usage / request log public DbSet TelemetryGenerationRequests { get; set; } = null!; public DbSet TelemetryLogSettings { get; set; } = null!; @@ -274,6 +277,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) entity.HasOne(e => e.Car).WithMany().HasForeignKey(e => e.CarId).OnDelete(DeleteBehavior.Cascade); entity.HasIndex(e => new { e.Source, e.SimCarId }).IsUnique(); }); + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.UserId).IsUnique(); + }); modelBuilder.Entity(entity => { entity.HasKey(e => e.Id); diff --git a/turn-one-backend/Tests/API/PhaseOneHubTests.cs b/turn-one-backend/Tests/API/PhaseOneHubTests.cs new file mode 100644 index 0000000..fd853a1 --- /dev/null +++ b/turn-one-backend/Tests/API/PhaseOneHubTests.cs @@ -0,0 +1,119 @@ +using System.Security.Claims; +using API.Controllers; +using API.Security; +using Domain.Entities; +using Domain.Enums; +using FluentAssertions; +using Infrastructure; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Tests.API; + +/// H-12 plan from the database, HCR-015 consent, H-17 Turnstile switch. +public class PhaseOneHubTests +{ + private static (IServiceProvider sp, Guid userId) Db(string name, PlanType plan) + { + var services = new ServiceCollection(); + services.AddDbContext(o => o.UseInMemoryDatabase(name)); + var sp = services.BuildServiceProvider(); + var userId = Guid.NewGuid(); + using var scope = sp.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Users.Add(new User { Id = userId, Email = "p@t.t", Username = "p", Password = "x", Plan = plan }); + db.SaveChanges(); + return (sp, userId); + } + + private static ClaimsPrincipal Token(Guid userId, string plan) => new(new ClaimsIdentity(new[] + { + new Claim(ClaimTypes.NameIdentifier, userId.ToString()), + new Claim("Plan", plan), + }, "test")); + + [Fact] + public async Task Requests_Use_The_Plan_In_The_Database_Not_The_Token() + { + var (sp, userId) = Db(nameof(Requests_Use_The_Plan_In_The_Database_Not_The_Token), PlanType.PRO); + var lookup = new PlanLookup(new MemoryCache(new MemoryCacheOptions()), sp.GetRequiredService()); + var transform = new PlanClaimsTransformation(lookup); + + // Token still says BASIC (issued before the upgrade). + var principal = await transform.TransformAsync(Token(userId, "BASIC")); + + principal.FindAll("Plan").Select(c => c.Value).Should().Equal("PRO"); + (await transform.TransformAsync(principal)).FindAll("Plan").Should().ContainSingle(); // idempotent + } + + [Fact] + public async Task A_Plan_Change_Shows_Up_After_Forget() + { + var (sp, userId) = Db(nameof(A_Plan_Change_Shows_Up_After_Forget), PlanType.BASIC); + var lookup = new PlanLookup(new MemoryCache(new MemoryCacheOptions()), sp.GetRequiredService()); + (await lookup.GetAsync(userId)).Should().Be(PlanType.BASIC); + + using (var scope = sp.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + (await db.Users.SingleAsync()).Plan = PlanType.ELITE; + await db.SaveChangesAsync(); + } + + (await lookup.GetAsync(userId)).Should().Be(PlanType.BASIC); // cached + lookup.Forget(userId); + (await lookup.GetAsync(userId)).Should().Be(PlanType.ELITE); + (await lookup.GetAsync(Guid.NewGuid())).Should().BeNull(); + } + + private static AiConsentController Consent(TurnOneDbContext db, Guid userId) => new(db) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext { User = Token(userId, "BASIC") }, + }, + }; + + [Fact] + public async Task Ai_Consent_Is_Off_Until_Granted_And_Can_Be_Withdrawn() + { + var (sp, userId) = Db(nameof(Ai_Consent_Is_Off_Until_Granted_And_Can_Be_Withdrawn), PlanType.BASIC); + using var scope = sp.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var api = Consent(db, userId); + + object Body(IActionResult r) => ((OkObjectResult)r).Value!; + bool Granted(object body) => (bool)body.GetType().GetProperty("granted")!.GetValue(body)!; + + Granted(Body(await api.Get())).Should().BeFalse(); + + (await api.Put(new AiConsentController.ConsentRequest { Granted = true, Version = "2020-01" })) + .Should().BeOfType("an old consent text can't be agreed to"); + + await api.Put(new AiConsentController.ConsentRequest { Granted = true, Version = AiConsent.CurrentVersion }); + Granted(Body(await api.Get())).Should().BeTrue(); + + await api.Put(new AiConsentController.ConsentRequest { Granted = false, Version = AiConsent.CurrentVersion }); + var row = await db.AiConsents.SingleAsync(); + row.Granted.Should().BeFalse(); + row.WithdrawnAt.Should().NotBeNull(); + } + + private static TurnstileVerifier Turnstile(string? secret) => new( + new ServiceCollection().AddHttpClient().BuildServiceProvider().GetRequiredService(), + new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["Turnstile:SecretKey"] = secret }).Build(), + NullLogger.Instance); + + [Fact] + public async Task Turnstile_Is_Skipped_Without_A_Secret_And_Requires_A_Token_With_One() + { + (await Turnstile(null).VerifyAsync(null, null)).Should().BeTrue(); + (await Turnstile("secret").VerifyAsync(null, "1.2.3.4")).Should().BeFalse(); + (await Turnstile("secret").VerifyAsync("", "1.2.3.4")).Should().BeFalse(); + } +} diff --git a/turn-one-client/app/(dashboard)/link/page.tsx b/turn-one-client/app/(dashboard)/link/page.tsx index 9f71572..aacf918 100644 --- a/turn-one-client/app/(dashboard)/link/page.tsx +++ b/turn-one-client/app/(dashboard)/link/page.tsx @@ -2,12 +2,13 @@ import { useCallback, useEffect, useState } from "react"; import { formatDistanceToNow } from "date-fns"; -import { CheckCircle2, Laptop, Link2, ShieldAlert, Trash2 } from "lucide-react"; +import { CheckCircle2, Laptop, Link2, ShieldAlert, Sparkles, Trash2 } from "lucide-react"; import { PageHeader } from "@/components/dashboard/page-header"; import { SectionCard } from "@/components/dashboard/simracing/section-card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { SimApiError } from "@/lib/simracing/api"; +import { getAiConsent, setAiConsent, type AiConsent } from "@/lib/simracing/leaderboards"; import { approvePairing, getPairing, @@ -34,6 +35,7 @@ export default function LinkDevicePage() { const [step, setStep] = useState({ kind: "enter" }); const [busy, setBusy] = useState(false); const [devices, setDevices] = useState(null); + const [consent, setConsent] = useState(null); const refreshDevices = useCallback(() => { listDevices() @@ -65,6 +67,21 @@ export default function LinkDevicePage() { } }, []); + useEffect(() => { + getAiConsent().then(setConsent).catch(() => setConsent(null)); + }, []); + + const toggleConsent = async (granted: boolean) => { + if (!consent) return; + const previous = consent; + setConsent({ ...consent, granted }); + try { + await setAiConsent(granted, consent.version); + } catch { + setConsent(previous); + } + }; + useEffect(() => { refreshDevices(); const fromUrl = new URLSearchParams(window.location.search).get("code"); @@ -200,6 +217,26 @@ export default function LinkDevicePage() { ))} + + {consent ? ( + + + + ) : null} ); } diff --git a/turn-one-client/app/(dashboard)/simracing/sessions/[id]/page.tsx b/turn-one-client/app/(dashboard)/simracing/sessions/[id]/page.tsx index a4041cd..b36ed72 100644 --- a/turn-one-client/app/(dashboard)/simracing/sessions/[id]/page.tsx +++ b/turn-one-client/app/(dashboard)/simracing/sessions/[id]/page.tsx @@ -43,6 +43,7 @@ import { LapEvolutionChart } from "@/components/dashboard/simracing/charts/lap-e import { SectorMatrixTable } from "@/components/dashboard/simracing/charts/sector-matrix"; import { TimeLossList } from "@/components/dashboard/simracing/charts/time-loss-list"; import { ShareCardButton } from "@/components/dashboard/simracing/share-card"; +import { LapEligibility } from "@/components/dashboard/simracing/lap-eligibility"; import type { LapTelemetryDto, MultiChannelChartData } from "@/lib/simracing/protocol"; import { fromLapTelemetryDto } from "@/lib/simracing/lap-telemetry"; import type { DistanceSeries } from "@/lib/simracing/analysis"; @@ -503,6 +504,7 @@ export default function SessionDetailPage() { {/* ---------------- Overview ---------------- */} {tab === "overview" ? (
+ diff --git a/turn-one-client/app/auth/signup/page.tsx b/turn-one-client/app/auth/signup/page.tsx index 983fbf1..35fe746 100644 --- a/turn-one-client/app/auth/signup/page.tsx +++ b/turn-one-client/app/auth/signup/page.tsx @@ -16,6 +16,7 @@ import { register } from "@/lib/auth" import { setAuthToken } from "@/lib/auth-utils" import { useAuth } from "@/components/auth/auth-provider" import { RegisterData } from "@/types/auth-types" +import { Turnstile, turnstileEnabled } from "@/components/auth/turnstile" export default function SignUpPage() { const [email, setEmail] = useState("") @@ -24,6 +25,7 @@ export default function SignUpPage() { const [username, setUsername] = useState("") const [error, setError] = useState(null) const [isLoading, setIsLoading] = useState(false) + const [turnstileToken, setTurnstileToken] = useState(null) const router = useRouter() const { refresh } = useAuth() @@ -39,7 +41,7 @@ export default function SignUpPage() { } try { - const registerData: RegisterData = { email, username, password, confirmPassword } + const registerData: RegisterData = { email, username, password, confirmPassword, turnstileToken: turnstileToken ?? undefined } const response = await register(registerData) if (response.success) { @@ -158,9 +160,11 @@ export default function SignUpPage() {

)} + {turnstileEnabled() && } +