Skip to content
Merged
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
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions docker/client/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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/ ./
Expand Down
68 changes: 68 additions & 0 deletions turn-one-backend/API/Controllers/AiConsentController.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
[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; }
/// <summary>The version of the text the user saw; a stale one is refused so nobody agrees to an old purpose.</summary>
public string Version { get; set; } = "";
}

[HttpGet]
public async Task<IActionResult> 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<IActionResult> 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)!);
}
6 changes: 5 additions & 1 deletion turn-one-backend/API/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,11 @@ public AuthController(

[EnableRateLimiting(RateLimits.Auth)]
[HttpPost("register")]
public async Task<ActionResult<AuthResponseDto>> Register(RegisterDto registerDto)
public async Task<ActionResult<AuthResponseDto>> 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)
Expand Down Expand Up @@ -127,6 +130,7 @@ public async Task<ActionResult<object>> ConfirmEmail([FromQuery] string token)
[HttpPost("forgot-password")]
public async Task<ActionResult> 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" });
Expand Down
25 changes: 25 additions & 0 deletions turn-one-backend/API/Controllers/SimLeaderboardsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,31 @@ public async Task<IActionResult> Validation(Guid lapId)
});
}

/// <summary>Per-lap leaderboard eligibility for a whole session (session page, HF-02/HF-04).</summary>
[HttpGet("sessions/{sessionId:guid}/validations")]
[AllowAnonymous]
public async Task<IActionResult> 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<IActionResult> PersonalBests(string username)
Expand Down
6 changes: 5 additions & 1 deletion turn-one-backend/API/Controllers/SubscriptionController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -30,6 +32,7 @@ public async Task<ActionResult<User>> 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)
Expand All @@ -50,6 +53,7 @@ public async Task<ActionResult<User>> DowngradePlan([FromBody] PlanType newPlan)
{
var userId = GetUserId();
var user = await _subscriptionService.DowngradePlanAsync(userId, newPlan);
_plans.Forget(userId);
return Ok(user);
}
catch (InvalidOperationException ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,10 @@ public async Task InvokeAsync(HttpContext context, TelemetryIngestionService ing
return;
}

var planClaim = principal.FindFirst("Plan")?.Value;
var plan = Enum.TryParse<PlanType>(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<API.Security.PlanLookup>();
var plan = await plans.GetAsync(userId)
?? (Enum.TryParse<PlanType>(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;
Expand Down
6 changes: 6 additions & 0 deletions turn-one-backend/API/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,12 @@
builder.Services.AddScoped<ILapAnalyticsService, LapAnalyticsService>();
builder.Services.AddScoped<IOverlayTokenService, OverlayTokenService>();
builder.Services.AddScoped<IDeviceAuthService, DeviceAuthService>();

// H-12: every request sees the user's current plan, not the one baked into the JWT.
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<API.Security.PlanLookup>();
builder.Services.AddSingleton<API.Security.TurnstileVerifier>();
builder.Services.AddScoped<Microsoft.AspNetCore.Authentication.IClaimsTransformation, API.Security.PlanClaimsTransformation>();
builder.Services.AddScoped<LapUploadService>();
builder.Services.AddScoped<CatalogService>();
builder.Services.AddScoped<SimLeaderboardService>();
Expand Down
83 changes: 83 additions & 0 deletions turn-one-backend/API/Security/PlanClaims.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
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;
}

/// <summary>The current plan, or null when the user doesn't exist (deleted account).</summary>
public async Task<PlanType?> GetAsync(Guid userId)
{
if (_cache.TryGetValue(CacheKey(userId), out PlanType? cached)) return cached;

using var scope = _scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<TurnOneDbContext>();
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;
}

/// <summary>Call after changing a user's plan so the next request sees it immediately.</summary>
public void Forget(Guid userId) => _cache.Remove(CacheKey(userId));

private static string CacheKey(Guid userId) => $"plan:{userId}";
}

/// <summary>
/// Replaces the token's "Plan" claim with <see cref="PlanLookup"/>'s value on every authenticated
/// request, so every existing <c>User.FindFirstValue("Plan")</c> check uses the current plan.
/// </summary>
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<ClaimsPrincipal> 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;
}
}
50 changes: 50 additions & 0 deletions turn-one-backend/API/Security/TurnstileVerifier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System.Text.Json;

namespace API.Security;

/// <summary>
/// H-17 — Cloudflare Turnstile check for sign-up and password reset. With no
/// <c>Turnstile:SecretKey</c> configured (local development) every request passes.
/// </summary>
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<TurnstileVerifier> _logger;

public TurnstileVerifier(IHttpClientFactory http, IConfiguration config, ILogger<TurnstileVerifier> logger)
{
_http = http;
_config = config;
_logger = logger;
}

public bool Enabled => !string.IsNullOrWhiteSpace(_config["Turnstile:SecretKey"]);

public async Task<bool> 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<string, string> { ["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;
}
}
}
3 changes: 3 additions & 0 deletions turn-one-backend/Application/DTOs/RegisterDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ public class RegisterDto
[Required]
[Compare("Password")]
public string ConfirmPassword { get; set; } = string.Empty;

/// <summary>Cloudflare Turnstile response from the sign-up form (H-17); checked when Turnstile is configured.</summary>
public string? TurnstileToken { get; set; }
}
28 changes: 28 additions & 0 deletions turn-one-backend/Domain/Entities/AiConsent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.ComponentModel.DataAnnotations;

namespace Domain.Entities;

/// <summary>
/// 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.
/// </summary>
public class AiConsent
{
/// <summary>Bump when what the data is used for changes; older grants then no longer count.</summary>
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; }
}
Loading
Loading