Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
758 lines (694 loc) · 29.6 KB
/
Copy pathProgram.cs
File metadata and controls
758 lines (694 loc) · 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
using System.Security.Claims;
using System.Text.Json;
using HomeAssistantAcDefender.Models;
using HomeAssistantAcDefender.Options;
using HomeAssistantAcDefender.Components;
using HomeAssistantAcDefender.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.HostFiltering;
using MudBlazor.Services;
var builder = WebApplication.CreateBuilder(args);
// Forwarded headers are opt-in and fail closed. A proxy can only influence the
// request scheme when its exact address or CIDR is configured in
// ForwardedHeaders__KnownProxies / ForwardedHeaders__KnownIPNetworks. An empty
// contract deliberately ignores forwarded headers instead of trusting a
// caller-supplied X-Forwarded-Proto value.
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.None;
options.KnownProxies.Clear();
options.KnownIPNetworks.Clear();
var configuredProxies = builder.Configuration["ForwardedHeaders:KnownProxies"];
var configuredNetworks = builder.Configuration["ForwardedHeaders:KnownIPNetworks"]
?? builder.Configuration["ForwardedHeaders:KnownNetworks"];
foreach (var address in HomeAssistantConfigurationValidator.ValidateKnownProxies(configuredProxies))
{
options.KnownProxies.Add(address);
}
foreach (var network in HomeAssistantConfigurationValidator.ValidateKnownNetworks(configuredNetworks))
{
options.KnownIPNetworks.Add(network);
}
if (options.KnownProxies.Count > 0 || options.KnownIPNetworks.Count > 0)
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.ForwardLimit = 1;
}
});
builder.Services.Configure<HostFilteringOptions>(options =>
{
options.AllowedHosts = HomeAssistantConfigurationValidator
.ValidateAllowedHosts(builder.Configuration["ForwardedHeaders:AllowedHosts"])
.ToArray();
});
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
if (args.Any(argument => string.Equals(argument, "--validate-deployment-contract", StringComparison.OrdinalIgnoreCase)))
{
HomeAssistantConfigurationValidator.RunNegativeRegression();
return;
}
if (args.Any(argument => string.Equals(argument, "--validate-cli-contract", StringComparison.OrdinalIgnoreCase)))
{
CliCommands.RunContractRegression();
return;
}
if (await CliCommands.TryRunAsync(args, builder.Configuration))
{
return;
}
builder.Services.AddOptions<HomeAssistantOptions>()
.Bind(builder.Configuration.GetSection(HomeAssistantOptions.SectionName))
.Validate(options =>
{
HomeAssistantConfigurationValidator.ValidateBaseUrl(
options.BaseUrl,
options.AllowInsecurePrivateNetworkHttp);
return true;
}, "HomeAssistant:BaseUrl is not a permitted HTTP(S) endpoint.")
.ValidateOnStart();
builder.Services.Configure<DefenderOptions>(builder.Configuration.GetSection(DefenderOptions.SectionName));
builder.Services.Configure<KioskOptions>(builder.Configuration.GetSection(KioskOptions.SectionName));
builder.Services.AddTransient<SetupReadOnlyHandler>();
builder.Services.AddHttpClient<SetupValidationService>(client => client.Timeout = TimeSpan.FromSeconds(15))
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false })
.AddHttpMessageHandler<SetupReadOnlyHandler>();
builder.Services.AddSingleton<SettingsGitRepository>();
builder.Services.AddSingleton<NotificationHistoryStore>();
builder.Services.AddSingleton<NotificationExportService>();
builder.Services.AddSingleton<SettingsRepositoryHistoryExportService>();
builder.Services.AddSingleton<WikiContentService>();
builder.Services.AddSingleton<DefenderStateStore>();
builder.Services.AddSingleton<AcDefenderService>();
builder.Services.AddSingleton<TwoFactorAuth>();
builder.Services.AddSingleton<GoogleDeviceLogin>();
builder.Services.AddSingleton<SdmCameraService>();
builder.Services.AddSingleton<HomeAssistantTokenStore>();
builder.Services.AddHttpClient<HomeAssistantClient>(client => client.Timeout = TimeSpan.FromSeconds(15));
builder.Services.AddHttpClient<OpenMeteoWeatherClient>(client => client.Timeout = TimeSpan.FromSeconds(15));
builder.Services.AddHostedService<AcDefenderWorker>();
builder.Services.AddHostedService<HubKioskService>();
builder.Services.AddHostedService<WakeTruceService>();
builder.Services.AddScoped<DefenderStateProvider>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddMudServices(configuration =>
{
// The same persistent thermostat outcome is deduplicated. Keep normal snackbar capacity so a
// command failure never hides a separate cooling alarm on a narrow wall-mounted display.
configuration.SnackbarConfiguration.PositionClass = "mud-snackbar-location-bottom-right";
configuration.SnackbarConfiguration.PreventDuplicates = true;
configuration.SnackbarConfiguration.ShowCloseIcon = true;
});
// Persist the DataProtection key ring under App_Data (a docker volume in production) so container
// rebuilds do NOT invalidate auth cookies and antiforgery tokens. Without this every redeploy
// signed everyone out and left open tabs with dead circuits — "the site stopped working".
var dataProtectionKeysPath = Path.Combine(builder.Environment.ContentRootPath, "App_Data", "dataprotection-keys");
Directory.CreateDirectory(dataProtectionKeysPath);
builder.Services.AddDataProtection()
.SetApplicationName("HomeAssistantAcDefender")
.PersistKeysToFileSystem(new DirectoryInfo(dataProtectionKeysPath));
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/logout";
options.AccessDeniedPath = "/login";
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.SlidingExpiration = true;
options.Cookie.Name = "AC_Defender_Auth";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.SameSite = SameSiteMode.Lax;
});
builder.Services.AddAuthorization();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler(errorApp => errorApp.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync(
"<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>AC Defender error</title></head>"
+ "<body style=\"font-family:'Segoe UI',Arial,sans-serif;padding:48px;background:#0f1614;color:#e7f6ef\">"
+ "<h1>Something went wrong</h1>"
+ "<p>The web request failed, but the background defender keeps reading and protecting the thermostat.</p>"
+ "<p><a href=\"/\" style=\"color:#46c1a7\">Return to the dashboard</a></p>"
+ "</body></html>");
}));
}
app.UseForwardedHeaders();
app.UseHostFiltering();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
// Serve the Site Wiki's images (docs/wiki/images/**) at /wikimedia. Rendered wiki HTML rewrites
// "images/..." paths here. Same public content as GitHub Pages, so no auth gate is needed.
var wikiImages = Path.Combine(app.Environment.ContentRootPath, "docs", "wiki", "images");
if (Directory.Exists(wikiImages))
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(wikiImages),
RequestPath = WikiContentService.ImagesRequestPath,
});
}
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.WithStaticAssets();
app.MapGet("/logout", async (HttpContext context) =>
{
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
context.Response.Redirect("/login");
});
// Anonymous, intentionally low-detail health response for Compose/load-balancer
// checks. It contains no Home Assistant configuration, account state, or
// thermostat readings. APP_VERSION and APP_REVISION are release metadata only.
app.MapGet("/healthz", (HttpContext context, IConfiguration configuration) => Results.Ok(new
{
status = "ok",
version = configuration["APP_VERSION"] ?? "unknown",
revision = configuration["APP_REVISION"] ?? "unknown",
buildTimeUtc = PresentationBuildInfo.TimestampUtc,
scheme = context.Request.Scheme,
})).AllowAnonymous();
// Every /api/* endpoint requires an authenticated session. The Blazor UI reads state
// server-side via DefenderStateProvider (not these endpoints), so locking them down does
// not affect the dashboard. It does stop an unauthenticated visitor from reading the whole
// defender state (which names every stealth/camouflage guard) or controlling the thermostat.
var api = app.MapGroup("/api").RequireAuthorization();
api.MapGet("/status", (DefenderStateStore store) => Results.Ok(store.GetSnapshot()));
api.MapGet("/settings", (DefenderStateStore store) => Results.Ok(store.GetSnapshot()));
api.MapGet("/notifications", (
int? limit,
bool? includeDismissed,
string? level,
string? from,
string? to,
string? actions,
NotificationHistoryStore notifications) =>
{
DateTimeOffset? fromInclusive = null;
DateTimeOffset? toExclusive = null;
if (!string.IsNullOrWhiteSpace(from))
{
if (!DateTimeOffset.TryParse(from, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out var parsedFrom))
{
return Results.BadRequest(new { error = "from must be an ISO-8601 timestamp or YYYY-MM-DD date." });
}
fromInclusive = parsedFrom;
}
if (!string.IsNullOrWhiteSpace(to))
{
if (to.Length == 10 && DateOnly.TryParseExact(to, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var parsedDate))
{
toExclusive = new DateTimeOffset(parsedDate.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc));
}
else if (DateTimeOffset.TryParse(to, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out var parsedTo))
{
toExclusive = parsedTo;
}
else
{
return Results.BadRequest(new { error = "to must be an ISO-8601 timestamp or YYYY-MM-DD date." });
}
}
if (fromInclusive is not null && toExclusive is not null && toExclusive <= fromInclusive)
{
return Results.BadRequest(new { error = "to must be after from." });
}
var actionFilter = string.IsNullOrWhiteSpace(actions)
? null
: actions.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
if (actionFilter is not null && actionFilter.Any(action => !NotificationHistoryStore.ActionKinds.Contains(action, StringComparer.OrdinalIgnoreCase)))
{
return Results.BadRequest(new { error = "actions accepts only created, read, dismissed, and restored." });
}
return Results.Ok(notifications.GetSnapshot(limit ?? 100, includeDismissed ?? false, level, fromInclusive, toExclusive, actionFilter));
});
api.MapPost("/notifications/{id:guid}/read", (Guid id, NotificationHistoryStore notifications) =>
notifications.MarkRead(id)
? Results.Ok(notifications.GetSnapshot(includeDismissed: true))
: Results.NotFound(new { error = "Notification was not found or could not be updated." }));
api.MapPost("/notifications/{id:guid}/dismiss", (Guid id, NotificationHistoryStore notifications) =>
notifications.Dismiss(id)
? Results.Ok(notifications.GetSnapshot(includeDismissed: true))
: Results.NotFound(new { error = "Notification was not found or could not be dismissed." }));
api.MapPost("/notifications/{id:guid}/restore", (Guid id, NotificationHistoryStore notifications) =>
notifications.Restore(id)
? Results.Ok(notifications.GetSnapshot(includeDismissed: true))
: Results.NotFound(new { error = "Notification was not found or could not be restored." }));
api.MapGet("/usage/live", async (HomeAssistantClient homeAssistantClient, CancellationToken cancellationToken) =>
{
try
{
return Results.Ok(await homeAssistantClient.GetLiveUsageAsync(cancellationToken));
}
catch (Exception ex)
{
return Results.BadRequest(new { error = ex.Message });
}
});
api.MapGet("/usage/alectra-hui", async (HomeAssistantClient homeAssistantClient, CancellationToken cancellationToken) =>
{
try
{
return Results.Ok(await homeAssistantClient.GetAlectraHuiEntitiesAsync(cancellationToken));
}
catch (Exception ex)
{
return Results.BadRequest(new { error = ex.Message });
}
});
api.MapGet("/usage/history", async (
string? entityId,
DateTimeOffset? from,
DateTimeOffset? to,
double? hours,
HomeAssistantClient homeAssistantClient,
CancellationToken cancellationToken) =>
{
try
{
var end = to ?? DateTimeOffset.UtcNow;
var start = from ?? end.AddHours(-Math.Max(0.1, hours ?? 24));
return Results.Ok(await homeAssistantClient.GetUsageHistoryAsync(entityId, start, end, cancellationToken));
}
catch (Exception ex)
{
return Results.BadRequest(new { error = ex.Message });
}
});
api.MapGet("/status/stream", async (HttpContext context, DefenderStateStore store, CancellationToken cancellationToken) =>
{
context.Response.Headers.CacheControl = "no-cache";
context.Response.Headers.Connection = "keep-alive";
context.Response.ContentType = "text/event-stream";
while (!cancellationToken.IsCancellationRequested)
{
var json = JsonSerializer.Serialize(store.GetSnapshot(), new JsonSerializerOptions(JsonSerializerDefaults.Web));
await context.Response.WriteAsync($"data: {json}\n\n", cancellationToken);
await context.Response.Body.FlushAsync(cancellationToken);
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
});
// Front-door camera: exchange the browser's WebRTC offer for Google's answer. Auth-gated with
// the rest of /api, so the stream is only reachable by signed-in household members.
api.MapPost("/camera/webrtc", async (CameraWebRtcRequest request, SdmCameraService camera) =>
{
if (!camera.Enabled)
{
return Results.Json(new { error = "camera bridge is not configured" }, statusCode: 503);
}
var answer = await camera.GenerateWebRtcAnswerAsync(request.OfferSdp ?? "");
return answer is null
? Results.Json(new { error = "stream negotiation failed" }, statusCode: 502)
: Results.Json(new { answerSdp = answer });
});
api.MapPost("/target/generate", async (DefenderStateStore store, AcDefenderService defender, CancellationToken cancellationToken) =>
{
var gate = store.TryBeginWebsiteCommand("generate target", bypassDebounce: true);
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
var snapshot = await defender.GenerateTargetAsync(cancellationToken);
return Results.Ok(snapshot);
});
api.MapPost("/target", async (TargetTemperatureRequest request, DefenderStateStore store, AcDefenderService defender, CancellationToken cancellationToken) =>
{
var gate = store.TryBeginWebsiteCommand("set target", bypassDebounce: true);
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
var snapshot = await defender.SetTargetAsync(request.TemperatureCelsius, cancellationToken);
return Results.Ok(snapshot);
});
api.MapPost("/defender", async (DefenderEnabledRequest request, DefenderStateStore store, AcDefenderService defender, CancellationToken cancellationToken) =>
{
var gate = store.TryBeginWebsiteCommand(request.Enabled ? "turn defender on" : "pause defender", bypassDebounce: true);
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
DefenderSnapshot snapshot;
try
{
snapshot = await defender.SetDefenderEnabledAsync(request.Enabled, cancellationToken);
}
catch (ThermostatOperationSupersededException ex)
{
return Results.Conflict(new { error = ex.Message, snapshot = store.GetSnapshot() });
}
if (!request.Enabled)
{
try
{
await defender.ParkThermostatForStandDownAsync(cancellationToken);
snapshot = store.GetSnapshot();
}
catch
{
// Parking is best-effort.
}
}
return Results.Ok(snapshot);
});
api.MapPost("/settings", async (SettingsRequest request, DefenderStateStore store, AcDefenderService defender, CancellationToken cancellationToken) =>
{
var gate = store.TryBeginWebsiteCommand("save settings", bypassDebounce: true);
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
var snapshot = await defender.UpdateSettingsAsync(request, cancellationToken);
return Results.Ok(snapshot);
});
api.MapPost("/thermostat/refresh", async (AcDefenderService defender, DefenderStateStore store, CancellationToken cancellationToken) =>
{
try
{
var gate = store.TryBeginWebsiteCommand("refresh thermostat", bypassDebounce: true);
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
await defender.RefreshRealThermostatAsync(cancellationToken);
return Results.Ok(store.GetSnapshot());
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return Results.StatusCode(499);
}
catch (HttpRequestException ex) when (ex.StatusCode is not null)
{
store.RecordHomeAssistantRequestRejected(
$"Home Assistant rejected the thermostat refresh ({(int)ex.StatusCode.Value}): {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
catch (Exception ex)
{
store.RecordHomeAssistantUnavailable($"Home Assistant error: {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
});
api.MapPost("/thermostat/force-target", async (AcDefenderService defender, DefenderStateStore store, CancellationToken cancellationToken) =>
{
try
{
var gate = store.TryBeginWebsiteCommand("force exact target");
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
await defender.ForceTargetAsync(cancellationToken);
return Results.Ok(store.GetSnapshot());
}
catch (ThermostatOperationSupersededException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (ThermostatCommandRetryDeferredException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return Results.StatusCode(499);
}
catch (ThermostatCommandRejectedException)
{
return Results.BadRequest(store.GetSnapshot());
}
catch (HttpRequestException ex) when (ex.StatusCode is not null)
{
store.RecordHomeAssistantRequestRejected(
$"Home Assistant rejected the thermostat request ({(int)ex.StatusCode.Value}): {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
catch (Exception ex)
{
store.RecordHomeAssistantUnavailable($"Home Assistant error: {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
});
api.MapPost("/thermostat/force-boost", async (AcDefenderService defender, DefenderStateStore store, CancellationToken cancellationToken) =>
{
try
{
var gate = store.TryBeginWebsiteCommand("force cooling");
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
await defender.ForceCoolingBoostAsync(cancellationToken);
return Results.Ok(store.GetSnapshot());
}
catch (ThermostatOperationSupersededException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (ThermostatCommandRetryDeferredException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return Results.StatusCode(499);
}
catch (ThermostatCommandRejectedException)
{
return Results.BadRequest(store.GetSnapshot());
}
catch (HttpRequestException ex) when (ex.StatusCode is not null)
{
store.RecordHomeAssistantRequestRejected(
$"Home Assistant rejected the thermostat request ({(int)ex.StatusCode.Value}): {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
catch (Exception ex)
{
store.RecordHomeAssistantUnavailable($"Home Assistant error: {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
});
api.MapPost("/thermostat/fan", async (FanModeRequest request, AcDefenderService defender, DefenderStateStore store, CancellationToken cancellationToken) =>
{
try
{
var gate = store.TryBeginWebsiteCommand($"set fan to {request.FanMode}");
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
await defender.ForceFanModeAsync(request.FanMode, cancellationToken);
return Results.Ok(store.GetSnapshot());
}
catch (ThermostatOperationSupersededException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (ThermostatCommandRetryDeferredException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return Results.StatusCode(499);
}
catch (ThermostatCommandRejectedException)
{
return Results.BadRequest(store.GetSnapshot());
}
catch (HttpRequestException ex) when (ex.StatusCode is not null)
{
store.RecordHomeAssistantRequestRejected(
$"Home Assistant rejected the thermostat request ({(int)ex.StatusCode.Value}): {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
catch (Exception ex)
{
store.RecordHomeAssistantUnavailable($"Home Assistant error: {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
});
api.MapPost("/thermostat/off", async (AcDefenderService defender, DefenderStateStore store, CancellationToken cancellationToken) =>
{
try
{
var gate = store.TryBeginWebsiteCommand("turn thermostat off");
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
await defender.TurnThermostatOffAsync(cancellationToken);
return Results.Ok(store.GetSnapshot());
}
catch (ThermostatOperationSupersededException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (ThermostatCommandRetryDeferredException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return Results.StatusCode(499);
}
catch (ThermostatCommandRejectedException)
{
return Results.BadRequest(store.GetSnapshot());
}
catch (HttpRequestException ex) when (ex.StatusCode is not null)
{
store.RecordHomeAssistantRequestRejected(
$"Home Assistant rejected the thermostat request ({(int)ex.StatusCode.Value}): {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
catch (Exception ex)
{
store.RecordHomeAssistantUnavailable($"Home Assistant error: {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
});
api.MapPost("/learn-history", async (AcDefenderService defender, CancellationToken cancellationToken) =>
{
try
{
return Results.Ok(await defender.LearnFromHistoryAsync(cancellationToken));
}
catch (Exception ex)
{
return Results.BadRequest(new { error = ex.Message });
}
});
api.MapPost("/emergency", async (EmergencyProtocolRequest request, AcDefenderService defender, DefenderStateStore store, CancellationToken cancellationToken) =>
{
try
{
var emergencyChangesThermostat = string.Equals(request.Protocol, "too-cold", StringComparison.OrdinalIgnoreCase);
var gate = store.TryBeginWebsiteCommand($"emergency {request.Protocol}", bypassDebounce: !emergencyChangesThermostat);
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
await defender.ApplyEmergencyProtocolAsync(request.Protocol, cancellationToken);
return Results.Ok(store.GetSnapshot());
}
catch (ThermostatOperationSupersededException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (ThermostatCommandRetryDeferredException)
{
return Results.Conflict(store.GetSnapshot());
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return Results.StatusCode(499);
}
catch (ThermostatCommandRejectedException)
{
return Results.BadRequest(store.GetSnapshot());
}
catch (HttpRequestException ex) when (ex.StatusCode is not null)
{
store.RecordHomeAssistantRequestRejected(
$"Home Assistant rejected the thermostat request ({(int)ex.StatusCode.Value}): {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
catch (Exception ex)
{
store.RecordHomeAssistantUnavailable($"Home Assistant error: {ex.Message}");
return Results.BadRequest(store.GetSnapshot());
}
});
// Siesta (mess hall): start = thermostat-affecting (parks or turns the unit off once), so it
// takes the non-bypass debounce gate like /thermostat/off; cancel only clears a hold.
api.MapPost("/siesta", async (SiestaRequest request, DefenderStateStore store, AcDefenderService defender, CancellationToken cancellationToken) =>
{
if (string.Equals(request.Action, "start", StringComparison.OrdinalIgnoreCase))
{
var gate = store.TryBeginWebsiteCommand("start siesta");
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
(bool Started, string Message) start;
try
{
start = await defender.StartSiestaAsync(request.Minutes ?? 60, "manual", cancellationToken);
}
catch (ThermostatOperationSupersededException ex)
{
return Results.Conflict(new { error = ex.Message });
}
return start.Started
? Results.Ok(store.GetSnapshot())
: Results.BadRequest(new { error = start.Message });
}
if (string.Equals(request.Action, "cancel", StringComparison.OrdinalIgnoreCase))
{
var gate = store.TryBeginWebsiteCommand("cancel siesta", bypassDebounce: true);
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
(bool Cancelled, string Message) cancel;
try
{
cancel = await defender.CancelSiestaAsync("website", cancellationToken);
}
catch (ThermostatOperationSupersededException ex)
{
return Results.Conflict(new { error = ex.Message });
}
return cancel.Cancelled
? Results.Ok(store.GetSnapshot())
: Results.BadRequest(new { error = cancel.Message });
}
return Results.BadRequest(new { error = "action must be start or cancel" });
});
// Reactor power: spend rations to summon the WinForge reactor's AI operator (1 ration = 1 h).
// Redemption stays auth-gated; it moves no money and touches no thermostat, so it bypasses the
// thermostat debounce.
api.MapPost("/reactor-power", (ReactorPowerRequest request, DefenderStateStore store) =>
{
var gate = store.TryBeginWebsiteCommand("summon reactor operator", bypassDebounce: true);
if (!gate.Accepted)
{
return Results.Json(gate.Snapshot, statusCode: StatusCodes.Status429TooManyRequests);
}
return store.TryRedeemReactorPower(request.Hours, out var message)
? Results.Ok(store.GetSnapshot())
: Results.BadRequest(new { error = message });
});
// The PUBLIC reactor-power voucher for WinForge Web's poller: active flag + expiry only — no
// balances, no defender state. Deliberately outside the auth group (harmless LAN read) with an
// open CORS header so the Tauri/browser frontend can fetch it cross-origin.
app.MapGet("/api/reactor-power", (HttpContext context, DefenderStateStore store) =>
{
context.Response.Headers.AccessControlAllowOrigin = "*";
var (active, until) = store.GetReactorPowerVoucher();
return Results.Ok(new
{
active,
until,
secondsRemaining = active && until is { } u ? (int)Math.Max(0, (u - DateTimeOffset.UtcNow).TotalSeconds) : 0,
mode = "ai-operator",
});
}).AllowAnonymous();
app.Run();