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
4 changes: 4 additions & 0 deletions .github/instructions/frontend.instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ applyTo: "src/MockAPI/wwwroot/**/*.{js,html,css},tests/{frontend,browser}/**/*.j
- Route management requests through `dashboard-management.js`. Configuration commands pass an explicit captured ETag; editor drafts and confirmations keep their reviewed revision despite live updates. Keep the single-flight guard through the authoritative refresh, surface failures, and never automatically replay rejected writes.
- Consume the synchronizer's explicit completed/failed/inactive refresh result at the command boundary. Background recovery may continue after failure, but a command must not treat a failed or interrupted refresh as successful.
- Serve scripts and styles with private, content-validated caching; keep dashboard HTML and administrative data non-storable. Do not use immutable caching for unversioned asset URLs.
- Keep PWA installation assets under authenticated `/__mockapi/` routes. The root-scoped worker handles
only same-origin GET navigations to `/`, never API, mock, health, or asset requests. Use a generic
reconnect page only on network failure; preserve HTTP errors and never cache administrative content
or queue offline writes. Keep the worker URL stable and its updates revalidated.
- Add JSDoc to every exported function, factory, and reusable exported value. Document parameters, return shapes, callbacks, lifecycle, side effects, thrown errors, and discriminated result variants where applicable.
- Prefer reusable `@typedef` contracts for shared object shapes. Keep annotations specific enough to help editors and reviewers; do not use `Object` when a meaningful shape is known.
- Keep shared endpoint, configuration, management-problem, and statistics wire shapes in `dashboard-core.js`, aligned with the backend's nullable and omitted fields. Keep named controller/lifecycle types in their owning modules and reuse shared contracts rather than duplicating payload shapes.
Expand Down
23 changes: 23 additions & 0 deletions docs/FEATURES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
# Feature Readiness

## Installable dashboard

The MockAPI dashboard is a progressive web app. Open your instance over HTTPS (or loopback HTTP
for development) and use your browser's **Install app** command. On iPhone or iPad, use Safari's
**Share > Add to Home Screen**. Availability and wording depend on the browser and operating system.
Installation opens the same instance in a standalone window; existing administrator authentication
still applies. Each origin identifies a separate installation.
The header displays the current instance's hostname, without protocol, port, or path, in both
browser tabs and installed app windows, including on mobile.

The dashboard requires a live connection. After the first successful visit activates its service
worker, an offline launch shows a generic **Connection unavailable** page with a **Reconnect to
MockAPI** link. It stores no dashboard pages, endpoint definitions, statistics, credentials, or
request/response content in service-worker caches. Offline changes are not supported or queued.
Mock requests, management API calls, event streams, and health probes are never intercepted.
Live server errors and authentication challenges remain unchanged.

The service worker updates through the browser's normal lifecycle; close existing dashboard windows
and reopen after a deployment to activate a waiting update. Browsers without service-worker support,
and non-loopback HTTP deployments, retain the ordinary live dashboard without offline support.
Disabling the dashboard also disables its manifest, icons, and service-worker routes; an already
installed app is not remotely uninstalled.

## Azure Container Apps Express

This matrix tracks the Azure Container Apps features MockAPI currently needs and their availability in the existing Consumption deployment versus Container Apps Express. Express is in preview, and its status is a documentation snapshot as of July 14, 2026. **Available** means the required capability is supported, **Partial** means it is not fully supported, and **In development** means MockAPI must not depend on it in an Express deployment yet.
Expand Down
11 changes: 11 additions & 0 deletions docs/PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,17 @@ Both Automatic and Columns when space allows must fall back to the single-column
command groups wrap; preserve the saved preference when resizing. Cap the endpoint search field
at 220px and align the collapse control with the first filter row when filters wrap.

### Installable dashboard

Offer a web app manifest, local PNG icons, and a standalone launch at `/`. Register a stable,
root-scoped service worker only in secure contexts; it handles only same-origin GET dashboard
navigations at `/`, including query strings. All mock, management, health, and asset requests bypass
the worker. Preserve live HTTP errors and authentication challenges; only a failed network navigation
receives a generic, non-storable reconnect page. Never cache dashboard HTML, endpoint definitions,
statistics, credentials, or request/response content, and never queue or replay offline writes.
Keep all PWA assets under the authenticated, reserved `/__mockapi/` namespace and disable them
with the dashboard. Revalidate the worker on updates rather than using immutable caching.

### Endpoint management

- API-level descriptions are separate from operation descriptions. Use the existing first path segment
Expand Down
11 changes: 9 additions & 2 deletions src/MockAPI/Management/DashboardAssets.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ internal static void Map(
string sourceName,
string contentType,
string version,
bool replaceVersionPlaceholder = false)
bool replaceVersionPlaceholder = false,
string? serviceWorkerScope = null)
{
var bytes = File.ReadAllBytes(Path.Combine(app.Environment.WebRootPath, sourceName));
if (replaceVersionPlaceholder)
Expand All @@ -40,8 +41,14 @@ internal static void Map(
var etag = new EntityTagHeaderValue($"\"{Convert.ToHexString(SHA256.HashData(bytes))}\"");
app.MapGet(route, (HttpContext context) =>
{
if (serviceWorkerScope is not null)
{
// The dashboard lives at /; the worker handles only that navigation, never mock or API traffic.
context.Response.Headers["Service-Worker-Allowed"] = serviceWorkerScope;
}
var requestedVersion = context.Request.Query["v"].ToString();
context.Response.Headers.CacheControl = string.Equals(requestedVersion, version, StringComparison.Ordinal)
context.Response.Headers.CacheControl = serviceWorkerScope is null
&& string.Equals(requestedVersion, version, StringComparison.Ordinal)
? "private, max-age=31536000, immutable"
: "private, no-cache";
return Results.File(bytes, contentType, entityTag: etag);
Expand Down
14 changes: 14 additions & 0 deletions src/MockAPI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@
"dashboard-test-request.js",
"dashboard-tutorial.js",
"favicon.svg",
"manifest.webmanifest",
"service-worker.js",
"icon-192.png",
"icon-512.png",
"openapi-logo.svg"
];
var assetVersion = DashboardAssets.CreateVersion(app.Environment.WebRootPath, dashboardAssetNames);
Expand Down Expand Up @@ -104,6 +108,16 @@
DashboardAssets.Map(app, "/favicon.svg", "favicon.svg", "image/svg+xml", assetVersion);
DashboardAssets.Map(app, "/favicon.ico", "favicon.svg", "image/svg+xml", assetVersion);
DashboardAssets.Map(app, "/brand-mark.svg", "brand-mark.svg", "image/svg+xml", assetVersion);
DashboardAssets.Map(app, "/__mockapi/manifest.webmanifest", "manifest.webmanifest", "application/manifest+json", assetVersion);
DashboardAssets.Map(app, "/__mockapi/icon-192.png", "icon-192.png", "image/png", assetVersion);
DashboardAssets.Map(app, "/__mockapi/icon-512.png", "icon-512.png", "image/png", assetVersion);
DashboardAssets.Map(
app,
"/__mockapi/service-worker.js",
"service-worker.js",
"text/javascript; charset=utf-8",
assetVersion,
serviceWorkerScope: "/");
DashboardAssets.Map(
app,
"/__mockapi/openapi-logo.svg",
Expand Down
9 changes: 6 additions & 3 deletions src/MockAPI/wwwroot/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,11 @@ button:disabled {

/* Page header and configuration commands */
.app-header {
height: 64px;
min-height: 64px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 28px;
padding: 8px 28px;
border-bottom: 1px solid var(--cp-border);
background: var(--cp-bg-elevated);
box-shadow: 0 3px 12px rgba(16, 36, 62, 0.06);
Expand Down Expand Up @@ -213,21 +213,25 @@ button:disabled {
}
.brand-lockup {
display: flex;
min-width: 0;
align-items: center;
gap: 12px;
}
.brand-lockup > div {
display: grid;
min-width: 0;
}
.brand-lockup strong {
font-size: 17px;
}
.brand-lockup span {
color: var(--cp-text-muted);
font-size: 12px;
overflow-wrap: anywhere;
}
.brand-mark {
display: block;
flex-shrink: 0;
width: 42px;
height: 34px;
border-radius: 8px;
Expand Down Expand Up @@ -2698,7 +2702,6 @@ html[data-theme="dark"] button:disabled {
.header-api-security {
margin-right: auto;
}
.brand-lockup > div span,
.connection-status {
display: none;
}
Expand Down
13 changes: 13 additions & 0 deletions src/MockAPI/wwwroot/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const elements = getDashboardElements(document, {
"how-it-works-new-endpoint": "button",
"import-button": "button",
"import-file": "input",
"instance-domain": "span",
"load-example-button": "button",
"save-button": "button",
"settings-button": "button",
Expand All @@ -69,6 +70,8 @@ const elements = getDashboardElements(document, {
"tutorial-title": "h2",
});

elements["instance-domain"].textContent = window.location.hostname;

const API = "/__mockapi/api";
// Access storage inside the store's guarded operations; the localStorage getter itself can throw.
const dashboardPreferencesStore = createDashboardPreferencesStore({
Expand Down Expand Up @@ -696,3 +699,13 @@ pageEvents.listen(window, "pagehide", (event) => {
dashboardSynchronizer.start().then(() => {
tutorialController.startIfNeeded(window.location.search);
});

if (window.isSecureContext && "serviceWorker" in navigator) {
// Keep the worker URL stable so deployments update one registration instead of accumulating workers.
navigator.serviceWorker
.register("/__mockapi/service-worker.js", { scope: "/", updateViaCache: "none" })
.catch((error) => {
console.error("Dashboard offline support could not be registered.", error);
showToast("Dashboard offline support is unavailable. The live dashboard still works.", true);
});
}
Binary file added src/MockAPI/wwwroot/icon-192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/MockAPI/wwwroot/icon-512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 3 additions & 1 deletion src/MockAPI/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
</script>
<title>MockAPI Console</title>
<meta name="theme-color" content="#075ea8" />
<link rel="manifest" href="/__mockapi/manifest.webmanifest" crossorigin="use-credentials" />
<link rel="apple-touch-icon" href="/__mockapi/icon-192.png" />
<link rel="icon" href="/favicon.svg?v={{ASSET_VERSION}}" type="image/svg+xml" />
<link rel="stylesheet" href="/app.css?v={{ASSET_VERSION}}" />
<script src="/app.js?v={{ASSET_VERSION}}" type="module"></script>
Expand All @@ -51,7 +53,7 @@
<img class="brand-mark" src="/brand-mark.svg?v={{ASSET_VERSION}}" alt="" width="42" height="34" />
<div>
<strong>MockAPI</strong>
<span>Operations console</span>
<span id="instance-domain"></span>
</div>
</div>
<div class="header-actions">
Expand Down
26 changes: 26 additions & 0 deletions src/MockAPI/wwwroot/manifest.webmanifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"id": "/",
"name": "MockAPI Console",
"short_name": "MockAPI",
"description": "Manage and test this MockAPI instance.",
"lang": "en",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#f4f9ff",
"theme_color": "#075ea8",
"icons": [
{
"src": "/__mockapi/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/__mockapi/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
}
]
}
60 changes: 60 additions & 0 deletions src/MockAPI/wwwroot/service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"use strict";

// Embed only a generic reconnect page. Never store dashboard HTML, credentials, definitions, or responses.
const offlineHtml = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#075ea8">
<title>MockAPI - Connection unavailable</title>
<style>
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; }
main { max-width: 32rem; padding: 2rem; }
p { line-height: 1.6; }
a { display: inline-block; padding: .8rem 1.2rem; background: #075ea8; color: white; border-radius: .4rem; }
a:focus-visible { outline: 3px solid currentColor; outline-offset: 4px; }
</style>
</head>
<body>
<main>
<h1>Connection unavailable</h1>
<p>MockAPI needs a connection to this instance. Check your network and that the server is running, then try again.</p>
<p>No endpoint data is available offline. Changes are not queued or replayed.</p>
<a href="/">Reconnect to MockAPI</a>
</main>
</body>
</html>`;

self.addEventListener("activate", (event) => {
event.waitUntil(self.clients.claim());
});

self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
// Root scope is necessary for the dashboard, but all mock, management, and health requests bypass us.
if (
event.request.method !== "GET" ||
event.request.mode !== "navigate" ||
url.origin !== self.location.origin ||
url.pathname !== "/"
) {
return;
}

event.respondWith(
fetch(event.request, { cache: "no-store" }).catch(
() =>
new Response(offlineHtml, {
status: 503,
headers: {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
"Content-Security-Policy":
"default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
},
})
)
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ public async Task EventStreams_AuthenticateBeforeOpeningStream(string path)
[InlineData("/favicon.ico")]
[InlineData("/favicon.svg")]
[InlineData("/__mockapi/openapi-logo.svg")]
[InlineData("/__mockapi/manifest.webmanifest")]
[InlineData("/__mockapi/service-worker.js")]
[InlineData("/__mockapi/icon-192.png")]
[InlineData("/__mockapi/icon-512.png")]
[InlineData("/dashboard-core.js")]
[InlineData("/dashboard-dom.js")]
[InlineData("/dashboard-editor-dialog.js")]
Expand Down
36 changes: 36 additions & 0 deletions tests/MockAPI.Tests/Management/DashboardOptimizationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using MockAPI.Configuration;
Expand All @@ -26,6 +27,10 @@ public sealed class DashboardOptimizationTests
[InlineData("/dashboard-layout.js")]
[InlineData("/dashboard-statistics.js")]
[InlineData("/dashboard-test-blade.js")]
[InlineData("/__mockapi/manifest.webmanifest")]
[InlineData("/__mockapi/service-worker.js")]
[InlineData("/__mockapi/icon-192.png")]
[InlineData("/__mockapi/icon-512.png")]
public async Task UnversionedAssets_RevalidateWithContentETagsAndNeverUseSharedCaching(string path)
{
await using var factory = new WebApplicationFactory<Program>();
Expand Down Expand Up @@ -95,6 +100,37 @@ public async Task VersionedAssets_UseOneContentVersionAndPrivateImmutableCaching
Assert.Equal("no-cache, private", stale.Headers.CacheControl!.ToString());
}

[Fact]
public async Task ServiceWorker_AllowsRootScopeAndRevalidatesEvenWithAVersionQuery()
{
await using var factory = new WebApplicationFactory<Program>();
using var client = factory.CreateClient();
var html = await client.GetStringAsync("/");
var version = Regex.Match(html, "/app\\.css\\?v=([A-F0-9]{64})").Groups[1].Value;
using var response = await client.GetAsync($"/__mockapi/service-worker.js?v={version}");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("/", Assert.Single(response.Headers.GetValues("Service-Worker-Allowed")));
Assert.True(response.Headers.CacheControl!.NoCache);
Assert.True(response.Headers.CacheControl.Private);
Assert.Equal("text/javascript", response.Content.Headers.ContentType!.MediaType);
using var manifest = await client.GetAsync("/__mockapi/manifest.webmanifest");
Assert.Equal("application/manifest+json", manifest.Content.Headers.ContentType!.MediaType);
}

[Theory]
[InlineData("/__mockapi/manifest.webmanifest")]
[InlineData("/__mockapi/service-worker.js")]
[InlineData("/__mockapi/icon-192.png")]
[InlineData("/__mockapi/icon-512.png")]
public async Task DisabledDashboard_DoesNotExposePwaAssets(string path)
{
await using var factory = new UnsecuredApplicationFactory().WithWebHostBuilder(builder =>
builder.UseSetting("MockApi:EnableDashboard", "false"));
using var client = factory.CreateClient();
using var response = await client.GetAsync(path);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

private static void AssertVersionedCacheControl(CacheControlHeaderValue? cacheControl)
{
Assert.NotNull(cacheControl);
Expand Down
1 change: 1 addition & 0 deletions tests/NativePublication.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,5 @@ try {
finally {
Remove-Item -LiteralPath $publicationFixture -Recurse -Force
}

Write-Host 'Native publication and release workflow contract tests passed.'
Loading