diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..828c4bd
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,17 @@
+.git
+.github
+.dart_tool
+build
+android
+ios
+macos
+linux
+windows
+docs
+test
+backend.Tests
+backend/bin
+backend/obj
+backend/wwwroot
+**/bin
+**/obj
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..cbbb0eb
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,33 @@
+name: Bug report
+description: Something does not work, looks wrong, or is confusing
+labels: [bug]
+body:
+ - type: textarea
+ id: what
+ attributes:
+ label: What happened
+ description: What you did, what you expected, and what you saw instead.
+ validations:
+ required: true
+ - type: dropdown
+ id: where
+ attributes:
+ label: Where
+ options:
+ - Phone layout
+ - Printer panel layout
+ - Administrator screen
+ - Sign-in
+ - Server or API
+ - Hosting
+ validations:
+ required: true
+ - type: input
+ id: setup
+ attributes:
+ label: Device, browser and text size
+ placeholder: "Phone, Chrome, text size larger than normal"
+ - type: textarea
+ id: shot
+ attributes:
+ label: Screenshot or message shown
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..43b0abb
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,5 @@
+blank_issues_enabled: false
+contact_links:
+ - name: Report a security problem privately
+ url: https://github.com/Hikki-dev/pull_printing_app/security/advisories/new
+ about: Please do not open a public issue for security problems.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..50849d8
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,15 @@
+name: Idea or improvement
+description: Something that would make the demo or the product better
+labels: [enhancement]
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: What problem would this solve, and for whom
+ description: Describe the person and the moment, not the solution.
+ validations:
+ required: true
+ - type: textarea
+ id: idea
+ attributes:
+ label: What you have in mind
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..fd17276
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,21 @@
+## What this changes
+
+
+
+## How it was checked
+
+
+
+- [ ] `dotnet test backend.Tests`
+- [ ] `flutter analyze --no-fatal-infos` and `flutter test`
+- [ ] Tried it in a browser or on a device
+
+## Not checked
+
+
+
+## Checklist
+
+- [ ] Rules about who may do what are enforced by the server, with a test
+- [ ] New or changed screens work at 1.5 and 2 times text size
+- [ ] Docs in `docs/` and `CHANGELOG.md` updated if behaviour changed
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..07dbe21
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,44 @@
+name: CI
+
+on:
+ push:
+ pull_request:
+
+jobs:
+ backend:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+ - run: dotnet test backend.Tests
+
+ frontend:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: subosito/flutter-action@v2
+ with:
+ channel: stable
+ - run: flutter pub get
+ - run: flutter analyze --no-fatal-infos
+ - run: flutter test
+
+ docker:
+ # Builds the image the way a host would, then starts it and checks it answers.
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: docker build -t pull-print-demo .
+ - name: Start the image and check it
+ run: |
+ docker run -d --name pp -p 8080:8080 pull-print-demo
+ for i in $(seq 1 30); do curl -fs http://localhost:8080/healthz && break; sleep 2; done
+ curl -fs http://localhost:8080/healthz
+ curl -fs http://localhost:8080/ | grep -q "Pull Print demo"
+ curl -fs -X POST -H 'content-type: application/json' -d '{"admin":false}' \
+ http://localhost:8080/api/auth/demo-login | grep -q '"token"'
+ test "$(curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/api/jobs/held)" = "401"
+ - if: failure()
+ run: docker logs pp
diff --git a/.gitignore b/.gitignore
index 79c113f..785a3fe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,3 +43,8 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release
+
+# .NET
+**/bin/
+**/obj/
+backend/wwwroot/
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..702f0c9
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,43 @@
+# Changelog
+
+All notable changes. Newest first.
+
+## Unreleased (pull request #1)
+
+### Added
+- **Work-account sign-in.** People sign in with their Microsoft 365 or Google Workspace account. The server does the sign-in, only lets in people from your organisation, adds them on first sign-in, and decides who is an administrator.
+- **Printers and quotas managed on the server.** Administrators add, switch off and remove printers, set pages a month for new people, for everyone or for one person, and see a setup check that names anything still to do. Pages start again each month.
+- A printer picker on the phone, and printer panels fixed to one printer by their address (`?printer=`).
+- `docs/09-connecting-your-workspace.md`: the ten-minute setup for Microsoft and Google.
+- A new README and guides with pictures of every screen taken from the running app (`docs/Getting%20started.md`, `docs/Fixing%20problems.md`), two diagrams, a short demo GIF, and `tools/screenshots/` to make them again.
+- Phone and printer-panel screens: sign in, choose documents, print, confirmation, administrator view.
+- A working .NET 8 backend with protected routes, quota checks on the server, and private demo sandboxes.
+- Demo banner and "What is this?" dialog on every screen, sample documents on demand, and **Start over**.
+- Select all and Clear, plain messages for a long document and for no pages left, partial-print notice.
+- The printer panel signs out after 60 seconds without a touch.
+- Static hosting on Vercel (`vercel.json`, `scripts/vercel-build.sh`) and a `Dockerfile` and `render.yaml` for the full stack.
+- A branded loading screen, page title, description, icons and manifest for the web build.
+- Design documents, mockups, an architecture and API reference, and a review record in `docs/`.
+- CI for the backend, the app, and the Docker image.
+- 112 backend tests and 64 app tests, including a simulated Microsoft/Google sign-in.
+
+### Changed
+- `PullPrintingBackend.csproj` is no longer empty; the backend builds.
+- Routes match what the app calls. `POST /api/jobs/release` takes `jobIds` and returns what really printed.
+- The app uses the server's answer about what printed, and refreshes a stale list.
+
+### Fixed
+- Sign in button pushed off screen at large text sizes and on short phones.
+- Overflows at 1.5 and 2 times text size.
+- A demo administrator could see every visitor's documents.
+- Unexpected server errors, missing security headers, and unbounded request sizes.
+
+### Removed
+- The MSAL wrapper (`msal_flutter`, `MsAuthService.dart`) and the `AUTH_MODE` and `MS_SCOPE` build settings. Sign-in no longer needs anything in the app.
+- The `AzureAd__*` settings, replaced by `Workspace__*`. `Demo__SigningKey` is now `Auth__SigningKey` (the old name still works).
+- Windows-only printing code (`System.Printing`), replaced by `IPrintDispatcher` with a simulated implementation.
+- The mock JSON server data (`frontend/db.json`).
+
+## Before this
+
+An early prototype: screens and an API shape that were not connected, and a backend that did not build.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..9a01518
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,46 @@
+# Contributing
+
+Thanks for helping. This is a small project, so the process is light.
+
+## Get set up
+
+You need the [Flutter SDK](https://docs.flutter.dev/get-started/install) and the [.NET 8 SDK](https://dotnet.microsoft.com/download).
+
+```bash
+flutter pub get
+flutter run -t frontend/lib/main.dart # the app on built-in sample data
+
+dotnet run --project backend # the API (ASPNETCORE_ENVIRONMENT=Development turns demo sign-in on)
+```
+
+The README has the full list of ways to run it, and [`docs/How%20it%20works.md`](docs/How%20it%20works.md) explains how the pieces fit.
+
+## Before you open a pull request
+
+Run what CI runs:
+
+```bash
+dotnet test backend.Tests
+flutter analyze --no-fatal-infos
+flutter test
+```
+
+There are 64 app tests and 112 backend tests.
+
+- **Add a test with every behaviour change.** Server rules go in `backend.Tests`; screens and the API client go in `test/`.
+- **Check large text.** `test/widget_test.dart` runs the phone screens at 1.5 and 2 times text size and fails on any overflow. New screens should be added there.
+- **Keep the server in charge.** The app only shows things; any rule about who may do what belongs in the backend, with a test.
+- **Match the style around you.** Run `dart format` on Flutter code you touch.
+- **Wording is part of the design.** Use the plain words in [`docs/03-screen-specs.md`](docs/03-screen-specs.md#wording), and keep messages saying what to do next.
+- **No stock or generated imagery, no emoji.** See [`docs/04-design-guidelines.md`](docs/04-design-guidelines.md).
+
+## Pull requests
+
+- One change per pull request, with a description that says what changed, why, and how you checked it.
+- Say what you did **not** check.
+- Update the docs in `docs/` and `CHANGELOG.md` when behaviour changes.
+- If a screen changed, take its pictures again: [`tools/screenshots`](tools/screenshots/README.md) explains how. Pictures come from the running app, never from a mock-up.
+
+## Reporting problems
+
+Use the issue templates. For anything security related, read [SECURITY.md](SECURITY.md) first.
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..b6b828d
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,31 @@
+# One image that serves both the web app and the API, for a free demo host.
+# Build: docker build -t pull-print-demo .
+# Run: docker run -p 8080:8080 pull-print-demo then open http://localhost:8080
+
+# 1) The web app (Flutter), built to talk to the API on the same address.
+FROM ghcr.io/cirruslabs/flutter:stable AS web
+WORKDIR /src
+COPY pubspec.yaml pubspec.lock .metadata ./
+COPY frontend ./frontend
+COPY web ./web
+RUN flutter pub get
+RUN flutter build web -t frontend/lib/main.dart --release --no-web-resources-cdn \
+ --dart-define=USE_MOCK=false
+
+# 2) The API (ASP.NET Core).
+FROM mcr.microsoft.com/dotnet/sdk:8.0 AS api
+WORKDIR /src
+COPY backend ./backend
+RUN dotnet publish backend -c Release -o /out
+
+# 3) Run both together: the API serves the web app from wwwroot.
+FROM mcr.microsoft.com/dotnet/aspnet:8.0
+WORKDIR /app
+COPY --from=api /out .
+COPY --from=web /src/build/web ./wwwroot
+ENV ASPNETCORE_ENVIRONMENT=Production \
+ Demo__Enabled=true
+USER $APP_UID
+EXPOSE 8080
+# Hosts such as Render tell the app which port to use through PORT.
+CMD ["sh", "-c", "ASPNETCORE_URLS=http://0.0.0.0:${PORT:-8080} exec dotnet PullPrintingBackend.dll"]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..e163f27
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Pull Print contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index d2d13a0..61a212f 100644
--- a/README.md
+++ b/README.md
@@ -1,122 +1,309 @@
-# pull_printing_app
-
-A **secure pull-printing** system prototype. A user sends a document to print, the server **holds** it, and it only prints when the user walks up to a printer, signs in and releases it. Built with a **Flutter** client and a **.NET (ASP.NET Core)** backend, with **Microsoft Entra ID (Azure AD)** for identity.
+# Pull Print
+[](https://github.com/Hikki-dev/pull_printing_app/actions/workflows/ci.yml)

-
-
+
+[](https://pull-print-demo.vercel.app)
+
+[](LICENSE)
+
+Send a document to print. It waits safely on a server. It only prints when you walk up to a printer, sign in with your work account and press **Print**. Printers and every person's page limit are managed from one screen.
-> **Status: early prototype.** The screens and API shape exist, but the pieces are not wired together yet and the backend does not build. Read [Current status](#current-status) before relying on any part of it.
+
-## About
+
A short walk through on a phone. Try it yourself. It runs on sample data, so nothing is really printed and no account is needed.
-An app that runs against a server and uses Azure to get the user's login details. When someone prints, the server keeps the job on hold until they go to the printer, sign in with the required credentials, and release it. They only ever see and print **their own** documents.
+You do not need to know how any of it works. Every screen says in plain words what to do next.
-## How it works
+## On this page
-1. A user sends a file to print, in the format they choose, from anywhere in the company (any floor).
-2. The server stores the job as **Held**. Nothing prints yet.
-3. At the printer the user signs in with their Azure credentials (card login is the intended next step).
-4. A screen shows **only their held jobs**. They press print on the ones they want.
-5. The job prints and their print quota goes down by one. An admin can set quotas.
+* [What you get](#what-you-get)
+* [How everything fits together](#how-everything-fits-together): one document, from sending to paper
+* [Try it first](#try-it-first): the live demo, no account needed
+* [Use it with your own accounts](#use-it-with-your-own-accounts): Microsoft 365 or Google Workspace
+* [The screens, step by step](#the-screens-step-by-step)
+ * [1. Sign in](#1-sign-in)
+ * [2. Choose what to print](#2-choose-what-to-print)
+ * [3. Print](#3-print)
+ * [At the printer's own screen](#at-the-printers-own-screen)
+ * [For administrators](#for-administrators)
+ * [Signing in with a work account](#signing-in-with-a-work-account)
+* [Run it yourself](#run-it-yourself) and [host it for free](#host-it-for-free)
+* [Your privacy and safety](#your-privacy-and-safety)
+* [The API in one table](#the-api-in-one-table)
+* [Limits](#limits) and [roadmap](#roadmap)
+* [Help and more reading](#help-and-more-reading)
-## Features
+## What you get
-| Feature | Where | State |
+| | | |
|---|---|---|
-| Sign in with Microsoft | `frontend/lib/screens/login_screen.dart`, `services/MsAuthService.dart` | UI done, sign-in does not complete yet (see status) |
-| List my held jobs and release one | `frontend/lib/screens/release_jobs_screen.dart` | UI done |
-| Admin dashboard listing all jobs | `frontend/lib/screens/admin_dashboard_screen.dart` | UI done, not reachable from login |
-| Quota indicator and job cards | `frontend/lib/widgets/` | Done |
-| Release endpoint with quota check | `backend/controllers/JobsController.cs` | Written |
-| Admin set-quota endpoint | `backend/controllers/AdminController.cs` | Written |
-| Print to a Windows queue | `backend/services/PrintService.cs` | Written (Windows only) |
+| **A phone and printer screen** | Sign in, see only your own documents, tick what you want, press Print | [Screens](#the-screens-step-by-step) |
+| **Page limits that cannot be skipped** | Checked on the server. Going over blocks Print and says by how many pages | [Choose what to print](#2-choose-what-to-print) |
+| **Work-account sign-in** | Microsoft 365 or Google Workspace. Only your organisation gets in | [Work accounts](#signing-in-with-a-work-account) |
+| **One place to manage everything** | Add printers, set pages a month for one person or everyone, see what is still to set up | [Administrators](#for-administrators) |
+| **Printer screens fixed to one printer** | Open a printer's link on its own screen and it prints there | [Printer's own screen](#at-the-printers-own-screen) |
+| **A free demo** | Every visitor gets private sample documents | [Try it first](#try-it-first) |
-## Architecture
+## How everything fits together
-```
-Flutter app (frontend/) ASP.NET Core API (backend/)
- LoginScreen ── MsAuthService (MSAL) AuthController POST /api/auth/login
- ReleaseJobsScreen ──┐ JobsController GET /api/jobs
- AdminDashboardScreen ┴── ApiService ─HTTP─▶ POST /api/jobs/release
- AdminController POST /api/admin/set-quota
- │
- AzureAuthService · UserService · PrintService
- └─ System.Printing queue
-```
+Send once, walk up, sign in, press Print. The server holds the document until then, and decides who may do what.
-### Data models
+
-- `User`: `Id`, `DisplayName`, `Email`, `IsAdmin`, `PrintQuota`
-- `PrintJob`: `Id`, `UserId`, `FileName`, `IsReleased`, `SubmittedAt`
-- `Quota`: `UserId`, `RemainingQuota`
+The whole story, including who decides what, is in [How it works](docs/How%20it%20works.md).
-### Backend API
+## Try it first
-| Method | Route | Purpose |
-|---|---|---|
-| `POST` | `/api/auth/login` | Body is a token string. 200 if valid, 401 otherwise |
-| `GET` | `/api/jobs` | List jobs |
-| `POST` | `/api/jobs/release` | Release a job. 403 when the user's quota is 0, otherwise prints and decrements the quota |
-| `POST` | `/api/admin/set-quota` | Body `{ "userId", "quota" }` |
+**Live demo: ** (runs entirely in your browser on built-in sample data).
-## Repository layout
+* Press **Sign in with Microsoft**. In the demo that signs you in to a private sandbox as "Alice Tan". No account is needed.
+* You start with four sample documents and 38 of 50 pages left.
+* Tick the documents you want and press **Print**. Tick too many and Print switches off and says by how many pages.
+* Printing does not use a real printer. It marks the documents as printed and uses up pages.
+* **Demo: sign in as administrator** shows every job and lets you manage printers and page limits, on a private copy of sample people.
+* A banner on every screen says it is a demo, and **What is this?** explains it in plain words. It also has **Start over**.
+* Other visitors never see your documents.
-```
-frontend/lib/ Flutter source: main.dart, screens, services, models, widgets
-frontend/db.json Sample held and released jobs for a mock JSON API
-backend/ ASP.NET Core API: controllers, services, models, data
-android/ ios/ web/ macos/ linux/ windows/ Flutter platform folders
-pubspec.yaml Flutter dependencies (repo root)
-```
+## Use it with your own accounts
-The Flutter entry point is **`frontend/lib/main.dart`**, not `lib/main.dart`.
+Run the server with your Microsoft 365 or Google Workspace details and people sign in with the work account they already have. You add printers once, and set pages a month for one person or everyone, from one screen. Step by step, about ten minutes: **[Connecting your workspace](docs/09-connecting-your-workspace.md)**.
+
+> Tested against a simulated Microsoft/Google sign-in only. It has not been run against a real tenant yet, so try it on a test tenant first ([issue #2](https://github.com/Hikki-dev/pull_printing_app/issues/2)).
+
+## The screens, step by step
+
+Every picture below was taken from the running app. Click one to see it full size. [Getting started](docs/Getting%20started.md) walks through the same screens with more detail, and [how the pictures are made](tools/screenshots/README.md) is explained if you want to refresh them.
+
+### 1. Sign in
+
+
+
+One button. There is no registration and no password field: the person signs in with their work account. In the demo the same button opens a private sandbox, and the banner at the top says so.
+
+
+
+### 2. Choose what to print
+
+
+
+Only the person's own documents are listed, newest first. The newest ones are ticked for them, stopping before anything would go over their limit. The ring shows the pages left this month.
+
+Tick a document that is too big, and Print switches off and says what to do:
+
+
+
+If more than one printer is set up, tap the printer name at the bottom to choose where to print:
+
+
+
+### 3. Print
+
+
+
+The confirmation names the printer, lists what printed, and shows the pages left. If the printer rejects some documents, they are named and stay on the list. Nothing is charged for a document that did not print.
+
+### At the printer's own screen
+
+Open a printer's **panel link** on the screen next to it, in full screen. It is fixed to that printer, so there is no question about where to print. It signs the person out after 60 seconds without a touch, and 20 seconds after printing, so the next person never sees their documents.
+
+
+
+
+
+
+
+Staff-card sign-in and a phone-code sign-in are drawn in the mockups but not built yet ([issue #6](https://github.com/Hikki-dev/pull_printing_app/issues/6)).
+
+### For administrators
+
+Everything an administrator needs is on one screen, in the order they need it.
+
+
+
+**Setup.** The first card says **Setup is complete**, or **Finish setting up** with each thing still to do in plain words. For a Microsoft or Google set-up it also shows the exact sign-in address to register, with a **Copy** button.
+
+
+
+
+
+**Printers.** Add, rename, switch off and remove printers. **Copy panel link** gives the address to open on that printer's own screen.
+
+
-## Running the Flutter app
+
+
+**People and quotas.** **New people start with** sets the pages a month for anyone who signs in from now on. **Give everyone** sets one number for the whole organisation (it asks first, because it replaces every limit). Each person also has their own row. People appear here the first time they sign in. Pages start again on the 1st of every month.
+
+
+
+
+
+**All jobs.** Every job with a search box and a status filter. A failed job says why.
+
+
+
+### Signing in with a work account
+
+When the server is set up for Microsoft 365 or Google Workspace, the sign-in button changes to match, and says who can use it.
+
+
+
+
+
+
+
+
Google Workspace
Microsoft 365
With the demo still on
+
+
+Someone who is not allowed in sees the reason, and can try again:
+
+
+
+What happens behind the button:
+
+
+
+## Run it yourself
+
+You need the [Flutter SDK](https://docs.flutter.dev/get-started/install) and the [.NET 8 SDK](https://dotnet.microsoft.com/download).
```bash
git clone https://github.com/Hikki-dev/pull_printing_app.git
cd pull_printing_app
+
+# Just the app, on built-in sample data. No server needed.
flutter pub get
flutter run -t frontend/lib/main.dart
+
+# The whole thing: API plus app, the way the hosted demo runs.
+flutter build web -t frontend/lib/main.dart --dart-define=USE_MOCK=false
+mkdir -p backend/wwwroot && cp -r build/web/. backend/wwwroot/
+ASPNETCORE_ENVIRONMENT=Development dotnet run --project backend # then open the address it prints
+
+# The app against an API running somewhere else (for example flutter run -d chrome)
+flutter run -d chrome -t frontend/lib/main.dart \
+ --dart-define=USE_MOCK=false --dart-define=API_BASE_URL=http://localhost:5000/api
```
-- `ApiService` calls `http://localhost:3000` with `GET /jobs`, `GET /jobs/held` and `POST /jobs/release`. Point it at your API, or at a mock server fed by `frontend/db.json`.
-- `frontend/lib/utils/constants.dart` holds an `apiBaseUrl` (default `http://localhost:5000/api`), but `ApiService` does not use it yet.
+Run the tests with `flutter test` (64) and `dotnet test backend.Tests` (112).
+
+Screens narrower than 760 px use the phone layout, wider ones the printer-panel layout.
-## Azure AD setup
+### Host it for free
-1. In the Azure portal, register an application in **Microsoft Entra ID**.
-2. Add a **Mobile and desktop** redirect URI of the form `msal://auth`.
-3. Add the delegated permission `User.Read`.
-4. Put your tenant and client ID in `frontend/lib/services/MsAuthService.dart` and `backend/services/AzureAuthService.cs`. Both currently contain placeholder or sample values.
+Two ways, both described in [Hosting the demo](docs/06-demo-hosting.md):
-## Current status
+* **Static, no server (what the live demo uses).** `vercel.json` and `scripts/vercel-build.sh` build the app on built-in sample data. Connect the repository to a Vercel project.
+* **Full stack.** A `Dockerfile` builds the web app and the API into one image, and `render.yaml` deploys it on Render's free plan: create a free account, choose **New, Blueprint**, and pick this repository.
-Known gaps, in rough priority order:
+To use real accounts instead of the demo, follow [Connecting your workspace](docs/09-connecting-your-workspace.md).
-1. **`backend/PullPrintingBackend.csproj` is empty**, so `dotnet build` fails. It needs a `Microsoft.NET.Sdk.Web` project that references `Microsoft.Identity.Client`.
-2. **Sign-in never completes.** `MsAuthService.init()` is never called, so the MSAL client is not created when `login()` runs, the error is caught and the user sees "Login failed.".
-3. **`AzureAuthService.ValidateToken` always returns `true`.** Real JWT validation against your tenant is required before this is exposed anywhere.
-4. **Endpoints are not protected.** `AdminController` and `JobsController` have no authorization, and the user id comes from the request body.
-5. **State is in memory.** Jobs and users live in lists and reset on restart. `ApplicationDbContext` is an empty placeholder.
-6. **Frontend and backend do not match.** The app calls `localhost:3000/jobs`, `/jobs/held`, `/jobs/release`, while the .NET API exposes `/api/jobs` and `/api/jobs/release`, and has no "my held jobs" route.
-7. **The admin dashboard uses a placeholder token** (`'your_token_here'`) and is not linked from the login flow.
-8. **No job submission path.** Nothing creates a held job yet.
-9. **Printing is Windows only.** `PrintService` uses `System.Printing`.
-10. **Duplicate MSAL wrappers.** `MsAuthService.dart` and `msal_flutter.dart` (`MsalService`) overlap. Keep one.
-11. **Tests are the Flutter template.** `test/widget_test.dart` still expects the counter app.
+### Repository layout
+
+```
+frontend/lib/ Flutter source: main.dart, screens, services, models, widgets, utils
+backend/ ASP.NET Core API: controllers, services, models
+backend.Tests/ API, store and sign-in tests (with a simulated Microsoft/Google)
+test/ Flutter tests
+tools/screenshots/ Takes every picture in these docs from the running app
+scripts/ Build script for static hosting
+docs/ Guides, design documents, pictures and mockups
+Dockerfile One image with the API and the web app
+render.yaml One-click free hosting on Render
+.github/workflows/ CI: backend tests, Flutter tests, and the Docker image
+CONTRIBUTING.md SECURITY.md CHANGELOG.md
+```
+
+The Flutter entry point is **`frontend/lib/main.dart`**, not `lib/main.dart`.
+
+## Your privacy and safety
+
+* **Every route except sign-in and `/healthz` needs a valid token.** Tokens are signed by the server and checked on every request. Admin routes need the Admin role.
+* **People only reach their own data.** Printing ignores any document that is not yours and waiting. Administrators only see and change people in their own group.
+* **Work accounts** sign in on Microsoft's or Google's own page. Pull Print never sees a password, only your organisation gets in, and the client secret stays on the server.
+* **The demo** is limited to 20 sign-ins a minute per address, at most 300 sandboxes exist at once, and each is deleted after 2 hours without use. Switch it off for anything real (`Demo__Enabled=false`): its tokens stop working immediately.
+* **Data is in memory** and is lost when the server restarts (see [Limits](#limits)).
+
+To report a security problem, read [SECURITY.md](SECURITY.md).
+
+## The API in one table
+
+All routes except sign-in and health need `Authorization: Bearer `.
+
+| Method | Route | Who | What it does |
+|---|---|---|---|
+| `GET` | `/api/auth/config` | anyone | Which sign-in to offer: `{ provider, providerName, domain, demo }` |
+| `POST` | `/api/auth/demo-login` | anyone, demo only | Creates a private sandbox and returns a token. Body `{ "admin": false }`. 404 unless `Demo__Enabled` is true |
+| `GET` | `/api/auth/login` | anyone, work accounts only | Sends the browser to Microsoft or Google. `?returnTo=/path` says where to come back to. 404 unless work sign-in is set up |
+| `GET` | `/api/auth/me` | signed in | Name and role from the token |
+| `GET` | `/api/printers` | signed in | The printers people can use (administrators also see switched-off ones) |
+| `GET` | `/api/jobs/held` | signed in | Your waiting documents, newest first |
+| `GET` | `/api/jobs/quota` | signed in | `{ used, total, left }` pages |
+| `POST` | `/api/jobs/release` | signed in | Body `{ "jobIds": [...], "printerId": "..." }`. 200 with what printed and where, 409 `quota_exceeded` with `pagesOver`, 409 `no_printer` or `printer_unavailable`, 404 if none of them are yours and waiting, 400 if empty |
+| `POST` | `/api/jobs/sample` | signed in, demo only | Adds one sample document to your list |
+| `GET` | `/api/jobs` | administrator | Every job in the administrator's own group |
+| `GET` | `/api/admin/setup` | administrator | How the server is set up and anything still to do, plus the address to register with Microsoft or Google |
+| `GET` | `/api/admin/users` | administrator | People in the administrator's group with their quotas |
+| `POST` | `/api/admin/set-quota` | administrator | Body `{ "userId", "quota" }`, 0 to 10000 pages |
+| `POST` | `/api/admin/default-quota` | administrator | Body `{ "quota" }`. Pages a month for people who sign in from now on |
+| `POST` | `/api/admin/set-quota-all` | administrator | Body `{ "quota" }`. Gives everyone the same pages, returns `{ "changed" }` |
+| `POST` `PUT` `DELETE` | `/api/admin/printers`, `/api/admin/printers/{id}` | administrator | Add, change (name, place, on or off) and remove printers |
+| `GET` | `/healthz` | anyone | `{ "status": "ok" }` |
+
+## Limits
+
+This is a demo, so on purpose:
+
+1. **Data lives in memory.** Everything resets when the server restarts, and demo sandboxes are deleted after 2 hours without use. A database would replace `PrintStore` (it sits behind `IPrintStore`).
+2. **Nothing is really printed.** `SimulatedPrintDispatcher` only logs. A real printer integration implements `IPrintDispatcher`.
+3. **No way to send a file yet.** The demo makes sample documents. Real submission (a print driver, email-to-print or upload) is an open decision, see `docs/05-open-decisions.md`.
+4. **Work-account sign-in is untested** against a real Microsoft or Google tenant. Sign-in runs in the browser, so a printer panel needs a browser in kiosk mode.
+5. **Free hosts sleep.** The first visit after a quiet period can take a minute to wake the server.
+6. **Placeholders to replace:** the Pull Print mark, the printer illustration, drawn document thumbnails and the drawn Microsoft and Google marks (use their own assets). See `docs/04-design-guidelines.md`.
+7. **Not built:** staff-card sign-in and the phone code sign-in screen from the mockups.
+8. **People, printers and quotas are lost on restart** until a database backs `IPrintStore`, and quotas are per person (no groups yet).
## Roadmap
-- [ ] Fill in the `.csproj` and get `dotnet run` working
-- [ ] Call `MsAuthService.init()` and complete Microsoft sign-in
-- [ ] Validate Entra ID tokens and add `[Authorize]` with an admin role
-- [ ] Persist users, jobs and quotas with EF Core
-- [ ] Add a job submission path and a "my held jobs" endpoint
-- [ ] Align frontend routes with the API
+- [x] Redesigned UI, demo mode and tests
+- [x] Backend builds, routes match the app, endpoints protected, tests
+- [x] Free hosting for a public demo
+- [x] A review from each user's point of view, with fixes ([docs/08](docs/08-review-and-fixes.md))
+- [x] Work-account sign-in (Microsoft and Google), central printers and quotas
+- [ ] Test work-account sign-in against a real tenant
+- [ ] Persist users, jobs and quotas in a database
+- [ ] A way to send a file to be held
+- [ ] A real printer integration
- [ ] Card login at the printer
-- [ ] Real tests
+
+## Help and more reading
+
+| If you want to | Read |
+|---|---|
+| Follow every screen with pictures | [Getting started](docs/Getting%20started.md) |
+| Use Microsoft 365 or Google Workspace | [Connecting your workspace](docs/09-connecting-your-workspace.md) |
+| Find a quick answer | [Questions and answers](docs/FAQ.md) |
+| Fix a problem | [Fixing problems](docs/Fixing%20problems.md) |
+| Put the demo online for free | [Hosting the demo](docs/06-demo-hosting.md) |
+| Understand how the pieces fit, every route and setting | [How it works](docs/How%20it%20works.md) |
+| See what went wrong from each user's point of view, and the fixes | [Review and fixes](docs/08-review-and-fixes.md) |
+| See the screens as designed, with exact wording | [Screen specs](docs/03-screen-specs.md) |
+| Answer the questions that change the design | [Open decisions](docs/05-open-decisions.md) |
+| Refresh the pictures in these docs | [tools/screenshots](tools/screenshots/README.md) |
+| Change the code | [Contributing](CONTRIBUTING.md) |
+| See what changed | [Changes](CHANGELOG.md) |
+
+All the design documents are listed in [`docs/`](docs/README.md).
+
+## Legal and responsibility
+
+* Pull Print is a portfolio and learning project, and a demo. It is not a finished print product, and nothing in the live demo prints on paper.
+* The code is released under the [MIT licence](LICENSE), as it is, with no promises.
+
+## Credits
+
+The Microsoft and Google marks on the sign-in buttons are drawn to their published rules and are placeholders: swap in their own assets before a public launch. Printer and document pictures are drawn for this project.
## Author
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..22ce1b1
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,39 @@
+# Security
+
+## Reporting a problem
+
+Please **do not open a public issue** for a security problem. Use GitHub's private reporting instead: on the repository page choose **Security**, then **Report a vulnerability**. Say what you found, how to reproduce it, and what it lets someone do.
+
+You will get an answer as soon as someone can look at it. This is a demo project maintained by one person, so there is no promised response time.
+
+## What this project is, and is not
+
+This is a **demo**. Its hosted version lets anyone sign in to a private sandbox of sample data. Do not put real documents, real people or real printers behind it.
+
+## What is protected
+
+- Every route except sign-in, the sign-in options and `/healthz` needs a valid signed token.
+- People only reach their own waiting documents. Administrators only reach people in their own group.
+- Printing is checked against the person's page quota on the server.
+- Demo sign-in is rate limited, sandboxes are capped and deleted after two hours idle, and request bodies are limited to 16 KB.
+- Work-account sign-in uses the authorization code flow with PKCE, only accepts people from your organisation, and sends the session token back after `#` so it is not sent to any server or left in the history.
+- Replies carry basic security headers, and unexpected errors never return details.
+
+## What is not done yet
+
+- Microsoft and Google work-account sign-in is tested against a simulated provider only. It **has not been run against a real tenant**.
+- A session token lasts 8 hours and cannot be revoked early. Someone removed from your organisation keeps access until it ends.
+- Data is in memory only, with no encryption at rest because there is nothing at rest.
+- Limits are per network address and trust the host's `X-Forwarded-For` header, which is right behind Render or similar hosts and wrong anywhere that does not set it.
+- No audit log.
+
+## Settings that matter
+
+| Setting | What to do |
+|---|---|
+| `Demo__Enabled` | Turn **off** for anything that is not a demo. Its tokens stop working immediately |
+| `Auth__SigningKey` | Set to a long random value (32 characters or more) and keep it secret. Without it everyone is signed out on every restart |
+| `Workspace__Provider`, `__ClientId`, `__ClientSecret`, `__TenantId`, `__Domain` | Turn on Microsoft or Google sign-in. See [docs/09](docs/09-connecting-your-workspace.md). The client secret belongs only on the server |
+| `Workspace__Admins` | Who is an administrator. Keep it short |
+
+The client secret is never sent to the app. Google sign-in refuses to turn on without `Workspace__Domain`, so it cannot be left open to every Google account.
diff --git a/backend.Tests/ApiTests.cs b/backend.Tests/ApiTests.cs
new file mode 100644
index 0000000..eac9a01
--- /dev/null
+++ b/backend.Tests/ApiTests.cs
@@ -0,0 +1,474 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace PullPrintingBackend.Tests;
+
+public class ApiFactory : WebApplicationFactory
+{
+ public const string Key = "test-signing-key-that-is-long-enough-for-hs256";
+
+ protected virtual bool DemoEnabled => true;
+
+ /// Tests call the API a lot from one address, so the limits are raised unless a test is about them.
+ protected virtual int LoginsPerMinute => 1000;
+
+ protected override void ConfigureWebHost(IWebHostBuilder builder)
+ {
+ builder.UseEnvironment("Testing");
+ builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(new Dictionary
+ {
+ ["Demo:Enabled"] = DemoEnabled ? "true" : "false",
+ ["Auth:SigningKey"] = Key,
+ ["RateLimit:LoginPerMinute"] = LoginsPerMinute.ToString(),
+ ["RateLimit:PerMinute"] = "100000",
+ }));
+ }
+}
+
+public class DemoOffFactory : ApiFactory
+{
+ protected override bool DemoEnabled => false;
+}
+
+public class DefaultLimitsFactory : ApiFactory
+{
+ protected override int LoginsPerMinute => 20;
+}
+
+/// A store that fails the way a real bug would, to check what the person sees.
+public class BrokenStoreFactory : ApiFactory
+{
+ protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder)
+ {
+ base.ConfigureWebHost(builder);
+ builder.ConfigureServices(services =>
+ {
+ var inner = new PullPrintingBackend.Services.PrintStore(
+ new PullPrintingBackend.Services.SimulatedPrintDispatcher(
+ Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance),
+ TimeProvider.System,
+ Microsoft.Extensions.Options.Options.Create(new PullPrintingBackend.Services.WorkspaceOptions()));
+ services.AddSingleton(new BrokenStore(inner));
+ });
+ }
+}
+
+public class BrokenStore : PullPrintingBackend.Services.IPrintStore
+{
+ private readonly PullPrintingBackend.Services.IPrintStore _inner;
+ public BrokenStore(PullPrintingBackend.Services.IPrintStore inner) => _inner = inner;
+
+ // Signing in works so the test can get a token; reading documents blows up.
+ public PullPrintingBackend.Models.UserSummary EnsureUser(string id, string name, bool isAdmin, string? email = null) => _inner.EnsureUser(id, name, isAdmin, email);
+ public PullPrintingBackend.Models.UserSummary EnsureDemoUser(string id, string name, bool isAdmin) => _inner.EnsureDemoUser(id, name, isAdmin);
+ public PullPrintingBackend.Models.UserSummary CreateDemoUser(bool isAdmin) => _inner.CreateDemoUser(isAdmin);
+ public PullPrintingBackend.Models.Quota? GetQuota(string userId) => _inner.GetQuota(userId);
+ public IReadOnlyList HeldJobs(string userId) => throw new InvalidOperationException("secret internal detail");
+ public IReadOnlyList AllJobs(string requesterId) => _inner.AllJobs(requesterId);
+ public IReadOnlyList Users(string requesterId) => _inner.Users(requesterId);
+ public PullPrintingBackend.Services.ReleaseResult Release(string userId, IReadOnlyCollection jobIds, string? printerId = null) => _inner.Release(userId, jobIds, printerId);
+ public int? DefaultQuota(string requesterId) => _inner.DefaultQuota(requesterId);
+ public bool SetDefaultQuota(string requesterId, int quota) => _inner.SetDefaultQuota(requesterId, quota);
+ public int SetQuotaForAll(string requesterId, int quota) => _inner.SetQuotaForAll(requesterId, quota);
+ public IReadOnlyList Printers(string requesterId) => _inner.Printers(requesterId);
+ public PullPrintingBackend.Models.Printer? AddPrinter(string requesterId, string name, string location) => _inner.AddPrinter(requesterId, name, location);
+ public bool UpdatePrinter(string requesterId, string printerId, string name, string location, bool enabled) => _inner.UpdatePrinter(requesterId, printerId, name, location, enabled);
+ public bool DeletePrinter(string requesterId, string printerId) => _inner.DeletePrinter(requesterId, printerId);
+ public bool SetQuota(string requesterId, string userId, int quota) => _inner.SetQuota(requesterId, userId, quota);
+ public PullPrintingBackend.Models.PrintJob? AddSample(string userId) => _inner.AddSample(userId);
+ public int Sweep() => _inner.Sweep();
+}
+
+public record Session(string Token, string UserId, string Name, bool IsAdmin);
+
+public class ApiTests : IClassFixture
+{
+ private readonly ApiFactory _factory;
+ public ApiTests(ApiFactory factory) => _factory = factory;
+
+ private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
+
+ private async Task<(HttpClient Client, Session Session)> SignIn(bool admin = false)
+ {
+ var client = _factory.CreateClient();
+ var response = await client.PostAsJsonAsync("/api/auth/demo-login", new { admin });
+ response.EnsureSuccessStatusCode();
+ var session = (await response.Content.ReadFromJsonAsync(Json))!;
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token);
+ return (client, session);
+ }
+
+ private static async Task Body(HttpResponseMessage response) =>
+ (await response.Content.ReadFromJsonAsync(Json));
+
+ private static async Task> Held(HttpClient client) =>
+ (await Body(await client.GetAsync("/api/jobs/held"))).EnumerateArray().ToList();
+
+ private static async Task HeldNames(HttpClient client) =>
+ (await Held(client)).Select(j => j.GetProperty("fileName").GetString()!).ToArray();
+
+ // ---- authentication ----------------------------------------------------
+
+ [Theory]
+ [InlineData("GET", "/api/jobs/held")]
+ [InlineData("GET", "/api/jobs/quota")]
+ [InlineData("GET", "/api/jobs")]
+ [InlineData("GET", "/api/auth/me")]
+ [InlineData("GET", "/api/admin/users")]
+ [InlineData("POST", "/api/jobs/release")]
+ [InlineData("POST", "/api/jobs/sample")]
+ [InlineData("POST", "/api/admin/set-quota")]
+ public async Task Endpoints_need_a_token(string method, string path)
+ {
+ var client = _factory.CreateClient();
+ var response = await client.SendAsync(new HttpRequestMessage(new HttpMethod(method), path));
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task Garbage_and_wrongly_signed_tokens_are_rejected()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "not-a-token");
+ Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/jobs/held")).StatusCode);
+
+ // A well-formed token signed with some other key.
+ var forged = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(
+ new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
+ "pullprint", "pullprint",
+ new[] { new System.Security.Claims.Claim("uid", "u2"), new System.Security.Claims.Claim("role", "Admin") },
+ expires: DateTime.UtcNow.AddHours(1),
+ signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(
+ new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(
+ System.Text.Encoding.UTF8.GetBytes("a-completely-different-signing-key-123456")),
+ Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256)));
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", forged);
+ Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/jobs")).StatusCode);
+ }
+
+ [Fact]
+ public async Task Demo_sign_in_returns_a_token_that_names_the_visitor()
+ {
+ var (client, session) = await SignIn();
+ Assert.Equal("Alice Tan", session.Name);
+ Assert.False(session.IsAdmin);
+
+ var me = await Body(await client.GetAsync("/api/auth/me"));
+ Assert.Equal(session.UserId, me.GetProperty("userId").GetString());
+ Assert.False(me.GetProperty("isAdmin").GetBoolean());
+ }
+
+ [Fact]
+ public async Task Demo_sign_in_can_be_switched_off_and_then_its_tokens_stop_working()
+ {
+ var (_, session) = await SignIn();
+
+ using var off = new DemoOffFactory();
+ var client = off.CreateClient();
+ Assert.Equal(HttpStatusCode.NotFound,
+ (await client.PostAsJsonAsync("/api/auth/demo-login", new { admin = false })).StatusCode);
+
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token);
+ Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/jobs/held")).StatusCode);
+ }
+
+ [Fact]
+ public async Task Normal_users_cannot_use_admin_routes()
+ {
+ var (client, session) = await SignIn();
+ Assert.Equal(HttpStatusCode.Forbidden, (await client.GetAsync("/api/jobs")).StatusCode);
+ Assert.Equal(HttpStatusCode.Forbidden, (await client.GetAsync("/api/admin/users")).StatusCode);
+ Assert.Equal(HttpStatusCode.Forbidden,
+ (await client.PostAsJsonAsync("/api/admin/set-quota", new { userId = session.UserId, quota = 9999 })).StatusCode);
+
+ // And the quota was not changed.
+ var quota = await Body(await client.GetAsync("/api/jobs/quota"));
+ Assert.Equal(50, quota.GetProperty("total").GetInt32());
+ }
+
+ [Fact]
+ public async Task Admins_see_the_jobs_of_their_own_sample_people_and_nobody_elses()
+ {
+ var (visitor, _) = await SignIn();
+ var visitorJobIds = (await Held(visitor)).Select(j => j.GetProperty("id").GetString()).ToHashSet();
+
+ var (admin, _) = await SignIn(admin: true);
+ var response = await admin.GetAsync("/api/jobs");
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var jobs = (await Body(response)).EnumerateArray().ToList();
+ var names = jobs.Select(j => j.GetProperty("fileName").GetString()).ToList();
+ Assert.Contains("Safety audit.pdf", names);
+ Assert.Contains("Invoice 2291.pdf", names);
+
+ // The visitor's documents are not in the administrator's view.
+ Assert.DoesNotContain(jobs, j => visitorJobIds.Contains(j.GetProperty("id").GetString()));
+ }
+
+ [Fact]
+ public async Task Sign_in_attempts_are_rate_limited()
+ {
+ using var factory = new DefaultLimitsFactory();
+ var client = factory.CreateClient();
+ HttpStatusCode last = HttpStatusCode.OK;
+ for (var i = 0; i < 25; i++)
+ last = (await client.PostAsJsonAsync("/api/auth/demo-login", new { admin = false })).StatusCode;
+ Assert.Equal(HttpStatusCode.TooManyRequests, last);
+ }
+
+ [Fact]
+ public async Task Health_check_needs_no_token()
+ {
+ var response = await _factory.CreateClient().GetAsync("/healthz");
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task Replies_carry_basic_security_headers()
+ {
+ var response = await _factory.CreateClient().GetAsync("/healthz");
+ Assert.Equal("nosniff", response.Headers.GetValues("X-Content-Type-Options").Single());
+ Assert.Equal("DENY", response.Headers.GetValues("X-Frame-Options").Single());
+ Assert.Equal("no-referrer", response.Headers.GetValues("Referrer-Policy").Single());
+ Assert.Contains("frame-ancestors 'none'", response.Headers.GetValues("Content-Security-Policy").Single());
+ }
+
+ [Fact]
+ public async Task An_unexpected_failure_gives_a_short_json_error_with_no_details()
+ {
+ using var broken = new BrokenStoreFactory();
+ var client = broken.CreateClient();
+ var login = await client.PostAsJsonAsync("/api/auth/demo-login", new { admin = false });
+ var session = (await login.Content.ReadFromJsonAsync(Json))!;
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token);
+
+ var response = await client.GetAsync("/api/jobs/held");
+
+ Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
+ var text = await response.Content.ReadAsStringAsync();
+ Assert.Contains("server_error", text);
+ Assert.DoesNotContain("secret internal detail", text);
+ Assert.DoesNotContain(" at ", text); // no stack trace
+ }
+
+ // ---- documents and quota -----------------------------------------------
+
+ [Fact]
+ public async Task A_visitor_sees_only_their_own_waiting_documents()
+ {
+ var (client, _) = await SignIn();
+ var names = await HeldNames(client);
+ Assert.Equal(
+ new[] { "Q3 budget review.pdf", "Site visit notes.docx", "Contract draft v4.pdf", "Floor plan.png" },
+ names);
+ Assert.DoesNotContain("Safety audit.pdf", names);
+
+ var quota = await Body(await client.GetAsync("/api/jobs/quota"));
+ Assert.Equal(12, quota.GetProperty("used").GetInt32());
+ Assert.Equal(50, quota.GetProperty("total").GetInt32());
+ Assert.Equal(38, quota.GetProperty("left").GetInt32());
+ }
+
+ [Fact]
+ public async Task Printing_uses_up_pages_and_removes_the_documents_from_the_list()
+ {
+ var (client, _) = await SignIn();
+ var held = await Held(client);
+ var ids = held.Take(2).Select(j => j.GetProperty("id").GetString()).ToList();
+
+ var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = ids });
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var body = await Body(response);
+ Assert.Equal(15, body.GetProperty("pages").GetInt32());
+ Assert.Equal(27, body.GetProperty("quota").GetProperty("used").GetInt32());
+
+ Assert.Equal(new[] { "Contract draft v4.pdf", "Floor plan.png" }, await HeldNames(client));
+ }
+
+ [Fact]
+ public async Task Going_over_quota_prints_nothing_and_says_by_how_much()
+ {
+ var (client, _) = await SignIn();
+ var ids = (await Held(client)).Select(j => j.GetProperty("id").GetString()).ToList(); // 44 pages, 38 left
+
+ var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = ids });
+ Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
+ var body = await Body(response);
+ Assert.Equal("quota_exceeded", body.GetProperty("error").GetString());
+ Assert.Equal(6, body.GetProperty("pagesOver").GetInt32());
+
+ Assert.Equal(4, (await Held(client)).Count);
+ var quota = await Body(await client.GetAsync("/api/jobs/quota"));
+ Assert.Equal(12, quota.GetProperty("used").GetInt32());
+ }
+
+ [Fact]
+ public async Task Someone_elses_document_cannot_be_printed()
+ {
+ var (client, _) = await SignIn();
+ var (admin, _) = await SignIn(admin: true);
+ var all = (await Body(await admin.GetAsync("/api/jobs"))).EnumerateArray().ToList();
+ var priyas = all.First(j => j.GetProperty("fileName").GetString() == "Safety audit.pdf").GetProperty("id").GetString();
+
+ var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = new[] { priyas } });
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+
+ var after = (await Body(await admin.GetAsync("/api/jobs"))).EnumerateArray()
+ .First(j => j.GetProperty("id").GetString() == priyas);
+ Assert.Equal("Held", after.GetProperty("status").GetString());
+ }
+
+ [Fact]
+ public async Task Visitors_are_isolated_from_each_other()
+ {
+ var (first, _) = await SignIn();
+ var (second, _) = await SignIn();
+ var ids = (await Held(first)).Take(2).Select(j => j.GetProperty("id").GetString()).ToList();
+ Assert.Equal(HttpStatusCode.OK, (await first.PostAsJsonAsync("/api/jobs/release", new { jobIds = ids })).StatusCode);
+
+ Assert.Equal(2, (await Held(first)).Count);
+ Assert.Equal(4, (await Held(second)).Count);
+ var quota = await Body(await second.GetAsync("/api/jobs/quota"));
+ Assert.Equal(12, quota.GetProperty("used").GetInt32());
+ }
+
+ [Fact]
+ public async Task Bad_release_requests_are_refused()
+ {
+ var (client, _) = await SignIn();
+ Assert.Equal(HttpStatusCode.BadRequest,
+ (await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = Array.Empty() })).StatusCode);
+ Assert.Equal(HttpStatusCode.NotFound,
+ (await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = new[] { "nope" } })).StatusCode);
+
+ var id = (await Held(client)).First().GetProperty("id").GetString();
+ Assert.Equal(HttpStatusCode.OK, (await client.PostAsJsonAsync("/api/jobs/release", new { jobId = id })).StatusCode);
+ // Printing the same document twice is refused and charges nothing more.
+ Assert.Equal(HttpStatusCode.NotFound, (await client.PostAsJsonAsync("/api/jobs/release", new { jobId = id })).StatusCode);
+ var quota = await Body(await client.GetAsync("/api/jobs/quota"));
+ Assert.Equal(24, quota.GetProperty("used").GetInt32());
+ }
+
+ [Fact]
+ public async Task Printing_too_many_documents_in_one_go_is_refused()
+ {
+ var (client, _) = await SignIn();
+ var ids = Enumerable.Range(0, 51).Select(i => "id" + i).ToArray();
+ var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = ids });
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Equal("too_many", (await Body(response)).GetProperty("error").GetString());
+ }
+
+ [Fact]
+ public async Task The_same_document_sent_twice_is_charged_once()
+ {
+ var (client, _) = await SignIn();
+ var id = (await Held(client)).First().GetProperty("id").GetString();
+
+ var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = new[] { id, id } });
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(12, (await Body(response)).GetProperty("pages").GetInt32());
+ }
+
+ [Fact]
+ public async Task Sample_documents_are_new_ones_first_and_run_out()
+ {
+ var (client, _) = await SignIn();
+ var added = new List();
+ for (var i = 0; i < 4; i++)
+ {
+ var response = await client.PostAsync("/api/jobs/sample", null);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ added.Add((await Body(response)).GetProperty("fileName").GetString()!);
+ }
+ Assert.Equal(
+ new[] { "Meeting agenda.docx", "Safety checklist.pdf", "Onboarding guide.pdf", "Site photo.png" },
+ added.OrderBy(n => n).Select(n => n).OrderBy(n => Array.IndexOf(
+ new[] { "Meeting agenda.docx", "Safety checklist.pdf", "Onboarding guide.pdf", "Site photo.png" }, n)));
+ Assert.Equal(8, (await Held(client)).Count);
+ Assert.Equal(HttpStatusCode.Conflict, (await client.PostAsync("/api/jobs/sample", null)).StatusCode);
+ }
+
+ [Fact]
+ public async Task A_printed_document_does_not_come_straight_back_as_a_sample()
+ {
+ var (client, _) = await SignIn();
+ var first = (await Held(client)).First().GetProperty("id").GetString();
+ await client.PostAsJsonAsync("/api/jobs/release", new { jobId = first }); // Q3 budget review.pdf
+
+ var sample = await Body(await client.PostAsync("/api/jobs/sample", null));
+ Assert.NotEqual("Q3 budget review.pdf", sample.GetProperty("fileName").GetString());
+ }
+
+ // ---- administration -----------------------------------------------------
+
+ private static async Task> AdminUsers(HttpClient admin) =>
+ (await Body(await admin.GetAsync("/api/admin/users"))).EnumerateArray().ToList();
+
+ private static JsonElement Person(List users, string name) =>
+ users.First(u => u.GetProperty("name").GetString() == name);
+
+ [Fact]
+ public async Task An_admin_sees_sample_people_and_can_change_their_quota()
+ {
+ var (admin, _) = await SignIn(admin: true);
+ var users = await AdminUsers(admin);
+ Assert.Equal(
+ new[] { "Alice Tan", "Bob Reyes", "Marcus Lee", "Priya Nair" },
+ users.Select(u => u.GetProperty("name").GetString()).ToArray());
+ Assert.Equal(200, Person(users, "Priya Nair").GetProperty("quota").GetProperty("total").GetInt32());
+
+ var priya = Person(users, "Priya Nair").GetProperty("userId").GetString();
+ Assert.Equal(HttpStatusCode.OK,
+ (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = priya, quota = 20 })).StatusCode);
+
+ var after = await AdminUsers(admin);
+ Assert.Equal(20, Person(after, "Priya Nair").GetProperty("quota").GetProperty("total").GetInt32());
+ }
+
+ [Fact]
+ public async Task An_admin_cannot_see_or_change_a_visitors_account()
+ {
+ var (_, visitor) = await SignIn();
+ var (admin, _) = await SignIn(admin: true);
+
+ Assert.DoesNotContain(await AdminUsers(admin), u => u.GetProperty("userId").GetString() == visitor.UserId);
+ Assert.Equal(HttpStatusCode.NotFound,
+ (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = visitor.UserId, quota = 1 })).StatusCode);
+ }
+
+ [Fact]
+ public async Task Two_admins_do_not_affect_each_other()
+ {
+ var (first, _) = await SignIn(admin: true);
+ var (second, _) = await SignIn(admin: true);
+
+ var priya = Person(await AdminUsers(first), "Priya Nair").GetProperty("userId").GetString();
+ Assert.Equal(HttpStatusCode.OK,
+ (await first.PostAsJsonAsync("/api/admin/set-quota", new { userId = priya, quota = 5 })).StatusCode);
+
+ Assert.Equal(200, Person(await AdminUsers(second), "Priya Nair").GetProperty("quota").GetProperty("total").GetInt32());
+ Assert.Equal(HttpStatusCode.NotFound,
+ (await second.PostAsJsonAsync("/api/admin/set-quota", new { userId = priya, quota = 1 })).StatusCode);
+ }
+
+ [Fact]
+ public async Task Quota_changes_are_validated()
+ {
+ var (admin, session) = await SignIn(admin: true);
+ Assert.Equal(HttpStatusCode.BadRequest,
+ (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = session.UserId, quota = -1 })).StatusCode);
+ Assert.Equal(HttpStatusCode.BadRequest,
+ (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = session.UserId, quota = 1_000_000 })).StatusCode);
+ Assert.Equal(HttpStatusCode.BadRequest,
+ (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = "", quota = 10 })).StatusCode);
+ Assert.Equal(HttpStatusCode.NotFound,
+ (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = "nobody", quota = 10 })).StatusCode);
+ }
+}
diff --git a/backend.Tests/PrinterAndQuotaTests.cs b/backend.Tests/PrinterAndQuotaTests.cs
new file mode 100644
index 0000000..18511a0
--- /dev/null
+++ b/backend.Tests/PrinterAndQuotaTests.cs
@@ -0,0 +1,317 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Options;
+using PullPrintingBackend.Models;
+using PullPrintingBackend.Services;
+
+namespace PullPrintingBackend.Tests;
+
+public class PrinterAndQuotaStoreTests
+{
+ private class FakeClock : TimeProvider
+ {
+ public DateTimeOffset Now { get; set; } = new(2026, 10, 22, 9, 0, 0, TimeSpan.Zero);
+ public override DateTimeOffset GetUtcNow() => Now;
+ }
+
+ private static PrintStore NewStore(FakeClock? clock = null, int defaultQuota = 50) =>
+ new(new SimulatedPrintDispatcher(NullLogger.Instance),
+ clock ?? new FakeClock(),
+ Options.Create(new WorkspaceOptions { DefaultQuota = defaultQuota }));
+
+ [Fact]
+ public void Pages_used_start_again_when_the_month_changes()
+ {
+ var clock = new FakeClock { Now = new(2026, 10, 31, 23, 0, 0, TimeSpan.Zero) };
+ var store = NewStore(clock);
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ var ids = store.HeldJobs(visitor.UserId).Take(2).Select(j => j.Id).ToList();
+
+ var printed = store.Release(visitor.UserId, ids);
+ Assert.Equal(ReleaseOutcome.Printed, printed.Outcome);
+ Assert.True(store.GetQuota(visitor.UserId)!.Used > 0);
+
+ clock.Now = new(2026, 11, 1, 0, 30, 0, TimeSpan.Zero);
+ Assert.Equal(0, store.GetQuota(visitor.UserId)!.Used);
+ }
+
+ [Fact]
+ public void Pages_used_do_not_reset_within_the_same_month()
+ {
+ var clock = new FakeClock { Now = new(2026, 10, 1, 0, 0, 0, TimeSpan.Zero) };
+ var store = NewStore(clock);
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ store.Release(visitor.UserId, store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList());
+ var used = store.GetQuota(visitor.UserId)!.Used;
+
+ clock.Now = new(2026, 10, 31, 23, 59, 0, TimeSpan.Zero);
+ Assert.Equal(used, store.GetQuota(visitor.UserId)!.Used);
+ }
+
+ [Fact]
+ public void The_default_quota_is_used_for_people_who_sign_in_later_and_not_for_those_already_there()
+ {
+ var store = NewStore(defaultQuota: 40);
+ var boss = store.EnsureUser("boss", "Boss", isAdmin: true);
+ var early = store.EnsureUser("early", "Early", isAdmin: false);
+ Assert.Equal(40, early.Quota.Total);
+
+ Assert.True(store.SetDefaultQuota(boss.UserId, 120));
+ Assert.Equal(120, store.DefaultQuota(boss.UserId));
+ Assert.Equal(120, store.EnsureUser("late", "Late", isAdmin: false).Quota.Total);
+ Assert.Equal(40, store.GetQuota("early")!.Total);
+ }
+
+ [Fact]
+ public void Giving_everyone_the_same_pages_changes_the_whole_group_and_only_that_group()
+ {
+ var store = NewStore();
+ var boss = store.EnsureUser("boss", "Boss", isAdmin: true);
+ store.EnsureUser("a", "A", isAdmin: false);
+ store.EnsureUser("b", "B", isAdmin: false);
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ var visitorBefore = store.GetQuota(visitor.UserId)!.Total;
+
+ var changed = store.SetQuotaForAll(boss.UserId, 15);
+
+ Assert.True(changed >= 2);
+ Assert.Equal(15, store.GetQuota("a")!.Total);
+ Assert.Equal(15, store.GetQuota("b")!.Total);
+ Assert.Equal(visitorBefore, store.GetQuota(visitor.UserId)!.Total);
+ }
+
+ [Fact]
+ public void A_demo_visitor_starts_with_three_printers_and_a_workspace_with_none()
+ {
+ var store = NewStore();
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ var boss = store.EnsureUser("boss", "Boss", isAdmin: true);
+
+ Assert.Equal(new[] { "Level 3 East", "Print room", "Reception" },
+ store.Printers(visitor.UserId).Select(p => p.Name).ToArray());
+ Assert.Empty(store.Printers(boss.UserId));
+ }
+
+ [Fact]
+ public void Printers_can_be_added_renamed_switched_off_and_removed()
+ {
+ var store = NewStore();
+ var boss = store.EnsureUser("boss", "Boss", isAdmin: true);
+
+ var added = store.AddPrinter(boss.UserId, "Studio", "Level 1")!;
+ Assert.Equal("Studio", store.Printers(boss.UserId).Single().Name);
+
+ Assert.True(store.UpdatePrinter(boss.UserId, added.Id, "Design studio", "Level 2", enabled: false));
+ var changed = store.Printers(boss.UserId).Single();
+ Assert.Equal(("Design studio", "Level 2", false), (changed.Name, changed.Location, changed.Enabled));
+
+ Assert.True(store.DeletePrinter(boss.UserId, added.Id));
+ Assert.Empty(store.Printers(boss.UserId));
+ Assert.False(store.DeletePrinter(boss.UserId, added.Id));
+ Assert.False(store.UpdatePrinter(boss.UserId, "nope", "x", "", true));
+ }
+
+ [Fact]
+ public void One_group_cannot_change_or_see_another_groups_printers()
+ {
+ var store = NewStore();
+ var boss = store.EnsureUser("boss", "Boss", isAdmin: true);
+ var visitor = store.CreateDemoUser(isAdmin: true);
+ var theirs = store.Printers(visitor.UserId).First();
+
+ Assert.False(store.UpdatePrinter(boss.UserId, theirs.Id, "Hijacked", "", true));
+ Assert.False(store.DeletePrinter(boss.UserId, theirs.Id));
+ Assert.Equal("Level 3 East", store.Printers(visitor.UserId).First().Name);
+ }
+
+ [Fact]
+ public void There_is_a_limit_to_how_many_printers_can_be_added()
+ {
+ var store = NewStore();
+ var boss = store.EnsureUser("boss", "Boss", isAdmin: true);
+ for (var i = 0; i < PrintStore.MaxPrinters; i++)
+ Assert.NotNull(store.AddPrinter(boss.UserId, $"P{i}", ""));
+ Assert.Null(store.AddPrinter(boss.UserId, "One too many", ""));
+ }
+
+ [Fact]
+ public void Printing_names_the_printer_used_and_picks_the_first_one_that_is_on_by_default()
+ {
+ var store = NewStore();
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ var first = store.Printers(visitor.UserId).First();
+ store.UpdatePrinter(visitor.UserId, first.Id, first.Name, first.Location, enabled: false);
+
+ var any = store.Release(visitor.UserId, store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList());
+ Assert.Equal(ReleaseOutcome.Printed, any.Outcome);
+ Assert.Equal("Print room", any.PrinterName);
+
+ var chosen = store.Printers(visitor.UserId).Last();
+ var picked = store.Release(visitor.UserId, store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList(), chosen.Id);
+ Assert.Equal(chosen.Name, picked.PrinterName);
+ Assert.Equal(chosen.Name, picked.Printed.Single().PrinterName);
+ }
+
+ [Fact]
+ public void A_switched_off_or_unknown_printer_prints_nothing_and_costs_nothing()
+ {
+ var store = NewStore();
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ var off = store.Printers(visitor.UserId).First();
+ store.UpdatePrinter(visitor.UserId, off.Id, off.Name, off.Location, enabled: false);
+ var ids = store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList();
+ var before = store.GetQuota(visitor.UserId)!.Used;
+
+ Assert.Equal(ReleaseOutcome.PrinterUnavailable, store.Release(visitor.UserId, ids, off.Id).Outcome);
+ Assert.Equal(ReleaseOutcome.PrinterUnavailable, store.Release(visitor.UserId, ids, "no-such-printer").Outcome);
+ Assert.Equal(before, store.GetQuota(visitor.UserId)!.Used);
+ Assert.Equal(ids.Count, store.HeldJobs(visitor.UserId).Count(j => ids.Contains(j.Id)));
+ }
+
+ [Fact]
+ public void A_printer_from_another_group_cannot_be_used()
+ {
+ var store = NewStore();
+ var a = store.CreateDemoUser(isAdmin: false);
+ var b = store.CreateDemoUser(isAdmin: false);
+ var bsPrinter = store.Printers(b.UserId).First();
+ var ids = store.HeldJobs(a.UserId).Take(1).Select(j => j.Id).ToList();
+
+ Assert.Equal(ReleaseOutcome.PrinterUnavailable, store.Release(a.UserId, ids, bsPrinter.Id).Outcome);
+ }
+
+ [Fact]
+ public void With_no_printers_at_all_the_outcome_says_so()
+ {
+ var store = NewStore();
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ foreach (var p in store.Printers(visitor.UserId)) store.DeletePrinter(visitor.UserId, p.Id);
+
+ var ids = store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList();
+ Assert.Equal(ReleaseOutcome.NoPrinter, store.Release(visitor.UserId, ids).Outcome);
+ }
+}
+
+public class PrinterAndQuotaApiTests : IClassFixture
+{
+ private readonly ApiFactory _factory;
+ public PrinterAndQuotaApiTests(ApiFactory factory) => _factory = factory;
+
+ private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
+
+ private async Task SignIn(bool admin)
+ {
+ var client = _factory.CreateClient();
+ var response = await client.PostAsJsonAsync("/api/auth/demo-login", new { admin });
+ var session = (await response.Content.ReadFromJsonAsync(Json))!;
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token);
+ return client;
+ }
+
+ [Fact]
+ public async Task A_visitor_can_list_printers_but_not_manage_them()
+ {
+ var client = await SignIn(admin: false);
+ var list = await client.GetFromJsonAsync("/api/printers", Json);
+ Assert.Equal(3, list.GetArrayLength());
+
+ Assert.Equal(HttpStatusCode.Forbidden,
+ (await client.PostAsJsonAsync("/api/admin/printers", new { name = "X" })).StatusCode);
+ Assert.Equal(HttpStatusCode.Forbidden,
+ (await client.PostAsJsonAsync("/api/admin/default-quota", new { quota = 10 })).StatusCode);
+ Assert.Equal(HttpStatusCode.Forbidden,
+ (await client.PostAsJsonAsync("/api/admin/set-quota-all", new { quota = 10 })).StatusCode);
+ Assert.Equal(HttpStatusCode.Forbidden, (await client.GetAsync("/api/admin/setup")).StatusCode);
+ }
+
+ [Fact]
+ public async Task An_administrator_adds_switches_off_and_removes_a_printer()
+ {
+ var admin = await SignIn(admin: true);
+
+ var added = await admin.PostAsJsonAsync("/api/admin/printers", new { name = "Studio", location = "L1" });
+ Assert.Equal(HttpStatusCode.OK, added.StatusCode);
+ var printer = await added.Content.ReadFromJsonAsync(Json);
+ var id = printer.GetProperty("id").GetString()!;
+
+ var off = await admin.PutAsJsonAsync($"/api/admin/printers/{id}", new { name = "Studio", location = "L1", enabled = false });
+ Assert.Equal(HttpStatusCode.OK, off.StatusCode);
+ var listed = (await admin.GetFromJsonAsync("/api/printers", Json)).EnumerateArray()
+ .First(p => p.GetProperty("id").GetString() == id);
+ Assert.False(listed.GetProperty("enabled").GetBoolean());
+
+ Assert.Equal(HttpStatusCode.OK, (await admin.DeleteAsync($"/api/admin/printers/{id}")).StatusCode);
+ Assert.Equal(HttpStatusCode.NotFound, (await admin.DeleteAsync($"/api/admin/printers/{id}")).StatusCode);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(" ")]
+ public async Task A_printer_needs_a_name(string name)
+ {
+ var admin = await SignIn(admin: true);
+ var response = await admin.PostAsJsonAsync("/api/admin/printers", new { name });
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
+
+ [Theory]
+ [InlineData("/api/admin/default-quota", -1)]
+ [InlineData("/api/admin/default-quota", 10_001)]
+ [InlineData("/api/admin/set-quota-all", -5)]
+ [InlineData("/api/admin/set-quota-all", 1_000_000)]
+ public async Task Quota_rules_outside_the_allowed_range_are_refused(string path, int quota)
+ {
+ var admin = await SignIn(admin: true);
+ Assert.Equal(HttpStatusCode.BadRequest, (await admin.PostAsJsonAsync(path, new { quota })).StatusCode);
+ }
+
+ [Fact]
+ public async Task The_administrators_quota_rules_take_effect()
+ {
+ var admin = await SignIn(admin: true);
+
+ Assert.Equal(HttpStatusCode.OK, (await admin.PostAsJsonAsync("/api/admin/default-quota", new { quota = 77 })).StatusCode);
+ var setup = await admin.GetFromJsonAsync("/api/admin/setup", Json);
+ Assert.Equal(77, setup.GetProperty("defaultQuota").GetInt32());
+
+ var all = await admin.PostAsJsonAsync("/api/admin/set-quota-all", new { quota = 9 });
+ var changed = (await all.Content.ReadFromJsonAsync(Json)).GetProperty("changed").GetInt32();
+ Assert.True(changed >= 1);
+ var users = await admin.GetFromJsonAsync("/api/admin/users", Json);
+ Assert.All(users.EnumerateArray(), u => Assert.Equal(9, u.GetProperty("quota").GetProperty("total").GetInt32()));
+ }
+
+ [Fact]
+ public async Task Printing_on_an_unknown_printer_is_refused_with_a_reason_and_prints_nothing()
+ {
+ var client = await SignIn(admin: false);
+ var held = (await client.GetFromJsonAsync("/api/jobs/held", Json)).EnumerateArray().First();
+ var response = await client.PostAsJsonAsync("/api/jobs/release",
+ new { jobIds = new[] { held.GetProperty("id").GetString() }, printerId = "no-such-printer" });
+
+ Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
+ var body = await response.Content.ReadFromJsonAsync(Json);
+ Assert.Equal("printer_unavailable", body.GetProperty("error").GetString());
+ var stillHeld = (await client.GetFromJsonAsync("/api/jobs/held", Json)).EnumerateArray();
+ Assert.Contains(stillHeld, j => j.GetProperty("id").GetString() == held.GetProperty("id").GetString());
+ }
+
+ [Fact]
+ public async Task Printing_on_a_chosen_printer_says_which_one()
+ {
+ var client = await SignIn(admin: false);
+ var printers = (await client.GetFromJsonAsync("/api/printers", Json)).EnumerateArray().ToList();
+ var reception = printers.First(p => p.GetProperty("name").GetString() == "Reception");
+ var held = (await client.GetFromJsonAsync("/api/jobs/held", Json)).EnumerateArray().First(j => j.GetProperty("pages").GetInt32() <= 12);
+
+ var response = await client.PostAsJsonAsync("/api/jobs/release",
+ new { jobIds = new[] { held.GetProperty("id").GetString() }, printerId = reception.GetProperty("id").GetString() });
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var body = await response.Content.ReadFromJsonAsync(Json);
+ Assert.Equal("Reception", body.GetProperty("printerName").GetString());
+ }
+}
diff --git a/backend.Tests/PullPrintingBackend.Tests.csproj b/backend.Tests/PullPrintingBackend.Tests.csproj
new file mode 100644
index 0000000..0957630
--- /dev/null
+++ b/backend.Tests/PullPrintingBackend.Tests.csproj
@@ -0,0 +1,25 @@
+
+
+
+ net8.0
+ enable
+ enable
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/backend.Tests/StoreTests.cs b/backend.Tests/StoreTests.cs
new file mode 100644
index 0000000..2c523e8
--- /dev/null
+++ b/backend.Tests/StoreTests.cs
@@ -0,0 +1,148 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Options;
+using PullPrintingBackend.Models;
+using PullPrintingBackend.Services;
+
+namespace PullPrintingBackend.Tests;
+
+public class StoreTests
+{
+ private class FakeClock : TimeProvider
+ {
+ public DateTimeOffset Now { get; set; } = new(2026, 10, 22, 9, 0, 0, TimeSpan.Zero);
+ public override DateTimeOffset GetUtcNow() => Now;
+ }
+
+ private class FailingDispatcher : IPrintDispatcher
+ {
+ public void Print(PrintJob job, Printer printer) => throw new InvalidOperationException("printer offline");
+ }
+
+ private static PrintStore NewStore(FakeClock? clock = null, IPrintDispatcher? dispatcher = null, int defaultQuota = 50) =>
+ new(dispatcher ?? new SimulatedPrintDispatcher(NullLogger.Instance),
+ clock ?? new FakeClock(),
+ Options.Create(new WorkspaceOptions { DefaultQuota = defaultQuota }));
+
+ [Fact]
+ public void Idle_sandboxes_are_removed_with_their_documents_but_the_shared_group_stays()
+ {
+ var clock = new FakeClock();
+ var store = NewStore(clock);
+ var root = store.EnsureUser("root", "Root", isAdmin: true);
+ store.EnsureUser("pat", "Pat Doe", isAdmin: false);
+ var visitor = store.CreateDemoUser(isAdmin: false);
+
+ clock.Now += TimeSpan.FromHours(1);
+ Assert.Equal(0, store.Sweep());
+
+ clock.Now += TimeSpan.FromHours(1.5);
+ Assert.Equal(1, store.Sweep());
+ Assert.Null(store.GetQuota(visitor.UserId));
+ Assert.Empty(store.HeldJobs(visitor.UserId));
+ Assert.Contains(store.Users(root.UserId), u => u.Name == "Pat Doe");
+ }
+
+ [Fact]
+ public void An_active_visitor_is_not_swept()
+ {
+ var clock = new FakeClock();
+ var store = NewStore(clock);
+ var visitor = store.CreateDemoUser(isAdmin: false);
+
+ clock.Now += TimeSpan.FromHours(1.5);
+ store.EnsureDemoUser(visitor.UserId, visitor.Name, false); // any request counts as activity
+ clock.Now += TimeSpan.FromHours(1.5);
+ Assert.Equal(0, store.Sweep());
+ Assert.NotNull(store.GetQuota(visitor.UserId));
+ }
+
+ [Fact]
+ public void An_active_admin_keeps_the_whole_sample_group()
+ {
+ var clock = new FakeClock();
+ var store = NewStore(clock);
+ var admin = store.CreateDemoUser(isAdmin: true);
+
+ clock.Now += TimeSpan.FromHours(1.5);
+ store.EnsureDemoUser(admin.UserId, admin.Name, true);
+ clock.Now += TimeSpan.FromHours(1.5); // sample people are 3 hours old, the admin is 1.5
+
+ Assert.Equal(0, store.Sweep());
+ Assert.Equal(4, store.Users(admin.UserId).Count);
+ }
+
+ [Fact]
+ public void An_admin_whose_sandbox_was_cleaned_up_gets_a_fresh_one_on_the_next_request()
+ {
+ var clock = new FakeClock();
+ var store = NewStore(clock);
+ var admin = store.CreateDemoUser(isAdmin: true);
+ clock.Now += TimeSpan.FromHours(3);
+ Assert.Equal(1, store.Sweep());
+ Assert.Empty(store.Users(admin.UserId));
+
+ store.EnsureDemoUser(admin.UserId, admin.Name, true);
+
+ Assert.Equal(4, store.Users(admin.UserId).Count);
+ }
+
+ [Fact]
+ public void The_number_of_sandboxes_is_capped_by_removing_the_least_recent()
+ {
+ var clock = new FakeClock();
+ var store = NewStore(clock);
+ var first = store.CreateDemoUser(isAdmin: false);
+ UserSummary last = first;
+ for (var i = 0; i < PrintStore.MaxVisitors + 5; i++)
+ {
+ clock.Now += TimeSpan.FromSeconds(1);
+ last = store.CreateDemoUser(isAdmin: i % 2 == 0);
+ }
+
+ Assert.Equal(PrintStore.MaxVisitors, store.SandboxCount);
+ Assert.Null(store.GetQuota(first.UserId));
+ Assert.NotNull(store.GetQuota(last.UserId));
+ }
+
+ [Fact]
+ public void Quotas_can_only_be_changed_inside_the_requesters_own_group()
+ {
+ var store = NewStore();
+ var admin = store.CreateDemoUser(isAdmin: true);
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ var alice = store.Users(admin.UserId).First(u => u.Name == "Alice Tan");
+
+ Assert.True(store.SetQuota(admin.UserId, alice.UserId, 99));
+ Assert.Equal(99, store.GetQuota(alice.UserId)!.Total);
+ Assert.False(store.SetQuota(admin.UserId, visitor.UserId, 1));
+ Assert.Equal(50, store.GetQuota(visitor.UserId)!.Total);
+ Assert.False(store.SetQuota("nobody", alice.UserId, 1));
+ }
+
+ [Fact]
+ public void A_job_the_printer_rejects_is_marked_failed_and_costs_no_pages()
+ {
+ var store = NewStore(dispatcher: new FailingDispatcher());
+ var visitor = store.CreateDemoUser(isAdmin: false);
+ var job = store.HeldJobs(visitor.UserId).First();
+
+ var result = store.Release(visitor.UserId, new[] { job.Id });
+
+ Assert.Empty(result.Printed);
+ Assert.Equal(12, store.GetQuota(visitor.UserId)!.Used);
+ var stored = store.AllJobs(visitor.UserId).Single(j => j.Id == job.Id);
+ Assert.Equal(JobStatus.Failed, stored.Status);
+ Assert.Equal("printer offline", stored.FailureReason);
+ Assert.DoesNotContain(store.HeldJobs(visitor.UserId), j => j.Id == job.Id);
+ }
+
+ [Fact]
+ public void Signing_in_with_a_new_account_creates_a_user_with_the_default_quota()
+ {
+ var store = NewStore();
+ var user = store.EnsureUser("entra-oid-1", "Dana Cole", isAdmin: false);
+ Assert.Equal(50, user.Quota.Total);
+ Assert.Equal(0, user.Quota.Used);
+ Assert.Empty(store.HeldJobs("entra-oid-1"));
+ }
+}
diff --git a/backend.Tests/WorkspaceTests.cs b/backend.Tests/WorkspaceTests.cs
new file mode 100644
index 0000000..a71a9e8
--- /dev/null
+++ b/backend.Tests/WorkspaceTests.cs
@@ -0,0 +1,617 @@
+using System.IdentityModel.Tokens.Jwt;
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Security.Claims;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Microsoft.AspNetCore.Authentication.OpenIdConnect;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.IdentityModel.Tokens;
+using PullPrintingBackend.Controllers;
+using PullPrintingBackend.Services;
+
+namespace PullPrintingBackend.Tests;
+
+// ---- the rules that decide whether a work account is let in ---------------
+
+public class WorkspaceRuleTests
+{
+ private static ClaimsPrincipal Account(params (string Type, string Value)[] claims) =>
+ new(new ClaimsIdentity(claims.Select(c => new Claim(c.Type, c.Value)), "test"));
+
+ private static WorkspaceOptions Google(string? admins = null) => new()
+ {
+ Provider = "Google", ClientId = "c", ClientSecret = "s", Domain = "example.com", Admins = admins,
+ };
+
+ private static WorkspaceOptions Microsoft(string? domain = null, string? admins = null) => new()
+ {
+ Provider = "Microsoft", ClientId = "c", ClientSecret = "s", TenantId = "tenant-1", Domain = domain, Admins = admins,
+ };
+
+ [Fact]
+ public void A_Google_account_in_the_domain_is_let_in()
+ {
+ var (user, denied) = WorkspaceIdentity.Map(Google(), Account(
+ ("sub", "123"), ("email", "Pat.Doe@Example.com"), ("email_verified", "true"), ("hd", "example.com"), ("name", "Pat Doe")));
+
+ Assert.Null(denied);
+ Assert.Equal("g-123", user!.Id);
+ Assert.Equal("Pat Doe", user.Name);
+ Assert.Equal("pat.doe@example.com", user.Email);
+ Assert.False(user.IsAdmin);
+ }
+
+ [Theory]
+ [InlineData("boss@example.com")]
+ [InlineData("Boss@Example.com")]
+ [InlineData("other@example.com, boss@example.com")]
+ [InlineData("other@example.com;boss@example.com")]
+ [InlineData("other@example.com boss@example.com")]
+ public void Administrators_are_found_by_email_however_the_list_is_written(string admins)
+ {
+ var (user, _) = WorkspaceIdentity.Map(Google(admins), Account(
+ ("sub", "1"), ("email", "boss@example.com"), ("email_verified", "true"), ("hd", "example.com")));
+ Assert.True(user!.IsAdmin);
+ }
+
+ [Fact]
+ public void A_personal_Google_account_is_turned_away()
+ {
+ // Personal accounts have no "hd" (hosted domain) claim.
+ var (user, denied) = WorkspaceIdentity.Map(Google(), Account(
+ ("sub", "1"), ("email", "pat@gmail.com"), ("email_verified", "true")));
+ Assert.Null(user);
+ Assert.Equal("wrong_account", denied!.Code);
+ Assert.Contains("example.com", denied.Message);
+ }
+
+ [Fact]
+ public void A_Google_account_from_another_organisation_is_turned_away()
+ {
+ var (user, denied) = WorkspaceIdentity.Map(Google(), Account(
+ ("sub", "1"), ("email", "pat@other.org"), ("email_verified", "true"), ("hd", "other.org")));
+ Assert.Null(user);
+ Assert.Equal("wrong_account", denied!.Code);
+ }
+
+ [Fact]
+ public void An_unverified_Google_email_is_turned_away()
+ {
+ var (user, denied) = WorkspaceIdentity.Map(Google(), Account(
+ ("sub", "1"), ("email", "pat@example.com"), ("email_verified", "false"), ("hd", "example.com")));
+ Assert.Null(user);
+ Assert.Equal("unverified_email", denied!.Code);
+ }
+
+ [Fact]
+ public void A_Google_domain_claim_alone_is_not_enough_the_email_must_match_too()
+ {
+ var (user, denied) = WorkspaceIdentity.Map(Google(), Account(
+ ("sub", "1"), ("email", "pat@evil.test"), ("email_verified", "true"), ("hd", "example.com")));
+ Assert.Null(user);
+ Assert.Equal("wrong_account", denied!.Code);
+ }
+
+ [Fact]
+ public void A_Microsoft_account_in_the_tenant_is_let_in_and_the_app_role_makes_an_administrator()
+ {
+ var (user, denied) = WorkspaceIdentity.Map(Microsoft(), Account(
+ ("oid", "abc"), ("tid", "tenant-1"), ("preferred_username", "Pat@Contoso.com"), ("name", "Pat Doe"), ("roles", "PullPrint.Admin")));
+
+ Assert.Null(denied);
+ Assert.Equal("m-abc", user!.Id);
+ Assert.Equal("pat@contoso.com", user.Email);
+ Assert.True(user.IsAdmin);
+ }
+
+ [Fact]
+ public void A_Microsoft_account_from_another_tenant_is_turned_away()
+ {
+ var (user, denied) = WorkspaceIdentity.Map(Microsoft(), Account(
+ ("oid", "abc"), ("tid", "someone-else"), ("preferred_username", "pat@contoso.com")));
+ Assert.Null(user);
+ Assert.Equal("wrong_account", denied!.Code);
+ }
+
+ [Fact]
+ public void Microsoft_sign_in_can_be_limited_to_one_email_domain()
+ {
+ var options = Microsoft(domain: "contoso.com");
+ var inside = WorkspaceIdentity.Map(options, Account(("oid", "1"), ("tid", "tenant-1"), ("preferred_username", "a@contoso.com")));
+ var guest = WorkspaceIdentity.Map(options, Account(("oid", "2"), ("tid", "tenant-1"), ("preferred_username", "b@partner.org")));
+ var noEmail = WorkspaceIdentity.Map(options, Account(("oid", "3"), ("tid", "tenant-1")));
+
+ Assert.NotNull(inside.User);
+ Assert.Equal("wrong_account", guest.Denied!.Code);
+ Assert.Equal("wrong_account", noEmail.Denied!.Code);
+ }
+
+ [Fact]
+ public void An_account_with_no_identity_is_turned_away()
+ {
+ Assert.Equal("no_identity", WorkspaceIdentity.Map(Microsoft(), Account(("name", "x"))).Denied!.Code);
+ Assert.Equal("no_identity", WorkspaceIdentity.Map(Google(), Account(("name", "x"))).Denied!.Code);
+ }
+
+ [Fact]
+ public void Accounts_from_different_providers_never_share_an_id()
+ {
+ var google = WorkspaceIdentity.Map(Google(), Account(("sub", "42"), ("email", "a@example.com"), ("email_verified", "true"), ("hd", "example.com")));
+ var microsoft = WorkspaceIdentity.Map(Microsoft(), Account(("oid", "42"), ("tid", "tenant-1")));
+ Assert.NotEqual(google.User!.Id, microsoft.User!.Id);
+ }
+}
+
+public class WorkspaceSettingsTests
+{
+ [Fact]
+ public void Nothing_is_wrong_when_nothing_is_set_up()
+ {
+ var options = new WorkspaceOptions();
+ Assert.False(options.IsConfigured);
+ Assert.False(options.Enabled);
+ Assert.Empty(options.Problems());
+ }
+
+ [Fact]
+ public void Missing_pieces_are_named_in_plain_words()
+ {
+ var google = new WorkspaceOptions { Provider = "Google" }.Problems();
+ Assert.Contains(google, p => p.Contains("Workspace__ClientId"));
+ Assert.Contains(google, p => p.Contains("Workspace__ClientSecret"));
+ Assert.Contains(google, p => p.Contains("Workspace__Domain") && p.Contains("any Google account"));
+
+ var microsoft = new WorkspaceOptions { Provider = "Microsoft", ClientId = "c", ClientSecret = "s" }.Problems();
+ Assert.Single(microsoft);
+ Assert.Contains("Workspace__TenantId", microsoft[0]);
+
+ Assert.Contains(new WorkspaceOptions { Provider = "Okta", ClientId = "c", ClientSecret = "s" }.Problems(),
+ p => p.Contains("Microsoft or Google"));
+ }
+
+ [Fact]
+ public void A_complete_set_is_enabled_and_names_the_right_sign_in_address()
+ {
+ var google = new WorkspaceOptions { Provider = "google", ClientId = "c", ClientSecret = "s", Domain = "example.com" };
+ Assert.True(google.Enabled);
+ Assert.Equal("Google", google.ProviderName);
+ Assert.Equal("https://accounts.google.com", google.EffectiveAuthority);
+
+ var microsoft = new WorkspaceOptions { Provider = "MICROSOFT", ClientId = "c", ClientSecret = "s", TenantId = "t-1" };
+ Assert.True(microsoft.Enabled);
+ Assert.Equal("https://login.microsoftonline.com/t-1/v2.0", microsoft.EffectiveAuthority);
+ }
+
+ [Theory]
+ [InlineData("/", "/")]
+ [InlineData(null, "/")]
+ [InlineData("", "/")]
+ [InlineData("/?printer=abc123", "/?printer=abc123")]
+ [InlineData("/panel?printer=abc#frag", "/panel?printer=abc")]
+ [InlineData("//evil.example", "/")]
+ [InlineData("https://evil.example", "/")]
+ [InlineData("/\\evil.example", "/")]
+ [InlineData("javascript:alert(1)", "/")]
+ [InlineData("/ok\r\nSet-Cookie: x=1", "/")]
+ public void Sign_in_can_only_send_people_back_to_a_page_on_this_site(string? asked, string expected) =>
+ Assert.Equal(expected, AuthController.SafeReturnPath(asked));
+}
+
+// ---- the whole sign-in round trip, against a pretend Microsoft or Google ---
+
+/// Plays the part of the provider's sign-in service: its settings, its keys and its token exchange.
+public sealed class FakeIdentityProvider : HttpMessageHandler
+{
+ public const string Issuer = "https://idp.test";
+ public const string ClientId = "test-client";
+ public const string ClientSecret = "test-secret";
+
+ private readonly RSA _rsa = RSA.Create(2048);
+ private readonly RsaSecurityKey _key;
+ private readonly Dictionary _codes = new();
+
+ public bool SawProofKey { get; private set; }
+ public int TokenRequests { get; private set; }
+
+ public FakeIdentityProvider() => _key = new RsaSecurityKey(_rsa) { KeyId = "k1" };
+
+ /// The person approves on the provider's page: returns the address the browser is sent back to.
+ public Uri Approve(Uri authorizeAddress, params Claim[] claims)
+ {
+ var query = System.Web.HttpUtility.ParseQueryString(authorizeAddress.Query);
+ var code = Guid.NewGuid().ToString("N");
+ _codes[code] = (query["nonce"]!, claims);
+ return new Uri($"{query["redirect_uri"]}?code={code}&state={Uri.EscapeDataString(query["state"]!)}");
+ }
+
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct)
+ {
+ var path = request.RequestUri!.AbsolutePath;
+ HttpResponseMessage Json(object body) => new(HttpStatusCode.OK)
+ {
+ Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"),
+ };
+
+ if (path.EndsWith("/.well-known/openid-configuration"))
+ return Task.FromResult(Json(new
+ {
+ issuer = Issuer,
+ authorization_endpoint = Issuer + "/authorize",
+ token_endpoint = Issuer + "/token",
+ jwks_uri = Issuer + "/jwks",
+ response_types_supported = new[] { "code" },
+ subject_types_supported = new[] { "public" },
+ id_token_signing_alg_values_supported = new[] { "RS256" },
+ }));
+
+ if (path == "/jwks")
+ {
+ var p = _rsa.ExportParameters(false);
+ return Task.FromResult(Json(new
+ {
+ keys = new[]
+ {
+ new { kty = "RSA", use = "sig", alg = "RS256", kid = "k1",
+ n = Base64UrlEncoder.Encode(p.Modulus), e = Base64UrlEncoder.Encode(p.Exponent) },
+ },
+ }));
+ }
+
+ if (path == "/token")
+ {
+ TokenRequests++;
+ var form = request.Content!.ReadAsStringAsync(ct).Result
+ .Split('&').Select(x => x.Split('=', 2))
+ .ToDictionary(x => Uri.UnescapeDataString(x[0]), x => Uri.UnescapeDataString(x[1].Replace('+', ' ')));
+ if (form["client_secret"] != ClientSecret || !_codes.TryGetValue(form["code"], out var pending))
+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)
+ {
+ Content = new StringContent("{\"error\":\"invalid_grant\"}", Encoding.UTF8, "application/json"),
+ });
+ _codes.Remove(form["code"]);
+ SawProofKey = form.ContainsKey("code_verifier");
+
+ var claims = (pending.Claims.Any(c => c.Type == "sub") ? pending.Claims : pending.Claims.Append(new Claim("sub", "sub-" + Guid.NewGuid())))
+ .Append(new Claim("nonce", pending.Nonce))
+ .Append(new Claim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));
+ var token = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
+ Issuer, ClientId, claims, DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow.AddMinutes(10),
+ new SigningCredentials(_key, SecurityAlgorithms.RsaSha256)));
+ return Task.FromResult(Json(new { id_token = token, access_token = "at", token_type = "Bearer", expires_in = 3600 }));
+ }
+
+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound));
+ }
+}
+
+public class WorkspaceFactory : WebApplicationFactory
+{
+ public FakeIdentityProvider Idp { get; } = new();
+ private readonly Dictionary _settings;
+
+ public WorkspaceFactory(string provider, Dictionary? extra = null)
+ {
+ _settings = new Dictionary
+ {
+ ["Workspace:Provider"] = provider,
+ ["Workspace:ClientId"] = FakeIdentityProvider.ClientId,
+ ["Workspace:ClientSecret"] = FakeIdentityProvider.ClientSecret,
+ ["Workspace:Authority"] = FakeIdentityProvider.Issuer,
+ ["Workspace:Admins"] = "boss@example.com",
+ ["Workspace:DefaultQuota"] = "40",
+ ["Demo:Enabled"] = "false",
+ ["Auth:SigningKey"] = ApiFactory.Key,
+ ["RateLimit:LoginPerMinute"] = "1000",
+ ["RateLimit:PerMinute"] = "100000",
+ };
+ if (provider == "Google") _settings["Workspace:Domain"] = "example.com";
+ if (provider == "Microsoft") _settings["Workspace:TenantId"] = "tenant-1";
+ foreach (var (key, value) in extra ?? new()) _settings[key] = value;
+ }
+
+ protected override void ConfigureWebHost(IWebHostBuilder builder)
+ {
+ builder.UseEnvironment("Testing");
+ builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(_settings));
+ builder.ConfigureServices(services =>
+ services.Configure(AuthController.WorkspaceScheme, o => o.BackchannelHttpHandler = Idp));
+ }
+
+ public HttpClient Browser() => CreateClient(new WebApplicationFactoryClientOptions
+ {
+ AllowAutoRedirect = false,
+ HandleCookies = true,
+ });
+
+ ///
+ /// Plays a person signing in: the app sends them to the provider, they approve, the provider sends them
+ /// back, and the app sends them on to the page with a token (or an error) in the address fragment.
+ ///
+ public async Task SignIn(HttpClient browser, string? returnTo, params Claim[] account)
+ {
+ var start = await browser.GetAsync("/api/auth/login" + (returnTo is null ? "" : "?returnTo=" + Uri.EscapeDataString(returnTo)));
+ Assert.Equal(HttpStatusCode.Redirect, start.StatusCode);
+ Assert.StartsWith(FakeIdentityProvider.Issuer + "/authorize", start.Headers.Location!.ToString());
+
+ var back = await browser.GetAsync(Idp.Approve(start.Headers.Location, account));
+ Assert.Equal(HttpStatusCode.Redirect, back.StatusCode);
+
+ var finish = await browser.GetAsync(back.Headers.Location);
+ Assert.Equal(HttpStatusCode.Redirect, finish.StatusCode);
+ return finish.Headers.Location!.OriginalString;
+ }
+
+ public static string TokenIn(string address) => address[(address.IndexOf("#token=", StringComparison.Ordinal) + 7)..];
+
+ public HttpClient Api(string token)
+ {
+ var client = CreateClient();
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
+ return client;
+ }
+}
+
+public class WorkspaceSignInTests
+{
+ private static Claim[] GoogleAccount(string email, string hd = "example.com", string verified = "true", string sub = "sub-1") => new[]
+ {
+ new Claim("sub", sub), new Claim("email", email), new Claim("email_verified", verified),
+ new Claim("hd", hd), new Claim("name", "Pat Doe"),
+ };
+
+ [Fact]
+ public async Task The_sign_in_screen_is_told_which_work_account_to_offer()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var config = await factory.CreateClient().GetFromJsonAsync("/api/auth/config");
+ Assert.Equal("google", config.GetProperty("provider").GetString());
+ Assert.Equal("Google", config.GetProperty("providerName").GetString());
+ Assert.Equal("example.com", config.GetProperty("domain").GetString());
+ Assert.False(config.GetProperty("demo").GetBoolean());
+ }
+
+ [Fact]
+ public async Task A_person_in_the_domain_signs_in_and_gets_a_working_session()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var browser = factory.Browser();
+
+ var landed = await factory.SignIn(browser, null, GoogleAccount("pat@example.com"));
+
+ Assert.StartsWith("/#token=", landed);
+ Assert.True(factory.Idp.SawProofKey, "The code exchange should use PKCE.");
+
+ var api = factory.Api(WorkspaceFactory.TokenIn(landed));
+ var me = await api.GetFromJsonAsync("/api/auth/me");
+ Assert.Equal("Pat Doe", me.GetProperty("name").GetString());
+ Assert.False(me.GetProperty("isAdmin").GetBoolean());
+
+ // First sign-in creates the person with the workspace's default quota, and an empty list.
+ var quota = await api.GetFromJsonAsync("/api/jobs/quota");
+ Assert.Equal(40, quota.GetProperty("total").GetInt32());
+ Assert.Equal(0, quota.GetProperty("used").GetInt32());
+ Assert.Empty((await api.GetFromJsonAsync("/api/jobs/held")).EnumerateArray());
+ }
+
+ [Fact]
+ public async Task The_same_person_signing_in_again_is_the_same_person()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var first = await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@example.com"));
+ var second = await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@example.com"));
+
+ var a = await factory.Api(WorkspaceFactory.TokenIn(first)).GetFromJsonAsync("/api/auth/me");
+ var b = await factory.Api(WorkspaceFactory.TokenIn(second)).GetFromJsonAsync("/api/auth/me");
+ Assert.Equal(a.GetProperty("userId").GetString(), b.GetProperty("userId").GetString());
+ }
+
+ [Fact]
+ public async Task An_administrator_in_the_list_gets_the_administrator_screen_and_nobody_else_does()
+ {
+ using var factory = new WorkspaceFactory("Google");
+
+ var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("Boss@example.com", sub: "boss"));
+ var bossApi = factory.Api(WorkspaceFactory.TokenIn(boss));
+ Assert.True((await bossApi.GetFromJsonAsync("/api/auth/me")).GetProperty("isAdmin").GetBoolean());
+ Assert.Equal(HttpStatusCode.OK, (await bossApi.GetAsync("/api/admin/setup")).StatusCode);
+
+ var pat = await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@example.com"));
+ var patApi = factory.Api(WorkspaceFactory.TokenIn(pat));
+ Assert.Equal(HttpStatusCode.Forbidden, (await patApi.GetAsync("/api/admin/setup")).StatusCode);
+ Assert.Equal(HttpStatusCode.Forbidden, (await patApi.GetAsync("/api/admin/users")).StatusCode);
+ }
+
+ [Fact]
+ public async Task The_administrator_sees_people_as_they_sign_in_and_can_set_their_quota()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var pat = await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@example.com"));
+ var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss"));
+ var bossApi = factory.Api(WorkspaceFactory.TokenIn(boss));
+
+ var people = (await bossApi.GetFromJsonAsync("/api/admin/users")).EnumerateArray().ToList();
+ var person = Assert.Single(people);
+ Assert.Equal("pat@example.com", person.GetProperty("email").GetString());
+
+ var id = person.GetProperty("userId").GetString();
+ Assert.Equal(HttpStatusCode.OK, (await bossApi.PostAsJsonAsync("/api/admin/set-quota", new { userId = id, quota = 15 })).StatusCode);
+ var quota = await factory.Api(WorkspaceFactory.TokenIn(pat)).GetFromJsonAsync("/api/jobs/quota");
+ Assert.Equal(15, quota.GetProperty("total").GetInt32());
+ }
+
+ [Theory]
+ [InlineData("pat@gmail.com", "", "true", "wrong_account")] // a personal account has no domain
+ [InlineData("pat@other.org", "other.org", "true", "wrong_account")] // another organisation
+ [InlineData("pat@example.com", "example.com", "false", "unverified_email")]
+ public async Task Accounts_that_do_not_belong_are_turned_away_with_a_reason(string email, string hd, string verified, string code)
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var claims = hd == ""
+ ? new[] { new Claim("sub", "x"), new Claim("email", email), new Claim("email_verified", verified), new Claim("name", "Pat") }
+ : GoogleAccount(email, hd, verified);
+
+ var landed = await factory.SignIn(factory.Browser(), null, claims);
+
+ Assert.Equal($"/#error={code}", landed);
+ }
+
+ [Fact]
+ public async Task A_turned_away_account_gets_no_session_and_is_not_added()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@other.org", "other.org"));
+
+ var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss"));
+ var people = await factory.Api(WorkspaceFactory.TokenIn(boss)).GetFromJsonAsync("/api/admin/users");
+ Assert.Empty(people.EnumerateArray());
+ }
+
+ [Fact]
+ public async Task The_page_the_person_came_from_is_kept_such_as_a_printer_panels_address()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var landed = await factory.SignIn(factory.Browser(), "/?printer=abc123", GoogleAccount("pat@example.com"));
+ Assert.StartsWith("/?printer=abc123#token=", landed);
+ }
+
+ [Theory]
+ [InlineData("//evil.example/steal")]
+ [InlineData("https://evil.example/")]
+ public async Task Sign_in_cannot_be_used_to_send_people_to_another_site(string returnTo)
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var landed = await factory.SignIn(factory.Browser(), returnTo, GoogleAccount("pat@example.com"));
+ Assert.StartsWith("/#token=", landed);
+ }
+
+ [Fact]
+ public async Task A_forged_return_from_the_provider_is_refused()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var browser = factory.Browser();
+ var response = await browser.GetAsync("/api/auth/callback?code=made-up&state=made-up");
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Equal("/#error=sign_in_failed", response.Headers.Location!.OriginalString);
+ Assert.Equal(0, factory.Idp.TokenRequests); // never even reached the code exchange
+ }
+
+ [Fact]
+ public async Task Finishing_sign_in_without_having_started_it_gives_nothing()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var response = await factory.Browser().GetAsync("/api/auth/complete");
+ Assert.Equal("/#error=sign_in_failed", response.Headers.Location!.OriginalString);
+ }
+
+ [Fact]
+ public async Task A_Microsoft_account_signs_in_and_the_app_role_makes_an_administrator()
+ {
+ using var factory = new WorkspaceFactory("Microsoft");
+ var landed = await factory.SignIn(factory.Browser(), null,
+ new Claim("oid", "o-1"), new Claim("tid", "tenant-1"), new Claim("preferred_username", "ada@contoso.com"),
+ new Claim("name", "Ada Lovelace"), new Claim("roles", "PullPrint.Admin"));
+
+ var me = await factory.Api(WorkspaceFactory.TokenIn(landed)).GetFromJsonAsync("/api/auth/me");
+ Assert.Equal("Ada Lovelace", me.GetProperty("name").GetString());
+ Assert.True(me.GetProperty("isAdmin").GetBoolean());
+ }
+
+ [Fact]
+ public async Task A_Microsoft_account_from_another_tenant_is_turned_away()
+ {
+ using var factory = new WorkspaceFactory("Microsoft");
+ var landed = await factory.SignIn(factory.Browser(), null,
+ new Claim("oid", "o-1"), new Claim("tid", "someone-elses-tenant"), new Claim("preferred_username", "x@elsewhere.com"));
+ Assert.Equal("/#error=wrong_account", landed);
+ }
+
+ [Fact]
+ public async Task Setup_check_names_the_address_to_register_and_what_needs_attention()
+ {
+ using var factory = new WorkspaceFactory("Google", new() { ["Demo:Enabled"] = "true", ["Auth:SigningKey"] = "" });
+ var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss"));
+ var setup = await factory.Api(WorkspaceFactory.TokenIn(boss)).GetFromJsonAsync("/api/admin/setup");
+
+ Assert.Equal("Google", setup.GetProperty("provider").GetString());
+ Assert.Equal("example.com", setup.GetProperty("domain").GetString());
+ Assert.Equal(40, setup.GetProperty("defaultQuota").GetInt32());
+ Assert.EndsWith("/api/auth/callback", setup.GetProperty("redirectUri").GetString());
+
+ var warnings = string.Join("\n", setup.GetProperty("warnings").EnumerateArray().Select(w => w.GetString()));
+ Assert.Contains("No printers yet", warnings);
+ Assert.Contains("Demo sign-in is on", warnings);
+ Assert.Contains("Auth__SigningKey is not set", warnings);
+ }
+
+ [Fact]
+ public async Task A_clean_setup_has_no_warnings_once_a_printer_is_added()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss"));
+ var api = factory.Api(WorkspaceFactory.TokenIn(boss));
+ Assert.Equal(HttpStatusCode.OK, (await api.PostAsJsonAsync("/api/admin/printers", new { name = "Level 3 East", location = "Third floor" })).StatusCode);
+
+ var setup = await api.GetFromJsonAsync("/api/admin/setup");
+ Assert.Empty(setup.GetProperty("warnings").EnumerateArray());
+ Assert.Equal(1, setup.GetProperty("printers").GetInt32());
+ }
+
+ [Fact]
+ public async Task Half_finished_settings_switch_work_sign_in_off_and_say_why()
+ {
+ using var factory = new WorkspaceFactory("Google", new() { ["Workspace:ClientSecret"] = "", ["Demo:Enabled"] = "true" });
+
+ var config = await factory.CreateClient().GetFromJsonAsync("/api/auth/config");
+ Assert.Equal("none", config.GetProperty("provider").GetString());
+ Assert.Equal(HttpStatusCode.NotFound, (await factory.Browser().GetAsync("/api/auth/login")).StatusCode);
+ Assert.Equal(HttpStatusCode.NotFound, (await factory.Browser().GetAsync("/api/auth/callback?code=x&state=y")).StatusCode);
+
+ // The demo still works, and its administrator is told what is wrong.
+ var login = await factory.CreateClient().PostAsJsonAsync("/api/auth/demo-login", new { admin = true });
+ var token = (await login.Content.ReadFromJsonAsync()).GetProperty("token").GetString()!;
+ var setup = await factory.Api(token).GetFromJsonAsync("/api/admin/setup");
+ Assert.Contains("Workspace__ClientSecret", string.Join("\n", setup.GetProperty("warnings").EnumerateArray().Select(w => w.GetString())));
+ }
+
+ [Fact]
+ public async Task Work_sign_in_is_off_when_nothing_is_set_up()
+ {
+ using var factory = new ApiFactory();
+ Assert.Equal(HttpStatusCode.NotFound, (await factory.CreateClient().GetAsync("/api/auth/login")).StatusCode);
+ var config = await factory.CreateClient().GetFromJsonAsync("/api/auth/config");
+ Assert.Equal("none", config.GetProperty("provider").GetString());
+ Assert.True(config.GetProperty("demo").GetBoolean());
+ }
+
+ [Fact]
+ public async Task A_work_session_stops_working_if_work_sign_in_is_switched_off()
+ {
+ string token;
+ using (var on = new WorkspaceFactory("Google"))
+ token = WorkspaceFactory.TokenIn(await on.SignIn(on.Browser(), null, GoogleAccount("pat@example.com")));
+
+ using var off = new ApiFactory(); // same signing key, no work sign-in
+ var client = off.CreateClient();
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
+ Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/jobs/quota")).StatusCode);
+ }
+
+ [Fact]
+ public async Task A_workspace_starts_with_no_sample_people_and_no_printers()
+ {
+ using var factory = new WorkspaceFactory("Google");
+ var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss"));
+ var api = factory.Api(WorkspaceFactory.TokenIn(boss));
+
+ Assert.Empty((await api.GetFromJsonAsync("/api/admin/users")).EnumerateArray());
+ Assert.Empty((await api.GetFromJsonAsync("/api/jobs")).EnumerateArray());
+ Assert.Empty((await api.GetFromJsonAsync("/api/printers")).EnumerateArray());
+ Assert.Equal(HttpStatusCode.NotFound, (await api.PostAsync("/api/jobs/sample", null)).StatusCode); // demo is off
+ }
+}
diff --git a/backend/Program.cs b/backend/Program.cs
index f20975f..dc9377f 100644
--- a/backend/Program.cs
+++ b/backend/Program.cs
@@ -1,10 +1,233 @@
+using System.Security.Claims;
+using System.Threading.RateLimiting;
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.AspNetCore.Authentication.OpenIdConnect;
+using Microsoft.AspNetCore.HttpOverrides;
+using Microsoft.AspNetCore.RateLimiting;
+using Microsoft.Extensions.Options;
+using Microsoft.IdentityModel.Protocols.OpenIdConnect;
+using Microsoft.IdentityModel.Tokens;
+using PullPrintingBackend.Controllers;
+using PullPrintingBackend.Services;
+
var builder = WebApplication.CreateBuilder(args);
-builder.Services.AddSingleton();
-builder.Services.AddSingleton();
-builder.Services.AddSingleton();
+
+builder.Services.Configure(builder.Configuration.GetSection("Demo"));
+builder.Services.Configure(builder.Configuration.GetSection("Auth"));
+builder.Services.Configure(builder.Configuration.GetSection("Workspace"));
+
+builder.Services.AddSingleton(TimeProvider.System);
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddHostedService();
builder.Services.AddControllers();
+// --- Authentication -------------------------------------------------------
+// Everyone ends up with the server's own session token (see AppTokenService), whether they signed in
+// to a demo sandbox or with their organisation's Microsoft or Google work account. The work-account
+// step is a normal OpenID Connect sign-in done here on the server, so the app needs no provider SDK.
+builder.Services.AddAuthentication("Bearer")
+ .AddJwtBearer("Bearer", options =>
+ {
+ options.MapInboundClaims = false;
+ options.Events = new JwtBearerEvents
+ {
+ OnTokenValidated = context =>
+ {
+ var services = context.HttpContext.RequestServices;
+ var principal = context.Principal!;
+ var store = services.GetRequiredService();
+ var name = principal.FindFirstValue(Claims.Name) ?? "Signed-in user";
+ var isAdmin = principal.IsInRole(Claims.AdminRole);
+ switch (principal.FindFirstValue(Claims.Kind))
+ {
+ case Claims.DemoKind when services.GetRequiredService>().Value.Enabled:
+ store.EnsureDemoUser(principal.UserId(), name, isAdmin);
+ break;
+ case Claims.WorkspaceKind when services.GetRequiredService>().Value.Enabled:
+ store.EnsureUser(principal.UserId(), name, isAdmin);
+ break;
+ default:
+ // The way this token was issued has been switched off since.
+ context.Fail("That kind of sign-in is switched off.");
+ break;
+ }
+ return Task.CompletedTask;
+ },
+ };
+ })
+ .AddCookie(AuthController.ExternalScheme, options =>
+ {
+ // Holds who the work account said you are for the few seconds between the two redirects.
+ options.Cookie.Name = ".pullprint.external";
+ options.Cookie.SameSite = SameSiteMode.Lax;
+ options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
+ options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
+ options.SlidingExpiration = false;
+ options.Events.OnRedirectToLogin = context =>
+ {
+ context.Response.StatusCode = StatusCodes.Status401Unauthorized;
+ return Task.CompletedTask;
+ };
+ })
+ // Always registered, but only used when Workspace settings are complete (see AuthController.Login).
+ // Its settings are read when it is first used, so it needs nothing when the server runs on demo sign-in alone.
+ .AddOpenIdConnect(AuthController.WorkspaceScheme, _ => { });
+
+builder.Services.AddOptions("Bearer")
+ .Configure((options, tokens) =>
+ {
+ options.TokenValidationParameters = new TokenValidationParameters
+ {
+ ValidIssuer = AppTokenService.Issuer,
+ ValidAudience = AppTokenService.Audience,
+ IssuerSigningKey = tokens.Key,
+ ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 },
+ NameClaimType = Claims.Name,
+ RoleClaimType = Claims.Role,
+ ClockSkew = TimeSpan.FromMinutes(1),
+ };
+ });
+
+builder.Services.AddOptions(AuthController.WorkspaceScheme)
+ .Configure>((options, workspace) =>
+ {
+ var w = workspace.Value;
+ options.Authority = w.EffectiveAuthority;
+ options.ClientId = string.IsNullOrWhiteSpace(w.ClientId) ? "not-configured" : w.ClientId;
+ options.ClientSecret = string.IsNullOrWhiteSpace(w.ClientSecret) ? "not-configured" : w.ClientSecret;
+ options.RequireHttpsMetadata = w.RequireHttpsMetadata;
+ options.ResponseType = OpenIdConnectResponseType.Code;
+ options.UsePkce = true;
+ options.CallbackPath = "/api/auth/callback";
+ options.SignInScheme = AuthController.ExternalScheme;
+ options.MapInboundClaims = false;
+ options.SaveTokens = false;
+ options.GetClaimsFromUserInfoEndpoint = false;
+ options.Scope.Clear();
+ options.Scope.Add("openid");
+ options.Scope.Add("profile");
+ options.Scope.Add("email");
+ options.CorrelationCookie.SameSite = SameSiteMode.Lax;
+ options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
+ options.NonceCookie.SameSite = SameSiteMode.Lax;
+ options.NonceCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
+ options.TokenValidationParameters.NameClaimType = Claims.Name;
+ options.Events = new OpenIdConnectEvents
+ {
+ OnRedirectToIdentityProvider = context =>
+ {
+ context.ProtocolMessage.Prompt = "select_account";
+ // A hint that limits the account chooser to the organisation. The server still checks the account itself.
+ if (w.IsGoogle && !string.IsNullOrWhiteSpace(w.Domain))
+ context.ProtocolMessage.SetParameter("hd", w.Domain!.TrimStart('@'));
+ return Task.CompletedTask;
+ },
+ OnRemoteFailure = context =>
+ {
+ context.Response.Redirect("/#error=sign_in_failed");
+ context.HandleResponse();
+ return Task.CompletedTask;
+ },
+ };
+ });
+
+builder.Services.AddAuthorization(options =>
+ options.AddPolicy(Claims.AdminPolicy, policy => policy.RequireRole(Claims.AdminRole)));
+
+// --- Abuse limits ---------------------------------------------------------
+builder.Services.AddRateLimiter(_ => { });
+builder.Services.AddOptions().Configure((options, config) =>
+{
+ var perMinute = config.GetValue("RateLimit:PerMinute", 300);
+ var loginsPerMinute = config.GetValue("RateLimit:LoginPerMinute", 20);
+ options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
+ options.GlobalLimiter = PartitionedRateLimiter.Create(context =>
+ RateLimitPartition.GetFixedWindowLimiter(
+ context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
+ _ => new FixedWindowRateLimiterOptions { PermitLimit = perMinute, Window = TimeSpan.FromMinutes(1) }));
+ options.AddPolicy("login", context =>
+ RateLimitPartition.GetFixedWindowLimiter(
+ context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
+ _ => new FixedWindowRateLimiterOptions { PermitLimit = loginsPerMinute, Window = TimeSpan.FromMinutes(1) }));
+});
+
+// The app normally sits behind the host's proxy, which adds the real client address.
+builder.Services.Configure(options =>
+{
+ options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
+ options.KnownNetworks.Clear();
+ options.KnownProxies.Clear();
+});
+
+// Only needed when the web app is served from a different address, such as `flutter run`.
+if (builder.Configuration.GetValue("Cors:AllowAnyOrigin"))
+{
+ builder.Services.AddCors(options =>
+ options.AddDefaultPolicy(policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
+}
+
var app = builder.Build();
+
+app.UseForwardedHeaders();
+
+// Anything unexpected becomes a short JSON error. Details stay in the server log, never in the reply.
+app.UseExceptionHandler(errors => errors.Run(async context =>
+{
+ context.Response.StatusCode = StatusCodes.Status500InternalServerError;
+ await context.Response.WriteAsJsonAsync(
+ new PullPrintingBackend.Models.ApiError("server_error", "Something went wrong on the server. Please try again."));
+}));
+
+app.Use(async (context, next) =>
+{
+ var headers = context.Response.Headers;
+ headers["X-Content-Type-Options"] = "nosniff";
+ headers["Referrer-Policy"] = "no-referrer";
+ headers["X-Frame-Options"] = "DENY";
+ headers["Content-Security-Policy"] = "frame-ancestors 'none'";
+ await next();
+});
+
+// The Flutter web build is served from wwwroot. Files that change on every deploy must not be cached.
+app.UseDefaultFiles();
+app.UseStaticFiles(new StaticFileOptions
+{
+ OnPrepareResponse = context =>
+ {
+ var name = context.File.Name;
+ if (name is "index.html" or "flutter_service_worker.js" or "flutter_bootstrap.js" or "version.json")
+ context.Context.Response.Headers.CacheControl = "no-cache";
+ },
+});
+
+// The work-account callback only exists once Microsoft or Google sign-in is set up.
+app.Use(async (context, next) =>
+{
+ if (context.Request.Path.StartsWithSegments("/api/auth/callback") &&
+ !context.RequestServices.GetRequiredService>().Value.Enabled)
+ {
+ context.Response.StatusCode = StatusCodes.Status404NotFound;
+ return;
+ }
+ await next();
+});
+
app.UseRouting();
-app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
+if (builder.Configuration.GetValue("Cors:AllowAnyOrigin")) app.UseCors();
+app.UseRateLimiter();
+app.UseAuthentication();
+app.UseAuthorization();
+
+app.MapGet("/healthz", () => Results.Ok(new { status = "ok" })).DisableRateLimiting();
+app.MapControllers();
+
+if (app.Environment.WebRootFileProvider.GetFileInfo("index.html").Exists)
+ app.MapFallbackToFile("/{*path:regex(^(?!api/).*$)}", "index.html");
+
app.Run();
+
+/// Lets the integration tests start the app.
+public partial class Program { }
diff --git a/backend/PullPrintingBackend.csproj b/backend/PullPrintingBackend.csproj
index e69de29..355a89a 100644
--- a/backend/PullPrintingBackend.csproj
+++ b/backend/PullPrintingBackend.csproj
@@ -0,0 +1,15 @@
+
+
+
+ net8.0
+ enable
+ enable
+ PullPrintingBackend
+
+
+
+
+
+
+
+
diff --git a/backend/appsettings.Development.json b/backend/appsettings.Development.json
new file mode 100644
index 0000000..4501bbf
--- /dev/null
+++ b/backend/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Demo": {
+ "Enabled": true
+ },
+ "Cors": {
+ "AllowAnyOrigin": true
+ }
+}
diff --git a/backend/appsettings.json b/backend/appsettings.json
new file mode 100644
index 0000000..b4cc71a
--- /dev/null
+++ b/backend/appsettings.json
@@ -0,0 +1,26 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Microsoft.AspNetCore.DataProtection": "Error"
+ }
+ },
+ "AllowedHosts": "*",
+ "Demo": {
+ "Enabled": false,
+ "SigningKey": ""
+ },
+ "AzureAd": {
+ "TenantId": "",
+ "ClientId": "",
+ "AdminRole": "PullPrint.Admin"
+ },
+ "RateLimit": {
+ "PerMinute": 300,
+ "LoginPerMinute": 20
+ },
+ "Cors": {
+ "AllowAnyOrigin": false
+ }
+}
diff --git a/backend/controllers/AdminController.cs b/backend/controllers/AdminController.cs
index 13c2ca9..ac61cb7 100644
--- a/backend/controllers/AdminController.cs
+++ b/backend/controllers/AdminController.cs
@@ -1,19 +1,144 @@
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Options;
+using PullPrintingBackend.Models;
using PullPrintingBackend.Services;
-[ApiController]
-[Route("api/[controller]")]
-public class AdminController : ControllerBase
+namespace PullPrintingBackend.Controllers
{
- private readonly UserService _userService;
- public AdminController(UserService userService) => _userService = userService;
-
- [HttpPost("set-quota")]
- public IActionResult SetQuota([FromBody] dynamic payload)
+ [ApiController]
+ [Route("api/[controller]")]
+ [Authorize(Policy = Claims.AdminPolicy)]
+ [RequestSizeLimit(16_384)]
+ public class AdminController : ControllerBase
{
- string userId = payload.userId;
- int quota = payload.quota;
- _userService.UpdateQuota(userId, quota);
- return Ok();
+ public const int MaxQuota = 10_000;
+
+ private readonly IPrintStore _store;
+ private readonly WorkspaceOptions _workspace;
+ private readonly DemoOptions _demo;
+ private readonly AppTokenService _tokens;
+
+ public AdminController(IPrintStore store, IOptions workspace,
+ IOptions demo, AppTokenService tokens)
+ {
+ _store = store;
+ _workspace = workspace.Value;
+ _demo = demo.Value;
+ _tokens = tokens;
+ }
+
+ // ---- the setup check ---------------------------------------------------
+
+ ///
+ /// A plain summary of how this server is set up and anything that needs attention,
+ /// including the address to register with Microsoft or Google.
+ ///
+ [HttpGet("setup")]
+ public SetupDto Setup()
+ {
+ var me = User.UserId();
+ var warnings = new List();
+ foreach (var problem in _workspace.Problems()) warnings.Add("Work account sign-in is not ready. " + problem);
+ if (_workspace.Enabled && _demo.Enabled)
+ warnings.Add("Demo sign-in is on, so anyone on the internet can sign in to a sample sandbox. Turn it off for real use (Demo__Enabled=false).");
+ var printers = _store.Printers(me);
+ if (printers.Count == 0) warnings.Add("No printers yet. Add one so people can print.");
+ else if (printers.All(p => !p.Enabled)) warnings.Add("Every printer is switched off, so nobody can print.");
+ if (_workspace.Enabled && _tokens.UsesRandomKey)
+ warnings.Add("Auth__SigningKey is not set, so everyone is signed out whenever the server restarts.");
+
+ var provider = _workspace.Enabled ? _workspace.ProviderName!
+ : _demo.Enabled ? "Demo only"
+ : "None";
+ return new SetupDto(
+ provider,
+ _workspace.Enabled ? _workspace.ProviderName : null,
+ _workspace.Enabled ? _workspace.Domain : null,
+ _demo.Enabled,
+ _store.DefaultQuota(me) ?? PrintStore.DefaultQuotaPages,
+ _store.Users(me).Count,
+ printers.Count,
+ $"{Request.Scheme}://{Request.Host}/api/auth/callback",
+ warnings);
+ }
+
+ // ---- people and quotas -------------------------------------------------
+
+ [HttpGet("users")]
+ public IEnumerable Users() =>
+ _store.Users(User.UserId()).Select(u => new UserQuotaDto(u.UserId, u.Name, u.Quota, u.Email));
+
+ [HttpPost("set-quota")]
+ public IActionResult SetQuota([FromBody] SetQuotaRequest request)
+ {
+ if (string.IsNullOrWhiteSpace(request.UserId))
+ return BadRequest(new ApiError("bad_request", "userId is required."));
+ if (InvalidQuota(request.Quota, out var problem)) return problem!;
+ return _store.SetQuota(User.UserId(), request.UserId, request.Quota)
+ ? Ok()
+ : NotFound(new ApiError("not_found", "No such user."));
+ }
+
+ /// The pages a month that new people start with.
+ [HttpPost("default-quota")]
+ public IActionResult SetDefaultQuota([FromBody] QuotaValueRequest request)
+ {
+ if (InvalidQuota(request.Quota, out var problem)) return problem!;
+ return _store.SetDefaultQuota(User.UserId(), request.Quota) ? Ok() : NotFound();
+ }
+
+ /// Gives everyone the same pages a month, and returns how many people changed.
+ [HttpPost("set-quota-all")]
+ public IActionResult SetQuotaForAll([FromBody] QuotaValueRequest request)
+ {
+ if (InvalidQuota(request.Quota, out var problem)) return problem!;
+ return Ok(new { changed = _store.SetQuotaForAll(User.UserId(), request.Quota) });
+ }
+
+ // ---- printers ----------------------------------------------------------
+
+ [HttpPost("printers")]
+ public IActionResult AddPrinter([FromBody] PrinterRequest request)
+ {
+ if (InvalidPrinter(request, out var problem)) return problem!;
+ var printer = _store.AddPrinter(User.UserId(), request.Name!, request.Location ?? "");
+ return printer is null
+ ? Conflict(new ApiError("too_many", $"At most {PrintStore.MaxPrinters} printers."))
+ : Ok(printer);
+ }
+
+ [HttpPut("printers/{id}")]
+ public IActionResult UpdatePrinter(string id, [FromBody] PrinterRequest request)
+ {
+ if (InvalidPrinter(request, out var problem)) return problem!;
+ return _store.UpdatePrinter(User.UserId(), id, request.Name!, request.Location ?? "", request.Enabled ?? true)
+ ? Ok()
+ : NotFound(new ApiError("not_found", "No such printer."));
+ }
+
+ [HttpDelete("printers/{id}")]
+ public IActionResult DeletePrinter(string id) =>
+ _store.DeletePrinter(User.UserId(), id) ? Ok() : NotFound(new ApiError("not_found", "No such printer."));
+
+ // ---- checks ------------------------------------------------------------
+
+ private static bool InvalidQuota(int quota, out IActionResult? problem)
+ {
+ problem = quota is < 0 or > MaxQuota
+ ? new BadRequestObjectResult(new ApiError("bad_request", $"Quota must be between 0 and {MaxQuota} pages."))
+ : null;
+ return problem is not null;
+ }
+
+ private static bool InvalidPrinter(PrinterRequest request, out IActionResult? problem)
+ {
+ problem = null;
+ if (string.IsNullOrWhiteSpace(request.Name))
+ problem = new BadRequestObjectResult(new ApiError("bad_request", "A printer needs a name."));
+ else if (request.Name.Length > 60 || (request.Location?.Length ?? 0) > 100)
+ problem = new BadRequestObjectResult(new ApiError("bad_request", "Name up to 60 characters, location up to 100."));
+ return problem is not null;
+ }
}
}
diff --git a/backend/controllers/AuthController.cs b/backend/controllers/AuthController.cs
index b495643..08ad126 100644
--- a/backend/controllers/AuthController.cs
+++ b/backend/controllers/AuthController.cs
@@ -1,18 +1,110 @@
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
+using Microsoft.Extensions.Options;
+using PullPrintingBackend.Models;
using PullPrintingBackend.Services;
-[ApiController]
-[Route("api/[controller]")]
-public class AuthController : ControllerBase
+namespace PullPrintingBackend.Controllers
{
- private readonly AzureAuthService _authService;
- public AuthController(AzureAuthService authService) => _authService = authService;
-
- [HttpPost("login")]
- public IActionResult Login([FromBody] string token)
+ [ApiController]
+ [Route("api/[controller]")]
+ [RequestSizeLimit(16_384)]
+ public class AuthController : ControllerBase
{
- if (_authService.ValidateToken(token))
- return Ok(new { message = "Token valid" });
- return Unauthorized();
+ public const string WorkspaceScheme = "Workspace";
+ public const string ExternalScheme = "External";
+
+ private readonly IPrintStore _store;
+ private readonly AppTokenService _tokens;
+ private readonly DemoOptions _demo;
+ private readonly WorkspaceOptions _workspace;
+ private readonly TimeProvider _time;
+
+ public AuthController(IPrintStore store, AppTokenService tokens, IOptions demo,
+ IOptions workspace, TimeProvider time)
+ {
+ _store = store;
+ _tokens = tokens;
+ _demo = demo.Value;
+ _workspace = workspace.Value;
+ _time = time;
+ }
+
+ /// What the sign-in screen needs before anyone is signed in: which work account to offer.
+ [HttpGet("config")]
+ public AuthConfigDto Config() => new(
+ _workspace.Enabled ? _workspace.ProviderName!.ToLowerInvariant() : "none",
+ _workspace.Enabled ? _workspace.ProviderName : null,
+ _workspace.Enabled ? _workspace.Domain : null,
+ _demo.Enabled);
+
+ ///
+ /// Demo sign-in: creates a private sandbox with sample documents and returns a token for it.
+ /// Not found unless Demo:Enabled is true.
+ ///
+ [HttpPost("demo-login")]
+ [EnableRateLimiting("login")]
+ public ActionResult DemoLogin([FromBody] DemoLoginRequest? request)
+ {
+ if (!_demo.Enabled) return NotFound();
+ var user = _store.CreateDemoUser(request?.Admin ?? false);
+ return new SessionDto(_tokens.Create(user, Claims.DemoKind, _time), user.UserId, user.Name, user.IsAdmin);
+ }
+
+ /// Who the token belongs to.
+ [HttpGet("me")]
+ [Authorize]
+ public MeDto Me() => new(
+ User.UserId(),
+ User.FindFirst(Claims.Name)?.Value ?? "Signed-in user",
+ User.IsInRole(Claims.AdminRole));
+
+ ///
+ /// Starts sign-in with the organisation's work account: sends the browser to Microsoft or Google.
+ /// is a path on this site to come back to, such as /?printer=abc.
+ ///
+ [HttpGet("login")]
+ [EnableRateLimiting("login")]
+ public IActionResult Login([FromQuery] string? returnTo)
+ {
+ if (!_workspace.Enabled) return NotFound();
+ var properties = new AuthenticationProperties { RedirectUri = "/api/auth/complete" };
+ properties.Items["returnTo"] = SafeReturnPath(returnTo);
+ return Challenge(properties, WorkspaceScheme);
+ }
+
+ ///
+ /// Where the browser lands after the work account signed in. Checks the account belongs to this
+ /// organisation, then hands the app a session token in the address fragment, which never reaches a server log.
+ ///
+ [HttpGet("complete")]
+ public async Task Complete()
+ {
+ var result = await HttpContext.AuthenticateAsync(ExternalScheme);
+ await HttpContext.SignOutAsync(ExternalScheme);
+
+ var returnTo = SafeReturnPath(result.Properties?.Items.TryGetValue("returnTo", out var saved) == true ? saved : null);
+ if (!result.Succeeded || result.Principal is null || !_workspace.Enabled)
+ return Redirect(returnTo + "#error=sign_in_failed");
+
+ var (person, denied) = WorkspaceIdentity.Map(_workspace, result.Principal);
+ if (person is null) return Redirect(returnTo + "#error=" + (denied?.Code ?? "sign_in_failed"));
+
+ var user = _store.EnsureUser(person.Id, person.Name, person.IsAdmin, person.Email);
+ var token = _tokens.Create(user, Claims.WorkspaceKind, _time);
+ return Redirect(returnTo + "#token=" + token);
+ }
+
+ /// Only paths on this site are allowed, so sign-in cannot be used to send people elsewhere.
+ public static string SafeReturnPath(string? path)
+ {
+ if (string.IsNullOrEmpty(path) || path.Length > 200) return "/";
+ if (path[0] != '/' || path.StartsWith("//") || path.Contains('\\')) return "/";
+ if (path.Any(char.IsControl)) return "/";
+ var hash = path.IndexOf('#');
+ return hash >= 0 ? path[..hash] : path;
+ }
}
}
diff --git a/backend/controllers/JobsController.cs b/backend/controllers/JobsController.cs
index bce8e4f..50f9d0e 100644
--- a/backend/controllers/JobsController.cs
+++ b/backend/controllers/JobsController.cs
@@ -1,31 +1,83 @@
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Options;
using PullPrintingBackend.Models;
using PullPrintingBackend.Services;
-[ApiController]
-[Route("api/[controller]")]
-public class JobsController : ControllerBase
+namespace PullPrintingBackend.Controllers
{
- private readonly PrintService _printService;
- private readonly UserService _userService;
- private static List _jobs = new();
-
- public JobsController(PrintService printService, UserService userService)
+ [ApiController]
+ [Route("api/[controller]")]
+ [Authorize]
+ [RequestSizeLimit(16_384)]
+ public class JobsController : ControllerBase
{
- _printService = printService;
- _userService = userService;
- }
+ public const int MaxDocumentsPerRelease = 50;
- [HttpGet]
- public IEnumerable GetJobs() => _jobs;
+ private readonly IPrintStore _store;
+ private readonly DemoOptions _demo;
- [HttpPost("release")]
- public IActionResult ReleaseJob([FromBody] PrintJob job)
- {
- var user = _userService.GetUserById(job.UserId);
- if (user.PrintQuota <= 0) return Forbid("Quota exceeded");
- _printService.ReleaseJob(job, "DefaultPrinter");
- user.PrintQuota--;
- return Ok();
+ public JobsController(IPrintStore store, IOptions demo)
+ {
+ _store = store;
+ _demo = demo.Value;
+ }
+
+ /// Every job in the administrator's own group. Administrators only.
+ [HttpGet]
+ [Authorize(Policy = Claims.AdminPolicy)]
+ public IReadOnlyList All() => _store.AllJobs(User.UserId());
+
+ /// The signed-in user's documents that are waiting to print, newest first.
+ [HttpGet("held")]
+ public IReadOnlyList Held() => _store.HeldJobs(User.UserId());
+
+ /// Pages used and allowed this month for the signed-in user.
+ [HttpGet("quota")]
+ public ActionResult MyQuota() =>
+ _store.GetQuota(User.UserId()) is { } quota ? quota : NotFound();
+
+ ///
+ /// Prints the chosen documents. Only the caller's own waiting documents are used,
+ /// and nothing prints if the total would go over their quota.
+ ///
+ [HttpPost("release")]
+ public ActionResult Release([FromBody] ReleaseRequest request)
+ {
+ var ids = (request.JobIds ?? new List()).ToList();
+ if (request.JobId is { Length: > 0 }) ids.Add(request.JobId);
+ ids = ids.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct().ToList();
+ if (ids.Count == 0)
+ return BadRequest(new ApiError("no_jobs", "Choose at least one document."));
+ if (ids.Count > MaxDocumentsPerRelease)
+ return BadRequest(new ApiError("too_many", $"Print at most {MaxDocumentsPerRelease} documents at a time."));
+
+ var result = _store.Release(User.UserId(), ids, request.PrinterId);
+ return result.Outcome switch
+ {
+ ReleaseOutcome.Printed => new ReleaseResponse(
+ result.Printed.Select(j => j.Id).ToList(), result.Pages, result.Quota, result.PrinterName),
+ ReleaseOutcome.NoPrinter => Conflict(new ApiError(
+ "no_printer", "No printer has been set up yet. Ask an administrator.")),
+ ReleaseOutcome.PrinterUnavailable => Conflict(new ApiError(
+ "printer_unavailable", "That printer is not available. Choose another one.")),
+ ReleaseOutcome.OverQuota => Conflict(new ApiError(
+ "quota_exceeded",
+ $"Over your limit by {result.PagesOver} pages.",
+ result.PagesOver)),
+ _ => NotFound(new ApiError("not_found", "Those documents are not waiting to print.")),
+ };
+ }
+
+ /// Demo only: sends one more sample document to the signed-in user.
+ [HttpPost("sample")]
+ public ActionResult Sample()
+ {
+ if (!_demo.Enabled) return NotFound();
+ var job = _store.AddSample(User.UserId());
+ return job is null
+ ? Conflict(new ApiError("no_more_samples", "You already have plenty of documents waiting."))
+ : job;
+ }
}
}
diff --git a/backend/controllers/PrintersController.cs b/backend/controllers/PrintersController.cs
new file mode 100644
index 0000000..831882e
--- /dev/null
+++ b/backend/controllers/PrintersController.cs
@@ -0,0 +1,23 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using PullPrintingBackend.Models;
+using PullPrintingBackend.Services;
+
+namespace PullPrintingBackend.Controllers
+{
+ [ApiController]
+ [Route("api/[controller]")]
+ [Authorize]
+ public class PrintersController : ControllerBase
+ {
+ private readonly IPrintStore _store;
+ public PrintersController(IPrintStore store) => _store = store;
+
+ ///
+ /// The printers people can print to. Administrators also see switched-off ones, so they can switch them back on.
+ ///
+ [HttpGet]
+ public IReadOnlyList List() =>
+ _store.Printers(User.UserId()).Where(p => p.Enabled || User.IsInRole(Claims.AdminRole)).ToList();
+ }
+}
diff --git a/backend/data/ApplicationDbContext.cs b/backend/data/ApplicationDbContext.cs
deleted file mode 100644
index e69de29..0000000
diff --git a/backend/models/Dtos.cs b/backend/models/Dtos.cs
new file mode 100644
index 0000000..108fb7d
--- /dev/null
+++ b/backend/models/Dtos.cs
@@ -0,0 +1,37 @@
+namespace PullPrintingBackend.Models
+{
+ public record DemoLoginRequest(bool Admin = false);
+
+ public record SessionDto(string Token, string UserId, string Name, bool IsAdmin);
+
+ public record MeDto(string UserId, string Name, bool IsAdmin, string? Email = null);
+
+ /// What the sign-in screen needs to know before anyone is signed in.
+ public record AuthConfigDto(string Provider, string? ProviderName, string? Domain, bool Demo);
+
+ /// Send jobIds; a single jobId is also accepted. Without printerId the first enabled printer is used.
+ public record ReleaseRequest(List? JobIds = null, string? JobId = null, string? PrinterId = null);
+
+ public record ReleaseResponse(List Printed, int Pages, Quota Quota, string? PrinterName);
+
+ public record SetQuotaRequest(string? UserId, int Quota);
+
+ public record QuotaValueRequest(int Quota);
+
+ public record PrinterRequest(string? Name, string? Location, bool? Enabled);
+
+ public record UserQuotaDto(string UserId, string Name, Quota Quota, string? Email = null);
+
+ public record SetupDto(
+ string Provider,
+ string? ProviderName,
+ string? Domain,
+ bool DemoEnabled,
+ int DefaultQuota,
+ int People,
+ int Printers,
+ string RedirectUri,
+ List Warnings);
+
+ public record ApiError(string Error, string Message, int? PagesOver = null);
+}
diff --git a/backend/models/PrintJob.cs b/backend/models/PrintJob.cs
index 7a84b03..a0d8e9a 100644
--- a/backend/models/PrintJob.cs
+++ b/backend/models/PrintJob.cs
@@ -1,11 +1,21 @@
namespace PullPrintingBackend.Models
{
- public class PrintJob
+ public static class JobStatus
{
- public string Id { get; set; }
- public string UserId { get; set; }
- public string FileName { get; set; }
- public bool IsReleased { get; set; }
- public DateTime SubmittedAt { get; set; }
+ public const string Held = "Held";
+ public const string Printed = "Printed";
+ public const string Failed = "Failed";
}
+
+ /// One document waiting to print, or already printed. Immutable, updated with with.
+ public record PrintJob(
+ string Id,
+ string UserId,
+ string UserName,
+ string FileName,
+ int Pages,
+ DateTimeOffset SubmittedAt,
+ string Status,
+ string? FailureReason = null,
+ string? PrinterName = null);
}
diff --git a/backend/models/Printer.cs b/backend/models/Printer.cs
new file mode 100644
index 0000000..ea128af
--- /dev/null
+++ b/backend/models/Printer.cs
@@ -0,0 +1,5 @@
+namespace PullPrintingBackend.Models
+{
+ /// A printer an administrator has set up. People can only print to enabled ones.
+ public record Printer(string Id, string Name, string Location, bool Enabled);
+}
diff --git a/backend/models/Quota.cs b/backend/models/Quota.cs
index cce6f65..e7da194 100644
--- a/backend/models/Quota.cs
+++ b/backend/models/Quota.cs
@@ -1,8 +1,8 @@
namespace PullPrintingBackend.Models
{
- public class Quota
+ /// Pages used and allowed this month.
+ public record Quota(int Used, int Total)
{
- public string UserId { get; set; }
- public int RemainingQuota { get; set; }
+ public int Left => Math.Max(Total - Used, 0);
}
}
diff --git a/backend/models/User.cs b/backend/models/User.cs
index 0ecb8bf..fd36e16 100644
--- a/backend/models/User.cs
+++ b/backend/models/User.cs
@@ -1,11 +1,28 @@
namespace PullPrintingBackend.Models
{
+ /// A person known to the store. Mutated only while the store's lock is held.
public class User
{
- public string Id { get; set; }
- public string DisplayName { get; set; }
- public string Email { get; set; }
+ public required string Id { get; init; }
+ public required string DisplayName { get; set; }
+ public string? Email { get; set; }
public bool IsAdmin { get; set; }
public int PrintQuota { get; set; }
+ public int PagesUsed { get; set; }
+
+ /// The month the used pages count belongs to, as year * 100 + month. Pages reset when it changes.
+ public int QuotaPeriod { get; set; }
+
+ public DateTimeOffset LastSeen { get; set; }
+
+ ///
+ /// Who can see and manage this person. Everyone who signs in with a work account shares the
+ /// default group; each demo visitor and demo administrator gets a private one.
+ ///
+ public string SandboxId { get; init; } = "default";
+
+ public Quota Quota => new(PagesUsed, PrintQuota);
}
+
+ public record UserSummary(string UserId, string Name, bool IsAdmin, Quota Quota, string? Email = null);
}
diff --git a/backend/services/AuthServices.cs b/backend/services/AuthServices.cs
new file mode 100644
index 0000000..84f8fbd
--- /dev/null
+++ b/backend/services/AuthServices.cs
@@ -0,0 +1,99 @@
+using System.IdentityModel.Tokens.Jwt;
+using System.Security.Claims;
+using System.Security.Cryptography;
+using System.Text;
+using Microsoft.Extensions.Options;
+using Microsoft.IdentityModel.Tokens;
+using PullPrintingBackend.Models;
+
+namespace PullPrintingBackend.Services
+{
+ public static class Claims
+ {
+ public const string UserId = "uid";
+ public const string Name = "name";
+ public const string Role = "role";
+ public const string Kind = "kind";
+ public const string AdminRole = "Admin";
+ public const string UserRole = "User";
+ public const string AdminPolicy = "Admin";
+
+ /// Token made by demo sign-in.
+ public const string DemoKind = "demo";
+
+ /// Token made after a work account (Microsoft or Google) signed in.
+ public const string WorkspaceKind = "workspace";
+ }
+
+ public class DemoOptions
+ {
+ /// Lets anyone sign in to a private sandbox. Turn off for anything real.
+ public bool Enabled { get; set; }
+ }
+
+ public class AuthOptions
+ {
+ /// At least 32 characters. When empty a random key is made at start-up and everyone is signed out on restart.
+ public string? SigningKey { get; set; }
+ }
+
+ ///
+ /// Makes and describes the server's own session tokens. Whoever signs in, with a demo sandbox or a
+ /// work account, gets the same kind of token, so nothing else needs to know how they signed in.
+ ///
+ public class AppTokenService
+ {
+ public const string Issuer = "pullprint";
+ public const string Audience = "pullprint";
+
+ public SymmetricSecurityKey Key { get; }
+
+ /// True when no signing key was set, so tokens stop working at every restart.
+ public bool UsesRandomKey { get; }
+
+ public AppTokenService(IOptions options, IConfiguration config, ILogger log)
+ {
+ // "Demo:SigningKey" is the older name for the same setting.
+ var configured = options.Value.SigningKey;
+ if (string.IsNullOrWhiteSpace(configured)) configured = config["Demo:SigningKey"];
+
+ if (string.IsNullOrWhiteSpace(configured))
+ {
+ log.LogInformation("Auth:SigningKey is not set, using a random key. Everyone is signed out when the app restarts.");
+ Key = new SymmetricSecurityKey(RandomNumberGenerator.GetBytes(48));
+ UsesRandomKey = true;
+ }
+ else
+ {
+ if (configured.Length < 32)
+ throw new InvalidOperationException("Auth:SigningKey must be at least 32 characters.");
+ Key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configured));
+ }
+ }
+
+ public string Create(UserSummary user, string kind, TimeProvider time)
+ {
+ var now = time.GetUtcNow();
+ var token = new JwtSecurityToken(
+ issuer: Issuer,
+ audience: Audience,
+ claims: new[]
+ {
+ new Claim(Claims.UserId, user.UserId),
+ new Claim(Claims.Name, user.Name),
+ new Claim(Claims.Role, user.IsAdmin ? Claims.AdminRole : Claims.UserRole),
+ new Claim(Claims.Kind, kind),
+ },
+ notBefore: now.UtcDateTime,
+ expires: now.AddHours(8).UtcDateTime,
+ signingCredentials: new SigningCredentials(Key, SecurityAlgorithms.HmacSha256));
+ return new JwtSecurityTokenHandler().WriteToken(token);
+ }
+ }
+
+ public static class ControllerUser
+ {
+ public static string UserId(this ClaimsPrincipal user) =>
+ user.FindFirstValue(Claims.UserId) ?? throw new InvalidOperationException("Signed-in user has no id.");
+ }
+}
diff --git a/backend/services/AzureAuthService.cs b/backend/services/AzureAuthService.cs
deleted file mode 100644
index 1b9f2fc..0000000
--- a/backend/services/AzureAuthService.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using Microsoft.Identity.Client;
-
-namespace PullPrintingBackend.Services
-{
- public class AzureAuthService
- {
- private readonly string _tenantId = "YOUR_TENANT_ID";
- private readonly string _clientId = "YOUR_CLIENT_ID";
-
- public bool ValidateToken(string token)
- {
- // Implement Azure AD JWT validation here
- return true;
- }
- }
-}
diff --git a/backend/services/DemoCleanupService.cs b/backend/services/DemoCleanupService.cs
new file mode 100644
index 0000000..fc6424a
--- /dev/null
+++ b/backend/services/DemoCleanupService.cs
@@ -0,0 +1,25 @@
+namespace PullPrintingBackend.Services
+{
+ /// Removes visitors who have been idle for two hours, with their documents.
+ public class DemoCleanupService : BackgroundService
+ {
+ private readonly IPrintStore _store;
+ private readonly ILogger _log;
+
+ public DemoCleanupService(IPrintStore store, ILogger log)
+ {
+ _store = store;
+ _log = log;
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ using var timer = new PeriodicTimer(TimeSpan.FromMinutes(10));
+ while (await timer.WaitForNextTickAsync(stoppingToken))
+ {
+ var removed = _store.Sweep();
+ if (removed > 0) _log.LogInformation("Removed {Count} idle visitors.", removed);
+ }
+ }
+ }
+}
diff --git a/backend/services/PrintDispatcher.cs b/backend/services/PrintDispatcher.cs
new file mode 100644
index 0000000..119e21e
--- /dev/null
+++ b/backend/services/PrintDispatcher.cs
@@ -0,0 +1,24 @@
+using PullPrintingBackend.Models;
+
+namespace PullPrintingBackend.Services
+{
+ ///
+ /// Sends a released job to a physical printer. Throw to mark the job as failed;
+ /// the message becomes the failure reason shown to administrators.
+ ///
+ public interface IPrintDispatcher
+ {
+ void Print(PrintJob job, Printer printer);
+ }
+
+ /// Demo dispatcher: logs the job and prints nothing.
+ public class SimulatedPrintDispatcher : IPrintDispatcher
+ {
+ private readonly ILogger _log;
+ public SimulatedPrintDispatcher(ILogger log) => _log = log;
+
+ public void Print(PrintJob job, Printer printer) =>
+ _log.LogInformation("Simulated print: {File} ({Pages} pages) for {User} on {Printer}",
+ job.FileName, job.Pages, job.UserName, printer.Name);
+ }
+}
diff --git a/backend/services/PrintService.cs b/backend/services/PrintService.cs
deleted file mode 100644
index 8ccbba2..0000000
--- a/backend/services/PrintService.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using System.Printing;
-using PullPrintingBackend.Models;
-
-namespace PullPrintingBackend.Services
-{
- public class PrintService
- {
- public void ReleaseJob(PrintJob job, string printerName)
- {
- LocalPrintServer server = new LocalPrintServer();
- PrintQueue queue = server.GetPrintQueue(printerName);
- queue.AddJob(job.FileName);
- job.IsReleased = true;
- }
- }
-}
diff --git a/backend/services/PrintStore.cs b/backend/services/PrintStore.cs
new file mode 100644
index 0000000..ee9a2c4
--- /dev/null
+++ b/backend/services/PrintStore.cs
@@ -0,0 +1,505 @@
+using Microsoft.Extensions.Options;
+using PullPrintingBackend.Models;
+
+namespace PullPrintingBackend.Services
+{
+ public enum ReleaseOutcome { Printed, NothingToPrint, OverQuota, NoPrinter, PrinterUnavailable }
+
+ public record ReleaseResult(
+ ReleaseOutcome Outcome,
+ IReadOnlyList Printed,
+ int Pages,
+ int PagesOver,
+ Quota Quota,
+ string? PrinterName = null);
+
+ /// Users, printers, jobs and quotas. The only place that decides who may print what.
+ public interface IPrintStore
+ {
+ /// A person who signed in with a work account. Added to the shared group on first sight.
+ UserSummary EnsureUser(string id, string name, bool isAdmin, string? email = null);
+
+ /// A demo visitor. Creates their private sandbox the first time, and again if it was cleaned up.
+ UserSummary EnsureDemoUser(string id, string name, bool isAdmin);
+
+ UserSummary CreateDemoUser(bool isAdmin);
+ Quota? GetQuota(string userId);
+ IReadOnlyList HeldJobs(string userId);
+
+ /// Every job in the requester's own group.
+ IReadOnlyList AllJobs(string requesterId);
+
+ /// Everyone else in the requester's own group, for the quota table.
+ IReadOnlyList Users(string requesterId);
+
+ /// Prints the person's own waiting documents on a printer. All or nothing against their quota.
+ ReleaseResult Release(string userId, IReadOnlyCollection jobIds, string? printerId = null);
+
+ /// Changes a quota. Only people in the requester's own group can be changed.
+ bool SetQuota(string requesterId, string userId, int quota);
+
+ /// Pages a month for people who sign in for the first time. Null when the requester is unknown.
+ int? DefaultQuota(string requesterId);
+
+ bool SetDefaultQuota(string requesterId, int quota);
+
+ /// Sets everyone's quota in the requester's group and returns how many people changed.
+ int SetQuotaForAll(string requesterId, int quota);
+
+ /// Printers in the requester's group, including switched-off ones.
+ IReadOnlyList Printers(string requesterId);
+
+ Printer? AddPrinter(string requesterId, string name, string location);
+ bool UpdatePrinter(string requesterId, string printerId, string name, string location, bool enabled);
+ bool DeletePrinter(string requesterId, string printerId);
+
+ PrintJob? AddSample(string userId);
+ int Sweep();
+ }
+
+ ///
+ /// In-memory store. Everything resets when the app restarts, and demo sandboxes that
+ /// have been idle for are removed. Swap for a database
+ /// by implementing .
+ ///
+ public class PrintStore : IPrintStore
+ {
+ public const int DefaultQuotaPages = 50;
+ public const int MaxHeldPerUser = 12;
+ public const int MaxVisitors = 300;
+ public const int MaxPrinters = 50;
+ public const string DefaultSandbox = "default";
+ public static readonly TimeSpan IdleLifetime = TimeSpan.FromHours(2);
+
+ private static readonly (string File, int Pages)[] SampleDocuments =
+ {
+ ("Q3 budget review.pdf", 12),
+ ("Site visit notes.docx", 3),
+ ("Contract draft v4.pdf", 28),
+ ("Floor plan.png", 1),
+ ("Meeting agenda.docx", 2),
+ ("Safety checklist.pdf", 6),
+ ("Onboarding guide.pdf", 18),
+ ("Site photo.png", 1),
+ };
+
+ private readonly object _gate = new();
+ private readonly Dictionary _users = new();
+ private readonly List _jobs = new();
+ private readonly Dictionary> _printers = new();
+ private readonly Dictionary _defaultQuota = new();
+ private readonly IPrintDispatcher _dispatcher;
+ private readonly TimeProvider _time;
+ private int _sampleCursor;
+
+ public PrintStore(IPrintDispatcher dispatcher, TimeProvider time, IOptions workspace)
+ {
+ _dispatcher = dispatcher;
+ _time = time;
+ // The shared group starts empty: real people and printers are added by signing in and by administrators.
+ _defaultQuota[DefaultSandbox] = Math.Max(workspace.Value.DefaultQuota, 0);
+ }
+
+ private DateTimeOffset Now => _time.GetUtcNow();
+
+ private static int Period(DateTimeOffset t) => t.Year * 100 + t.Month;
+
+ /// Pages are used up per calendar month (UTC), so a new month starts everyone at zero.
+ private void Normalize(User user)
+ {
+ var period = Period(Now);
+ if (user.QuotaPeriod == period) return;
+ user.PagesUsed = 0;
+ user.QuotaPeriod = period;
+ }
+
+ private int DefaultFor(string sandbox) =>
+ _defaultQuota.TryGetValue(sandbox, out var q) ? q : DefaultQuotaPages;
+
+ // ---- demo sample data ------------------------------------------------
+
+ /// Sample people with a few jobs each, so a demo administrator has something to look at.
+ private void SeedSandbox(string sandbox, string idPrefix)
+ {
+ var now = Now;
+ AddUser(idPrefix + "u2", "Bob Reyes", used: 50, total: 50, sandbox);
+ AddUser(idPrefix + "u3", "Priya Nair", used: 8, total: 200, sandbox);
+ AddUser(idPrefix + "u4", "Marcus Lee", used: 20, total: 50, sandbox);
+ AddJob(idPrefix + "u2", "Bob Reyes", "report.docx", 3, now.AddMinutes(-30), JobStatus.Printed, printer: "Reception");
+ AddJob(idPrefix + "u3", "Priya Nair", "Safety audit.pdf", 41, now.AddHours(-1), JobStatus.Held);
+ AddJob(idPrefix + "u4", "Marcus Lee", "Invoice 2291.pdf", 2, now.AddDays(-1), JobStatus.Failed, "printer offline");
+ }
+
+ private void SeedPrinters(string sandbox)
+ {
+ _printers[sandbox] = new List
+ {
+ new(NewId(), "Level 3 East", "Third floor, east wing", true),
+ new(NewId(), "Reception", "Ground floor", true),
+ new(NewId(), "Print room", "Second floor", true),
+ };
+ }
+
+ private User AddUser(string id, string name, int used, int total, string sandbox, bool admin = false, string? email = null)
+ {
+ var user = new User
+ {
+ Id = id,
+ DisplayName = name,
+ Email = email,
+ IsAdmin = admin,
+ PagesUsed = used,
+ PrintQuota = total,
+ QuotaPeriod = Period(Now),
+ LastSeen = Now,
+ SandboxId = sandbox,
+ };
+ _users[id] = user;
+ return user;
+ }
+
+ /// Alice Tan with her four waiting documents, as every demo visitor starts.
+ private User AddAlice(string id, string sandbox)
+ {
+ const string name = "Alice Tan";
+ var user = AddUser(id, name, used: 12, total: DefaultQuotaPages, sandbox);
+ var now = Now;
+ AddJob(id, name, "Q3 budget review.pdf", 12, now.AddMinutes(-20), JobStatus.Held);
+ AddJob(id, name, "Site visit notes.docx", 3, now.AddMinutes(-40), JobStatus.Held);
+ AddJob(id, name, "Contract draft v4.pdf", 28, now.AddDays(-1), JobStatus.Held);
+ AddJob(id, name, "Floor plan.png", 1, now.AddDays(-1).AddHours(-1), JobStatus.Held);
+ return user;
+ }
+
+ private PrintJob AddJob(string userId, string userName, string file, int pages,
+ DateTimeOffset at, string status, string? reason = null, string? printer = null)
+ {
+ var job = new PrintJob(NewId(), userId, userName, file, pages, at, status, reason, printer);
+ _jobs.Add(job);
+ return job;
+ }
+
+ private static string NewId() => Guid.NewGuid().ToString("N")[..8];
+
+ private UserSummary Summary(User u)
+ {
+ Normalize(u);
+ return new(u.Id, u.DisplayName, u.IsAdmin, u.Quota, u.Email);
+ }
+
+ // ---- people ------------------------------------------------------------
+
+ public UserSummary EnsureUser(string id, string name, bool isAdmin, string? email = null)
+ {
+ lock (_gate)
+ {
+ if (!_users.TryGetValue(id, out var user))
+ user = AddUser(id, name, used: 0, total: DefaultFor(DefaultSandbox), DefaultSandbox, admin: isAdmin, email: email);
+ user.DisplayName = name;
+ user.IsAdmin = isAdmin;
+ if (email is not null) user.Email = email;
+ user.LastSeen = Now;
+ return Summary(user);
+ }
+ }
+
+ public UserSummary EnsureDemoUser(string id, string name, bool isAdmin)
+ {
+ lock (_gate)
+ {
+ if (_users.TryGetValue(id, out var existing))
+ {
+ existing.LastSeen = Now;
+ return Summary(existing);
+ }
+
+ EvictOldestSandboxes(MaxVisitors - 1);
+ SeedPrinters(id);
+ if (isAdmin)
+ {
+ // A private copy of the sample people, so changes here affect nobody else.
+ SeedSandbox(id, idPrefix: id + "-");
+ AddAlice(id + "-u1", id);
+ return Summary(AddUser(id, name, used: 0, total: DefaultQuotaPages, id, admin: true));
+ }
+ return Summary(AddAlice(id, id));
+ }
+ }
+
+ public UserSummary CreateDemoUser(bool isAdmin) =>
+ EnsureDemoUser("demo-" + NewId(), isAdmin ? "Administrator" : "Alice Tan", isAdmin);
+
+ public Quota? GetQuota(string userId)
+ {
+ lock (_gate)
+ {
+ if (!_users.TryGetValue(userId, out var u)) return null;
+ Normalize(u);
+ return u.Quota;
+ }
+ }
+
+ public IReadOnlyList HeldJobs(string userId)
+ {
+ lock (_gate)
+ return _jobs
+ .Where(j => j.UserId == userId && j.Status == JobStatus.Held)
+ .OrderByDescending(j => j.SubmittedAt)
+ .ToList();
+ }
+
+ private string? SandboxOf(string userId) =>
+ _users.TryGetValue(userId, out var u) ? u.SandboxId : null;
+
+ public IReadOnlyList AllJobs(string requesterId)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ return _jobs
+ .Where(j => sandbox is not null && SandboxOf(j.UserId) == sandbox)
+ .OrderByDescending(j => j.SubmittedAt)
+ .ToList();
+ }
+ }
+
+ public IReadOnlyList Users(string requesterId)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ return _users.Values
+ .Where(u => sandbox is not null && u.SandboxId == sandbox && !u.IsAdmin)
+ .OrderBy(u => u.DisplayName)
+ .Select(Summary)
+ .ToList();
+ }
+ }
+
+ // ---- printing ----------------------------------------------------------
+
+ public ReleaseResult Release(string userId, IReadOnlyCollection jobIds, string? printerId = null)
+ {
+ lock (_gate)
+ {
+ if (!_users.TryGetValue(userId, out var user))
+ return new ReleaseResult(ReleaseOutcome.NothingToPrint, Array.Empty(), 0, 0, new Quota(0, 0));
+ Normalize(user);
+
+ // Only the caller's own waiting jobs can be released, whatever ids were sent.
+ var chosen = _jobs
+ .Where(j => j.UserId == userId && j.Status == JobStatus.Held && jobIds.Contains(j.Id))
+ .ToList();
+ if (chosen.Count == 0)
+ return new ReleaseResult(ReleaseOutcome.NothingToPrint, Array.Empty(), 0, 0, user.Quota);
+
+ var available = _printers.TryGetValue(user.SandboxId, out var list)
+ ? list.Where(p => p.Enabled).OrderBy(p => p.Name).ToList()
+ : new List();
+ var printer = printerId is null
+ ? available.FirstOrDefault()
+ : available.FirstOrDefault(p => p.Id == printerId);
+ if (printer is null)
+ return new ReleaseResult(
+ printerId is null ? ReleaseOutcome.NoPrinter : ReleaseOutcome.PrinterUnavailable,
+ Array.Empty(), 0, 0, user.Quota);
+
+ var pages = chosen.Sum(j => j.Pages);
+ if (pages > user.Quota.Left)
+ return new ReleaseResult(ReleaseOutcome.OverQuota, Array.Empty(), pages,
+ pages - user.Quota.Left, user.Quota, printer.Name);
+
+ var printed = new List();
+ foreach (var job in chosen)
+ {
+ var index = _jobs.IndexOf(job);
+ try
+ {
+ _dispatcher.Print(job, printer);
+ _jobs[index] = job with { Status = JobStatus.Printed, PrinterName = printer.Name };
+ user.PagesUsed += job.Pages;
+ printed.Add(_jobs[index]);
+ }
+ catch (Exception e)
+ {
+ _jobs[index] = job with { Status = JobStatus.Failed, FailureReason = e.Message, PrinterName = printer.Name };
+ }
+ }
+ user.LastSeen = Now;
+ return new ReleaseResult(ReleaseOutcome.Printed, printed, printed.Sum(j => j.Pages), 0, user.Quota, printer.Name);
+ }
+ }
+
+ // ---- quotas and settings -------------------------------------------------
+
+ public bool SetQuota(string requesterId, string userId, int quota)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ if (sandbox is null || !_users.TryGetValue(userId, out var user) || user.SandboxId != sandbox)
+ return false;
+ user.PrintQuota = quota;
+ return true;
+ }
+ }
+
+ public int? DefaultQuota(string requesterId)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ return sandbox is null ? null : DefaultFor(sandbox);
+ }
+ }
+
+ public bool SetDefaultQuota(string requesterId, int quota)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ if (sandbox is null) return false;
+ _defaultQuota[sandbox] = quota;
+ return true;
+ }
+ }
+
+ public int SetQuotaForAll(string requesterId, int quota)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ if (sandbox is null) return 0;
+ var people = _users.Values.Where(u => u.SandboxId == sandbox && !u.IsAdmin).ToList();
+ foreach (var person in people) person.PrintQuota = quota;
+ return people.Count;
+ }
+ }
+
+ // ---- printers ------------------------------------------------------------
+
+ public IReadOnlyList Printers(string requesterId)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ return sandbox is not null && _printers.TryGetValue(sandbox, out var list)
+ ? list.OrderBy(p => p.Name).ToList()
+ : new List();
+ }
+ }
+
+ public Printer? AddPrinter(string requesterId, string name, string location)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ if (sandbox is null) return null;
+ if (!_printers.TryGetValue(sandbox, out var list)) _printers[sandbox] = list = new List();
+ if (list.Count >= MaxPrinters) return null;
+ var printer = new Printer(NewId(), name.Trim(), location.Trim(), true);
+ list.Add(printer);
+ return printer;
+ }
+ }
+
+ public bool UpdatePrinter(string requesterId, string printerId, string name, string location, bool enabled)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ if (sandbox is null || !_printers.TryGetValue(sandbox, out var list)) return false;
+ var index = list.FindIndex(p => p.Id == printerId);
+ if (index < 0) return false;
+ list[index] = new Printer(printerId, name.Trim(), location.Trim(), enabled);
+ return true;
+ }
+ }
+
+ public bool DeletePrinter(string requesterId, string printerId)
+ {
+ lock (_gate)
+ {
+ var sandbox = SandboxOf(requesterId);
+ return sandbox is not null
+ && _printers.TryGetValue(sandbox, out var list)
+ && list.RemoveAll(p => p.Id == printerId) > 0;
+ }
+ }
+
+ // ---- demo helpers and clean-up -----------------------------------------
+
+ public PrintJob? AddSample(string userId)
+ {
+ lock (_gate)
+ {
+ if (!_users.TryGetValue(userId, out var user)) return null;
+ var held = _jobs.Where(j => j.UserId == userId && j.Status == JobStatus.Held).ToList();
+ if (held.Count >= MaxHeldPerUser) return null;
+
+ // Prefer a document this person has not had yet, then one that is not waiting right now.
+ var ever = _jobs.Where(j => j.UserId == userId).Select(j => j.FileName).ToHashSet();
+ var waiting = held.Select(j => j.FileName).ToHashSet();
+ foreach (var avoid in new[] { ever, waiting })
+ {
+ for (var i = 0; i < SampleDocuments.Length; i++)
+ {
+ var (file, pages) = SampleDocuments[(_sampleCursor + i) % SampleDocuments.Length];
+ if (avoid.Contains(file)) continue;
+ _sampleCursor = (_sampleCursor + i + 1) % SampleDocuments.Length;
+ user.LastSeen = Now;
+ return AddJob(userId, user.DisplayName, file, pages, Now, JobStatus.Held);
+ }
+ }
+ return null;
+ }
+ }
+
+ /// Removes demo sandboxes nobody has used for .
+ public int Sweep()
+ {
+ lock (_gate)
+ {
+ var cutoff = Now - IdleLifetime;
+ var idle = _users.Values
+ .Where(u => u.SandboxId != DefaultSandbox)
+ .GroupBy(u => u.SandboxId)
+ .Where(g => g.Max(u => u.LastSeen) < cutoff)
+ .Select(g => g.Key)
+ .ToList();
+ foreach (var sandbox in idle) RemoveSandbox(sandbox);
+ return idle.Count;
+ }
+ }
+
+ /// How many demo sandboxes exist right now.
+ public int SandboxCount
+ {
+ get
+ {
+ lock (_gate)
+ return _users.Values.Where(u => u.SandboxId != DefaultSandbox).Select(u => u.SandboxId).Distinct().Count();
+ }
+ }
+
+ private void EvictOldestSandboxes(int keep)
+ {
+ var oldestFirst = _users.Values
+ .Where(u => u.SandboxId != DefaultSandbox)
+ .GroupBy(u => u.SandboxId)
+ .OrderBy(g => g.Max(u => u.LastSeen))
+ .Select(g => g.Key)
+ .ToList();
+ for (var i = 0; i < oldestFirst.Count - keep; i++) RemoveSandbox(oldestFirst[i]);
+ }
+
+ private void RemoveSandbox(string sandbox)
+ {
+ var ids = _users.Values.Where(u => u.SandboxId == sandbox).Select(u => u.Id).ToHashSet();
+ foreach (var id in ids) _users.Remove(id);
+ _jobs.RemoveAll(j => ids.Contains(j.UserId));
+ _printers.Remove(sandbox);
+ _defaultQuota.Remove(sandbox);
+ }
+ }
+}
diff --git a/backend/services/UserService.cs b/backend/services/UserService.cs
deleted file mode 100644
index cefb8a0..0000000
--- a/backend/services/UserService.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using PullPrintingBackend.Models;
-
-namespace PullPrintingBackend.Services
-{
- public class UserService
- {
- private List _users = new();
-
- public User GetUserById(string id) => _users.FirstOrDefault(u => u.Id == id);
-
- public void UpdateQuota(string userId, int quota)
- {
- var user = GetUserById(userId);
- if (user != null) user.PrintQuota = quota;
- }
- }
-}
diff --git a/backend/services/WorkspaceOptions.cs b/backend/services/WorkspaceOptions.cs
new file mode 100644
index 0000000..9166f12
--- /dev/null
+++ b/backend/services/WorkspaceOptions.cs
@@ -0,0 +1,126 @@
+using System.Security.Claims;
+
+namespace PullPrintingBackend.Services
+{
+ ///
+ /// Connects the server to the organisation's work accounts, Microsoft Entra ID or Google Workspace.
+ /// People sign in with their normal work account; the server decides who may do what.
+ ///
+ public class WorkspaceOptions
+ {
+ /// Microsoft or Google. Leave empty for demo-only.
+ public string? Provider { get; set; }
+
+ public string? ClientId { get; set; }
+ public string? ClientSecret { get; set; }
+
+ /// Microsoft only: the tenant (directory) id.
+ public string? TenantId { get; set; }
+
+ ///
+ /// Google: the Workspace domain, required. Microsoft: optional extra limit to one email domain.
+ ///
+ public string? Domain { get; set; }
+
+ /// Email addresses of administrators, separated by commas, semicolons or spaces.
+ public string? Admins { get; set; }
+
+ /// Microsoft only: an app role that also makes someone an administrator.
+ public string AdminRole { get; set; } = "PullPrint.Admin";
+
+ /// Pages a month for a person who signs in for the first time.
+ public int DefaultQuota { get; set; } = 50;
+
+ /// Overrides the provider's sign-in address. Only for tests and special set-ups.
+ public string? Authority { get; set; }
+
+ public bool RequireHttpsMetadata { get; set; } = true;
+
+ public bool IsMicrosoft => string.Equals(Provider, "Microsoft", StringComparison.OrdinalIgnoreCase);
+ public bool IsGoogle => string.Equals(Provider, "Google", StringComparison.OrdinalIgnoreCase);
+ public bool IsConfigured => !string.IsNullOrWhiteSpace(Provider);
+
+ /// Plain-words reasons the settings cannot be used. Empty means ready.
+ public IReadOnlyList Problems()
+ {
+ var problems = new List();
+ if (!IsConfigured) return problems;
+ if (!IsMicrosoft && !IsGoogle)
+ problems.Add($"Workspace__Provider is \"{Provider}\". Use Microsoft or Google.");
+ if (string.IsNullOrWhiteSpace(ClientId)) problems.Add("Workspace__ClientId is missing.");
+ if (string.IsNullOrWhiteSpace(ClientSecret)) problems.Add("Workspace__ClientSecret is missing.");
+ if (IsMicrosoft && string.IsNullOrWhiteSpace(TenantId)) problems.Add("Workspace__TenantId is missing.");
+ if (IsGoogle && string.IsNullOrWhiteSpace(Domain))
+ problems.Add("Workspace__Domain is missing. Without it any Google account could sign in.");
+ if (DefaultQuota < 0) problems.Add("Workspace__DefaultQuota cannot be negative.");
+ return problems;
+ }
+
+ public bool Enabled => IsConfigured && Problems().Count == 0;
+
+ public string? ProviderName => IsMicrosoft ? "Microsoft" : IsGoogle ? "Google" : null;
+
+ /// The address the person is sent to in order to sign in.
+ public string EffectiveAuthority =>
+ !string.IsNullOrWhiteSpace(Authority) ? Authority!
+ : IsMicrosoft ? $"https://login.microsoftonline.com/{TenantId}/v2.0"
+ : "https://accounts.google.com";
+
+ public IReadOnlySet AdminEmails =>
+ (Admins ?? "")
+ .Split(new[] { ',', ';', ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries)
+ .Select(e => e.Trim().ToLowerInvariant())
+ .ToHashSet();
+ }
+
+ public record WorkspaceUser(string Id, string Name, string? Email, bool IsAdmin);
+
+ /// Why a work account was turned away, in words for the person.
+ public record WorkspaceDenied(string Code, string Message);
+
+ /// Turns what the provider says about a person into who they are here, or says why not.
+ public static class WorkspaceIdentity
+ {
+ public static (WorkspaceUser? User, WorkspaceDenied? Denied) Map(WorkspaceOptions options, ClaimsPrincipal principal)
+ {
+ string? Claim(string type) => principal.FindFirstValue(type);
+
+ var email = (Claim("email") ?? Claim("preferred_username") ?? Claim("upn"))?.Trim().ToLowerInvariant();
+ var domain = options.Domain?.Trim().TrimStart('@').ToLowerInvariant();
+ var name = Claim("name") ?? email ?? "Signed-in user";
+
+ string? id;
+ if (options.IsGoogle)
+ {
+ id = Claim("sub");
+ if (id is null) return (null, new("no_identity", "The sign-in did not say who you are."));
+ if (!string.Equals(Claim("email_verified"), "true", StringComparison.OrdinalIgnoreCase))
+ return (null, new("unverified_email", "Your email address is not verified with Google."));
+ if (domain is not null &&
+ !string.Equals(Claim("hd"), domain, StringComparison.OrdinalIgnoreCase))
+ return (null, NotInDomain(domain));
+ id = "g-" + id;
+ }
+ else
+ {
+ id = Claim("oid") ?? Claim("sub");
+ if (id is null) return (null, new("no_identity", "The sign-in did not say who you are."));
+ var tenant = Claim("tid");
+ if (options.TenantId is { Length: > 0 } && tenant is not null &&
+ !string.Equals(tenant, options.TenantId, StringComparison.OrdinalIgnoreCase))
+ return (null, new("wrong_account", "That account belongs to a different organisation."));
+ id = "m-" + id;
+ }
+
+ if (domain is not null && (email is null || !email.EndsWith("@" + domain, StringComparison.Ordinal)))
+ return (null, NotInDomain(domain));
+
+ var isAdmin = (email is not null && options.AdminEmails.Contains(email)) ||
+ (options.IsMicrosoft && principal.FindAll("roles").Any(c => c.Value == options.AdminRole));
+ return (new WorkspaceUser(id, name, email, isAdmin), null);
+ }
+
+ private static WorkspaceDenied NotInDomain(string domain) =>
+ new("wrong_account", $"That account is not part of {domain}. Sign in with your work account.");
+ }
+}
diff --git a/docs/01-product-brief.md b/docs/01-product-brief.md
new file mode 100644
index 0000000..bc82a76
--- /dev/null
+++ b/docs/01-product-brief.md
@@ -0,0 +1,45 @@
+# 01 Product brief
+
+## The one job
+
+A person has sent a document to print. They walk to a printer, prove who they are, and get their pages. **Everything in the design serves that walk-up moment.** Sending a file and administering quotas matter, but they are not where speed is won or lost.
+
+## Who uses it
+
+| User | What they want | Where |
+|---|---|---|
+| Staff member | Collect their printing quickly and leave | At a printer panel, sometimes on their phone |
+| Administrator | See all jobs, set page quotas, spot failures | Desktop browser |
+
+A staff member is usually standing, often carrying things, and has no patience for menus. Design for that person, not for someone sitting at a desk.
+
+## Speed targets
+
+These are targets to design and test against, not measurements.
+
+| Task | Target |
+|---|---|
+| Sign in at the printer to seeing own documents | Under 5 seconds with a card, under 15 with a phone code |
+| Seeing own documents to pages printing | One tap (documents are pre-selected) |
+| Whole walk-up visit | Under 10 seconds with a card |
+| Taps needed to print everything waiting | 1 after sign-in |
+
+## Principles
+
+1. **One obvious action per screen.** The Print button is the largest thing on the release screen.
+2. **Pre-select everything.** Most people want all their waiting documents. Unticking is the exception.
+3. **Show only what is theirs.** No other person's file names, ever. This is the point of the product.
+4. **Say how many pages and how many are left.** Quota surprises are the main thing that stops a print.
+5. **Big touch targets.** At least 44 px on phone and web, at least 64 px on the printer panel.
+6. **Sign out for them.** The panel signs out automatically so the next person never sees the last user's list.
+7. **Plain words.** No jargon such as "release", "held" or "spool" in user-facing text. See [wording](03-screen-specs.md#wording).
+
+## Scope of the mockups
+
+In scope: phone sign-in, phone job list, phone confirmation, printer panel sign-in, release and confirmation, admin jobs and quotas.
+
+Out of scope for now: how a file reaches the server (no submission path exists in the code yet), printer settings such as duplex or colour, card reader hardware, notifications.
+
+## What exists in the code today
+
+The Flutter app has a login screen, a held-jobs list and an admin list. The .NET API has release and set-quota endpoints. See the [README status](../README.md#current-status) for what does not work yet. The mockups are the target design; they do not describe current behaviour.
diff --git a/docs/02-user-flows.md b/docs/02-user-flows.md
new file mode 100644
index 0000000..068fc25
--- /dev/null
+++ b/docs/02-user-flows.md
@@ -0,0 +1,60 @@
+# 02 User flows
+
+Diagrams use Mermaid, which GitHub renders in the page.
+
+## Flow A: print at the printer panel (main flow)
+
+```mermaid
+flowchart LR
+ A[Send file to Pull Print from any computer] --> B[Server keeps it waiting]
+ B --> C[Walk up to a printer]
+ C --> D[K1 Sign in]
+ D --> E[K2 Your documents all ticked]
+ E -->|Print| F[K3 Printing]
+ F -->|Sign out or 20 s timeout| D
+ E -->|Untick some, Print| F
+```
+
+Screens: [K1](03-screen-specs.md#k1-printer-panel--sign-in), [K2](03-screen-specs.md#k2-printer-panel--your-documents), [K3](03-screen-specs.md#k3-printer-panel--printing).
+
+| Step | User does | Screen shows | System does |
+|---|---|---|---|
+| 1 | Walks up | Sign-in with phone code (card later) | Requests a device code from Microsoft |
+| 2 | Enters code on phone, taps confirm | Documents list, all ticked, total pages and pages left | Fetches only this user's waiting jobs |
+| 3 | Taps Print | Printing confirmation, pages left | Sends jobs to the printer, reduces quota by pages printed |
+| 4 | Leaves | Auto sign-out after 20 seconds | Clears the session on the panel |
+
+## Flow B: print from the phone
+
+```mermaid
+flowchart LR
+ P1[P1 Sign in] --> P2[P2 Waiting to print pick jobs and printer]
+ P2 -->|Print| P3[P3 Sent to printer]
+ P3 -->|Back to my jobs| P2
+```
+
+This flow lets someone release from their phone without using the panel. See [open decision 3](05-open-decisions.md#3-should-phone-release-require-being-at-the-printer): it weakens the "only when you are at the printer" rule unless the app confirms the person is near it.
+
+## Flow C: administrator
+
+```mermaid
+flowchart LR
+ L[Sign in as admin] --> J[A1 Jobs]
+ J --> Q[Users and quotas]
+ Q -->|Edit number, Save| Q
+ J -->|Filter by status or search| J
+```
+
+## Error and edge cases
+
+Each needs a designed screen or message before build. Wording is in [03](03-screen-specs.md#states-to-design-next).
+
+| Case | What the person should see | What they can do |
+|---|---|---|
+| No documents waiting | "Nothing waiting to print" | Sign out |
+| Selection is over quota | Print disabled, how many pages over | Untick documents, or ask admin |
+| Quota is zero | "You have no pages left this month" | Sign out, contact admin |
+| Printer offline or out of paper | Printer name and the problem | Try another printer, which keeps the jobs waiting |
+| Sign-in code expired | "That code has expired" and a new code | Get a new code |
+| Network lost | "Cannot reach the print server" | Retry |
+| Job failed | Job marked as failed with reason | Try again; the job stays waiting |
diff --git a/docs/03-screen-specs.md b/docs/03-screen-specs.md
new file mode 100644
index 0000000..1b1e920
--- /dev/null
+++ b/docs/03-screen-specs.md
@@ -0,0 +1,133 @@
+# 03 Screen specs
+
+Seven screens. Images are the mockups in [`design/screens/`](design/screens/).
+
+> The pictures below are the **mockups** the app was built from. For pictures of the screens as built, see [Getting started](Getting%20started.md).
+
+## Wording
+
+| Avoid | Use |
+|---|---|
+| Release | Print |
+| Held job, spooled | Waiting to print, "Your documents" |
+| Quota | Pages left this month |
+| Authenticate, credentials | Sign in |
+| Error: 403 | A sentence that says what happened and what to do |
+
+---
+
+## P1 Phone: sign in
+
+
+
+**Purpose:** get the person signed in, and tell a first-time user what the product does in three lines.
+
+- Dark hero with the printer illustration (a sheet feeds out of it, animated). White sheet below holds the heading and three step cards.
+- One button: **Sign in with Microsoft** or **Sign in with Google**, whichever your organisation uses (the server says which), in that company's button style. In the demo it is the Microsoft button and signs in to sample data.
+- Under the button, one line says who can sign in, for example "Use your @example.com account. No new password."
+- If an account is turned away, a red box above the button says why in plain words and stays until the next try.
+- "How it works" is three numbered steps. This is the in-app guide for new users.
+- No registration, no password field. Identity comes from the work account.
+
+## P2 Phone: waiting to print
+
+
+
+**Purpose:** see own waiting documents and print the ones wanted.
+
+- Pages-left bar at the top.
+- Dark header with greeting and a ring showing pages left.
+- Each job is a whole row that toggles a checkbox. Shows a document thumbnail with file-type strip, file name, page count, when it was sent. Selecting updates the button and totals live; over quota disables the button and says by how many pages.
+- Selected rows have a thick blue border and a tick, so selection is not shown by colour alone.
+- Bottom bar: chosen printer and one button that states what it will do, "Print 2 jobs · 15 pages". Tap the printer to pick another when there is more than one. With none set up it says "No printer available" and Print stays off.
+- Sign-out is an icon button with an accessible label.
+
+## P3 Phone: sent to printer
+
+
+
+**Purpose:** confirm it worked and show pages left.
+
+- Tick, "Sent to Level 3 East", the list of what was sent, and the new pages-left figure.
+- One secondary button: **Back to my jobs**.
+
+## K1 Printer panel: sign in
+
+
+
+**Purpose:** identify the person at the printer. Screen is 1024 × 600, touch.
+
+- Left: dark panel with logo, heading, reassurance line and the printer illustration.
+- Right, primary: sign in with phone. A short code is shown large; the person enters it at `microsoft.com/devicelogin` on their own phone, then taps **I have entered the code**. This is the standard Microsoft device-code sign-in, so no keyboard is needed on the panel.
+- Right, secondary: tap staff card, marked "Coming later". This becomes the fast path once readers exist.
+- Header shows the printer name and status so people know which printer they are at.
+
+## K2 Printer panel: your documents
+
+
+
+**Purpose:** print everything with one tap. The most important screen.
+
+- Header: name, pages left, **Sign out** (always visible).
+- Documents are cards with large thumbnails, 4 across; the whole card toggles. Documents sent today are ticked by default.
+- Footer: running total ("2 documents · 15 pages"), pages left after printing, and the **Print** button (300 × 72 px, largest element).
+- If the selection is over quota, the footer says by how many pages and Print is disabled.
+
+## K3 Printer panel: printing
+
+
+
+**Purpose:** confirm and clear the session.
+
+- "Printing 15 pages", "Collect your documents from the tray", pages left.
+- **Print more** returns to K2. **Sign out** returns to K1.
+- Signs out automatically after 20 seconds, with a visible message saying so.
+
+## A1 Admin: setup, printers, people and jobs
+
+
+
+**Purpose:** set the system up once, keep printers and page limits right, find failed jobs.
+
+- **Setup** card first: "Setup is complete", or "Finish setting up" with each thing still to do in plain words, and (for Microsoft or Google) the exact sign-in address to register with a **Copy** button.
+- Four counts: waiting, printed today, failed, people out of quota.
+- **Printers**: add, rename, switch off and remove. **Copy panel link** gives the address to open on that printer's own screen, which fixes it to that printer.
+- **People and quotas**: **New people start with** (a default), **Give everyone** (asks to confirm, because it replaces every limit), then one row per person with an editable number and **Save**. People appear the first time they sign in.
+- **All jobs** table with search and status filter. Status is a text label, with a failure reason where there is one.
+- Layout is fluid. Tables scroll sideways inside their box on narrow screens.
+
+---
+
+## States and how they are handled
+
+Each is built in the app and covered by a test. Wording is exact.
+
+| Screen | State | What happens |
+|---|---|---|
+| P2, K2 | Select all | The button above the list ticks every document, then reads **Clear** |
+| P2, K2 | One document longer than the pages left | "This document needs 28 pages. You have 8 left." Print is off |
+| P2, K2 | More than one document, over quota | "Over your limit by 5 pages. Untick one." |
+| P2, K2 | No pages left | "No pages left this month." |
+| P3, K3 | Only some documents printed | The ones that printed are listed, and "1 document could not be printed and is still waiting." |
+| P2, K2 | Nothing printed | A message, and the person stays on their list |
+| P2, K2 | The list was out of date | "Those documents are not waiting to print. Your list has been refreshed." |
+| K2 | No touch for 60 seconds | Signed out, with "You were signed out because the screen was idle." |
+| any | Session ended (server restart, 8 hours) | Back to sign-in with "Your session has ended. Please sign in again." |
+| any | Too many requests | "Too many requests. Please wait a minute and try again." |
+| any, demo | Banner | "Demo: nothing is really printed." and **What is this?**, which has **Start over** |
+
+Already built and not repeated above: "Nothing waiting to print." with **Send sample documents** (demo) or "Send a file to Pull Print from your computer.", "Cannot reach the print server." with **Try again**, and "No jobs match." with **Clear filters** on the administrator screen.
+
+Not built yet, described for when they are:
+
+| Screen | State | Message |
+|---|---|---|
+| K1 | Phone code expired | "That code has expired." Button: "Get a new code" |
+| K3 | Printer problem | "The printer is out of paper. Your documents are still waiting." |
+
+## Accessibility checks applied
+
+- Controls are real buttons, links, inputs and labels.
+- Text contrast is at least 4.5:1 against its background.
+- Touch targets: 44 px minimum on phone and web, 64 px on the panel.
+- Selected and status states use a label, shape or border as well as colour.
diff --git a/docs/04-design-guidelines.md b/docs/04-design-guidelines.md
new file mode 100644
index 0000000..1d0080e
--- /dev/null
+++ b/docs/04-design-guidelines.md
@@ -0,0 +1,70 @@
+# 04 Design guidelines
+
+The visual style is deliberately plain: a utility people use in ten seconds and forget.
+
+## Imagery and logos
+
+**Not used:** AI-generated images or mascots, stock photos, emoji, gradient washes, glow or glass effects.
+
+**Used:**
+
+| Item | Source | Notes |
+|---|---|---|
+| Microsoft logo on the sign-in button | Microsoft's published four-square mark and sign-in button rules | Required for "Sign in with Microsoft". Colours `#F25022 #7FBA00 #00A4EF #FFB900`, white button, grey border, grey text. Replace the drawn copy with the asset from Microsoft's branding page before release. |
+| Pull Print mark | Our own, a document with text lines on the primary blue | Placeholder until the organisation supplies its own logo. |
+| Printer illustration | Our own flat vector, two blues, one animated sheet | Used on sign-in and confirmation screens. Replace with a photo of the real printer once available. |
+| Document thumbnails | Drawn from the file type: page with title bar and text lines, a file-type strip (PDF, DOCX, PNG) | In the build, replace with a real first-page preview from the server. |
+| Avatars | Initials on a flat colour | Replace with the Microsoft profile photo if available. |
+
+Only outline icons where text cannot do the job (sign out, printer, status). Each has a text or accessible label.
+
+Guide images: the mockups in [`design/screens/`](design/screens/) for now. After build, use real screenshots with numbered callouts and a photo of the actual printer panel.
+
+## Colour
+
+| Role | Value | Use |
+|---|---|---|
+| Background | `#F4F6F8` | Screen background |
+| Surface | `#FFFFFF` | Cards, header, footer |
+| Text | `#16212C` | Body and headings |
+| Muted text | `#4A5866` | Secondary text (7:1 on white) |
+| Border | `#D5DBE1` | Card and field outlines |
+| Primary | `#0B5CAD` | Print button, selection |
+| Hero navy | `#0E2A47` | Headers, sign-in and confirmation backgrounds |
+| Waiting | text on `#FFF0D1`, text `#6B4200` | Status label |
+| Failed | text on `#FBE3E3`, text `#7A1F1F` | Status label |
+
+One accent colour. Status is always a word, never colour alone.
+
+## Type
+
+Inter, falling back to the system font. Sizes in px.
+
+| Use | Phone and web | Printer panel |
+|---|---|---|
+| Screen heading | 20–32 | 28–44 |
+| Row title | 16 | 20 |
+| Secondary text | 14 | 16–18 |
+| Primary button | 17 | 24 |
+
+Minimum text size is 13 px on phone and web, 16 px on the panel.
+
+## Sizing and spacing
+
+- Touch targets: 44 px minimum, 64 px on the panel.
+- Rows are whole-row tap targets.
+- Spacing steps: 8, 12, 16, 24, 32.
+- Corner radius: 10–12 px on controls and cards.
+- Primary button is the largest element on the screen.
+
+## Mapping to Flutter
+
+`frontend/lib/utils/theme.dart` currently uses `Colors.blue` and a blue app bar. Replace it with a `ThemeData` built from the table above (`ColorScheme.fromSeed` is not enough on its own, set the values explicitly). Keep `JobCard` as the row widget but make it a checkbox row with the sizes above, and make `QuotaIndicator` read "38 of 50 pages left" rather than "used / total pages".
+
+## Checklist before a screen is done
+
+- One primary action, visible without scrolling.
+- Works at 390 px wide (phone) or 1024 × 600 (panel).
+- Contrast checked, targets measured.
+- Empty, over-quota and error states exist.
+- Wording matches the [word list](03-screen-specs.md#wording).
diff --git a/docs/05-open-decisions.md b/docs/05-open-decisions.md
new file mode 100644
index 0000000..b934472
--- /dev/null
+++ b/docs/05-open-decisions.md
@@ -0,0 +1,53 @@
+# 05 Open decisions
+
+Questions that change the design. Each has a recommendation, but the answer is yours.
+
+## 1. Is quota counted in pages or in jobs?
+
+The README says quota "goes down by one" per print, which reads as per job. `QuotaIndicator` and the mockups use pages. Pages is fairer and matches paper cost, but it needs the server to know the page count of every job.
+
+**Recommendation:** pages. The mockups assume it.
+
+## 2. How does someone sign in at the printer?
+
+Built so far: the person signs in with their work account (Microsoft or Google) in the browser on the panel. Still open: the phone-code screen from the mockups (the person enters a short code on their own phone, so nobody types a password on a shared screen), and staff cards. Card is faster, but needs readers and a mapping from card to user.
+
+**Recommendation:** add the phone code next, since it keeps passwords off a shared screen. Add card when hardware exists. Card would then be the 5-second path.
+
+## 2b. Quotas by group?
+
+Pages are per person today, with a default for new people and one number for everyone. Real organisations want "students 30, staff 200". That needs the directory (Microsoft Graph groups or Google organisational units).
+
+**Recommendation:** after real-tenant testing, map one or two groups to quotas. Keep the per-person override.
+
+## 3. Should phone release require being at the printer?
+
+The product promise is that jobs print only when you are standing at the printer. If the phone can release to any printer, someone can print to a printer in another room and leave it in the tray.
+
+Options: (a) phone view only shows jobs and sends people to the panel, (b) the phone must scan a code shown on the panel, (c) allow it, accept the risk.
+
+**Recommendation:** (b). P2 would swap "Printer: Level 3 East" for a scan step.
+
+## 4. What happens to jobs nobody collects?
+
+Waiting jobs stay on the server. Options: expire after a set time (for example 24 hours) and say so on screen, or keep until deleted.
+
+**Recommendation:** expire after 24 hours and show "Deleted after 24 hours" under each job. This is also better for privacy.
+
+## 5. What happens when selection exceeds quota?
+
+Drawn as: Print disabled and the shortfall shown. Alternative: print as many whole documents as fit.
+
+**Recommendation:** as drawn. It is predictable.
+
+## 6. How do files reach the server?
+
+Nothing in the code creates a waiting job. This sets the whole front of the flow: a Windows print driver or print queue, email-to-print, a web upload page, or the phone app. It is not designed here.
+
+**Recommendation:** decide before building the panel, because it determines the file types and the page-count source.
+
+## 7. Does the panel run the Flutter app?
+
+K1–K3 are sized for a 1024 × 600 touch screen. Running the same Flutter app in a kiosk mode on a small Windows or Linux device is the shortest route, and Flutter has Windows and Linux targets in this repo.
+
+**Recommendation:** yes, with a kiosk route that has no back navigation and auto sign-out.
diff --git a/docs/06-demo-hosting.md b/docs/06-demo-hosting.md
new file mode 100644
index 0000000..d9f00f0
--- /dev/null
+++ b/docs/06-demo-hosting.md
@@ -0,0 +1,67 @@
+# 06 Hosting the demo
+
+How to put the demo online for free so anyone with the link can try it.
+
+## What you get
+
+One address that serves the web app and the API together. Each visitor signs in to a private sandbox with sample documents. Nothing is printed, nothing is kept for long, and nobody can see anyone else's documents.
+
+## Option 1: Render (free plan)
+
+1. Create a free account at [render.com](https://render.com) and connect your GitHub account.
+2. Choose **New**, then **Blueprint**, and pick this repository. Render reads `render.yaml` and sets everything up: one web service, built from the `Dockerfile`, with a generated signing key.
+3. Wait for the first build. It builds the web app and the API, so it takes several minutes.
+4. Open the address Render gives you. Share it.
+
+To update the demo, push to the branch Render watches. It rebuilds on its own (`autoDeploy`).
+
+## Option 2: any host that runs a Docker image
+
+The `Dockerfile` works anywhere that runs a container and tells it which port to use through the `PORT` environment variable.
+
+```bash
+docker build -t pull-print-demo .
+docker run -p 8080:8080 -e Auth__SigningKey="$(openssl rand -base64 48)" pull-print-demo
+```
+
+Then open `http://localhost:8080`.
+
+## Settings
+
+Set these as environment variables on the host. Double underscores stand for the colon in the setting name.
+
+| Variable | Default | What it does |
+|---|---|---|
+| `Demo__Enabled` | `true` in the image | Lets visitors sign in to a sandbox. `false` turns demo sign-in off and invalidates demo tokens |
+| `Auth__SigningKey` | random at start | At least 32 characters. Set it so visitors stay signed in when the server restarts. The Render blueprint generates one |
+| `RateLimit__LoginPerMinute` | `20` | Sign-ins per minute from one address |
+| `RateLimit__PerMinute` | `300` | All requests per minute from one address |
+| `Workspace__*` | empty | Turns on Microsoft or Google work-account sign-in. See [09](09-connecting-your-workspace.md) |
+| `Cors__AllowAnyOrigin` | `false` | Only needed if the web app is served from a different address |
+
+## What to expect from a free host
+
+- **It sleeps when idle.** Free plans usually stop a service after a quiet period. The first visitor afterwards waits a minute or so while it wakes up. The banner and sign-in screen load first, and sign-in works once it is up.
+- **It forgets when it sleeps or restarts.** Data is in memory. A visitor who comes back after a restart is signed in again with fresh sample documents, or sees "Your session has ended" and signs in again. That is expected.
+- **Limits can change.** Check the host's current free-plan terms before relying on it.
+
+## Checking it works
+
+Open `/healthz` on your address. It should answer `{"status":"ok"}`. Then open the address, sign in, and press Print. The pages-left figure should go down.
+
+## Things to know before sharing the link widely
+
+- Anyone with the link can sign in. That is the point of a demo, so keep real data out of it.
+- Sign-in and request limits are per address. Many people behind one office or school network share a limit, which is generous for normal use but can be hit by a classroom all signing in at once.
+- The app trusts the host's proxy to say who is calling, which is right for Render and similar hosts. If you put it behind something else, check that it sets `X-Forwarded-For`.
+- The Microsoft and Google logos on the sign-in buttons are drawn to their rules. Replace them with the companies' own assets before any public launch.
+- This page is about the sample-data demo. To use real accounts, printers and quotas, see [09 Connecting your workspace](09-connecting-your-workspace.md) and switch the demo off.
+
+## Option 3: Vercel (static, no server)
+
+The simplest free option needs no server at all. In this mode the app runs on its built-in sample data inside the visitor's browser, so every visitor already has their own private copy and nothing sleeps.
+
+- `vercel.json` and `scripts/vercel-build.sh` build the web app with `USE_MOCK=true`. Connect the repository to a Vercel project and it builds on every push.
+- Data lives in the browser tab and resets when the page is reloaded.
+- There is no API in this mode, so nothing can be shared between visitors and the administrator view only shows the built-in sample people.
+- Use Option 1 or 2 when you want to show the real API.
diff --git a/docs/08-review-and-fixes.md b/docs/08-review-and-fixes.md
new file mode 100644
index 0000000..14a85e4
--- /dev/null
+++ b/docs/08-review-and-fixes.md
@@ -0,0 +1,72 @@
+# 08 Review and fixes
+
+A review of the demo from each kind of user's point of view, what went wrong or could go wrong, and what was done about it. "How it was found" says whether the problem came from reading the code, from an automated test, or from running the real app in a browser.
+
+## Fixed
+
+### First-time visitor
+| What went wrong | Why it mattered | How it was found | Fix |
+|---|---|---|---|
+| The web page was still the Flutter template: tab title "pull_printing_app", description "A new Flutter project.", Flutter's icons | The first thing every visitor sees, and what link previews show | Reading the deployed page | Real title, description, link preview text, brand icons and manifest (`web/`) |
+| A blank white page for several seconds while about 8 MB loads | Looks broken | Reading the page source | A branded loading screen that disappears at the first frame |
+| The manifest locked the app to portrait | The printer panel is landscape | Reading the manifest | `orientation: any` |
+| "Sign in with Microsoft" in the demo suggested a Microsoft account is needed | Visitors may hesitate or give up | Review | "No account needed. You get your own sample documents, and nothing is really printed." |
+| A visitor who printed everything had no way back to the start | Stuck with an empty list | Review | **Start over** in the "What is this?" dialog |
+
+### Large text and small screens
+| What went wrong | How it was found | Fix |
+|---|---|---|
+| At 1.5 times text size on a phone, **the Sign in button was pushed below the screen** with nothing to say it was there | Automated test at 1.5x text | Sign-in layout shrinks the printer picture, drops the step cards and adapts to text size |
+| The Microsoft button text, the pages-left ring, the confirmation row and the panel's left column overflowed at large text | Same test, then 2x and the panel at 1.3x | Text wraps or scales down inside fixed shapes; document cards grow with text size |
+| A 360 by 640 phone with the demo banner pushed Sign in off screen | Automated test | Compact sign-in layout |
+
+### Someone using the printer panel
+| What went wrong | Fix |
+|---|---|
+| A person could walk away leaving their documents on a shared screen | The panel signs out after 60 seconds without a touch, with a message saying why. Any touch restarts the count |
+
+### Someone with a long document or few pages left
+| What went wrong | Fix |
+|---|---|
+| "Untick one" when only one document is chosen made no sense | "This document needs 28 pages. You have 8 left." |
+| Zero pages left gave the same message as being a few pages over | "No pages left this month." |
+| Ticking each document by hand to print everything | **Select all** and **Clear** |
+| Nowhere to go from a quota block in the demo | A demo tip points to the administrator demo, where limits can be raised |
+
+### When printing does not go as expected
+| What went wrong | How it was found | Fix |
+|---|---|---|
+| The app assumed every chosen document printed, even if the server said only some did | Review of the API contract | The app uses the server's list of what printed, and says which documents are still waiting |
+| If nothing printed, the person got a raw error | Review | A plain message, and they stay on their list |
+| A list that was out of date ("documents are not waiting") left the person confused | Review | The message says the list was refreshed, and it is |
+| Hitting the rate limit showed "error 429" | Review | "Too many requests. Please wait a minute and try again." |
+| A session that ended (server restart, 8 hours) looked like "cannot reach the server" | Browser run | The person is signed out with "Your session has ended" |
+
+### Privacy and safety
+| What went wrong | How it was found | Fix |
+|---|---|---|
+| The demo administrator's list showed **every visitor's documents**, against the promise that nobody else can see yours | Browser run with two visitors and an administrator | Every demo administrator gets a private copy of the sample people, and can only reach their own group |
+| An unexpected server error could return details | Review | Always a short JSON error, details only in the server log |
+| No basic security headers | Review | `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `frame-ancestors 'none'` |
+| No limit on request size or on how many documents one request names | Review | 16 KB bodies, at most 50 documents, repeats counted once |
+| A sample document that was just printed came straight back as the next sample | Browser run | New documents first |
+
+## Known and not fixed
+
+Each one is a GitHub issue.
+
+- Work-account sign-in (Microsoft and Google) has not been run against a real tenant. [#2](https://github.com/Hikki-dev/pull_printing_app/issues/2)
+- Data is in memory only. [#3](https://github.com/Hikki-dev/pull_printing_app/issues/3)
+- There is no way to send your own file. [#4](https://github.com/Hikki-dev/pull_printing_app/issues/4)
+- Nothing is really printed. [#5](https://github.com/Hikki-dev/pull_printing_app/issues/5)
+- Staff-card sign-in and the phone code sign-in from the mockups are not built. [#6](https://github.com/Hikki-dev/pull_printing_app/issues/6)
+- The Pull Print mark, printer picture, thumbnails and Microsoft and Google marks are placeholders. [#7](https://github.com/Hikki-dev/pull_printing_app/issues/7)
+- The browser Back button leaves the demo instead of going to the previous screen. [#8](https://github.com/Hikki-dev/pull_printing_app/issues/8)
+- The app is light-only, English-only, and has not been checked with a screen reader on a real device. [#9](https://github.com/Hikki-dev/pull_printing_app/issues/9)
+- Limits are per address, so a whole room behind one network address shares them. (Noted in [SECURITY.md](../SECURITY.md).)
+
+## How to repeat this review
+
+1. `dotnet test backend.Tests` and `flutter test` (the large-text, small-screen and idle tests are in `test/widget_test.dart`).
+2. Build the web app, serve it, and click through it in a browser as a visitor, a visitor who runs out of pages, and an administrator.
+3. Try 1.5 times and 2 times text size on a phone, and the panel at 1024 by 600.
diff --git a/docs/09-connecting-your-workspace.md b/docs/09-connecting-your-workspace.md
new file mode 100644
index 0000000..4345c8b
--- /dev/null
+++ b/docs/09-connecting-your-workspace.md
@@ -0,0 +1,149 @@
+# 09 Connecting your workspace
+
+How to make Pull Print use your organisation's own accounts, so people sign in with the work account they already have, and you control the printers and each person's pages from one screen.
+
+Pick the one you use. It takes about ten minutes, and you do it once.
+
+> **Honest status.** The sign-in is built and tested against a **simulated** Microsoft/Google sign-in (the whole round trip, including refusing the wrong organisation). It has **not been run against a real tenant**, because that needs your account. Follow the steps below on a test tenant first. If something does not work, see [Fixing problems](Fixing%20problems.md); the **Setup** card on the administrator screen says what is missing, and [issue #2](https://github.com/Hikki-dev/pull_printing_app/issues/2) is where to report it.
+
+## How it works, in one picture
+
+
+
+In short:
+
+```
+Person ──▶ "Sign in with Microsoft / Google" ──▶ their normal work sign-in
+ │
+Pull Print server ◀── who they are (checked here) ─────┘
+ │
+ ├─ is this person from our organisation? no ─▶ turned away, with a reason
+ ├─ new here? ─▶ added, with the default pages a month
+ ├─ on the administrators list? ─▶ gets the administrator screen
+ └─ shows only their own documents; prints only on printers you added
+```
+
+Two things live on the server, so there is one place to manage them:
+
+- **Printers.** You add each printer once (name and place). People pick one, or the printer's own screen is fixed to it.
+- **People and pages.** Everyone appears the first time they sign in with the default pages a month. You change one person, or everyone, from the administrator screen. Pages start again on the 1st of each month (UTC).
+
+## What you need
+
+| | Microsoft 365 / Entra ID | Google Workspace |
+|---|---|---|
+| An account that can register apps | Application Administrator, or Global Administrator | Super admin of a Google Cloud project |
+| The address people use | `https://` | `https://` |
+| What you copy out | Application (client) ID, Directory (tenant) ID, a client secret | Client ID and client secret, and your domain such as `example.com` |
+
+`` is where you run the server (for example the Render address, or your own domain). It must be **https**.
+
+## Microsoft 365 (Entra ID)
+
+1. Open the **Microsoft Entra admin centre**, then **App registrations**, **New registration**.
+2. Name it `Pull Print`. Under supported account types choose **Accounts in this organizational directory only**.
+3. Under **Redirect URI** choose **Web** and enter `https:///api/auth/callback`. Register.
+4. On the overview page copy the **Application (client) ID** and the **Directory (tenant) ID**.
+5. Go to **Certificates & secrets**, **New client secret**, and copy the secret's **Value** now (it is shown once).
+6. *(Optional, to make administrators without a list)* Under **App roles** create a role with value `PullPrint.Admin` for **Users/Groups**, then assign it to your administrators under **Enterprise applications**, **Users and groups**.
+7. Set these on the server (see [Settings](#settings)):
+
+ ```
+ Workspace__Provider=Microsoft
+ Workspace__TenantId=
+ Workspace__ClientId=
+ Workspace__ClientSecret=
+ Workspace__Admins=you@yourcompany.com
+ ```
+
+Only accounts from that tenant can sign in. To allow just one email domain inside it, also set `Workspace__Domain=yourcompany.com`.
+
+## Google Workspace
+
+1. Open the **Google Cloud console**, create or pick a project, then **APIs & Services**, **OAuth consent screen**. Choose **Internal** (only your Workspace organisation can sign in). Fill in the app name `Pull Print` and your support email.
+2. Go to **Credentials**, **Create credentials**, **OAuth client ID**. Type **Web application**.
+3. Under **Authorized redirect URIs** add `https:///api/auth/callback`. Create.
+4. Copy the **Client ID** and **Client secret**.
+5. Set these on the server:
+
+ ```
+ Workspace__Provider=Google
+ Workspace__ClientId=
+ Workspace__ClientSecret=
+ Workspace__Domain=example.com
+ Workspace__Admins=you@example.com
+ ```
+
+`Workspace__Domain` is **required** for Google. Without it any Google account could sign in, so the server refuses to turn Google sign-in on.
+
+## Settings
+
+Set these as environment variables on the host. Double underscores stand for the colon.
+
+| Setting | Needed | What it does |
+|---|---|---|
+| `Workspace__Provider` | yes | `Microsoft` or `Google`. Leave empty for the demo only |
+| `Workspace__ClientId` | yes | From the app registration or OAuth client |
+| `Workspace__ClientSecret` | yes | Keep it secret. Never put it in the app or in Git |
+| `Workspace__TenantId` | Microsoft | The directory (tenant) id |
+| `Workspace__Domain` | Google: yes. Microsoft: optional | Only addresses ending `@domain` get in |
+| `Workspace__Admins` | recommended | Email addresses of administrators, separated by commas or spaces |
+| `Workspace__AdminRole` | no | Microsoft app role that also makes an administrator. Default `PullPrint.Admin` |
+| `Workspace__DefaultQuota` | no | Pages a month for someone signing in for the first time. Default 50. Changeable on the administrator screen |
+| `Auth__SigningKey` | **yes for real use** | At least 32 random characters. Without it everyone is signed out whenever the server restarts |
+| `Demo__Enabled` | set to `false` | Turns the sample-data demo off. Leaving it on lets anyone on the internet open a sandbox |
+
+Generate a signing key with `openssl rand -base64 48`.
+
+## First sign-in: set up in four steps
+
+1. Open `https://` and sign in with an account in `Workspace__Admins`. You land on the **administrator** screen.
+2. Read the **Setup** card at the top. It lists anything still to do in plain words, and shows the exact sign-in address to register. When nothing is left it says **Setup is complete**.
+3. **Printers**: press **Add a printer** for each one (name, and where it is). Use **Copy panel link** to get that printer's own address.
+4. **People and quotas**: set **New people start with** to your usual pages a month. People appear in the list as they first sign in. Use **Give everyone** to set the same number for the whole organisation at once, or set one person on their row.
+
+## At the printer
+
+Open the printer's **panel link** (`https:///?printer=`) on the screen next to the printer, in full screen. It is fixed to that printer, so people sign in, see their documents, and press **Print**, with no question about which printer. It signs people out after 60 seconds without a touch, and asks which account to use each time so the next person is never signed in as the last.
+
+On a phone, the same address without `?printer=` lets the person pick a printer.
+
+## What people and administrators see
+
+The sign-in button changes to match, and says who can use it:
+
+ 
+
+Administrators get a Setup card. It lists what is still to do and shows the exact address to register in step 3 of the guides above:
+
+
+
+When nothing is left it says **Setup is complete**. Every screen is shown in [Getting started](Getting%20started.md).
+
+## When someone cannot sign in
+
+
+
+| They see | Why | What to do |
+|---|---|---|
+| "That account is not allowed here" | Wrong organisation or domain, or a personal account | Sign in with the work account. Check `Workspace__TenantId` / `Workspace__Domain` |
+| "Your email address is not verified" | Google says the address is not verified | Verify it in the Google account |
+| "Your account did not tell us who you are" | The provider sent no identity | Check the app registration, then ask support |
+| "Sign-in did not work" | The provider or the server failed | Try again. Check the server log and that the redirect address matches exactly |
+| Sign-in button missing, only a demo | Settings incomplete | Open the server's `/api/auth/config`, or read the log: it names the missing setting |
+
+## Security notes
+
+- The provider's sign-in happens on Microsoft's or Google's own page. Pull Print never sees a password.
+- The server then issues its own 8-hour session token. It reaches the app in the address after `#` and is removed from the address bar before the app starts, so it is not left in the browser history.
+- The client secret stays on the server.
+- Only your organisation can sign in. People only ever see their own documents, and quota is checked on the server.
+- Administrators are decided by the server (the `Workspace__Admins` list or the app role). The app cannot grant it.
+- Someone who is removed from your organisation can still use a session already issued, for up to 8 hours. Removing them from `Workspace__Admins` takes effect at their next sign-in.
+
+## What is not built yet
+
+- **Groups and departments.** Quotas are per person, with a default and "everyone". Setting pages by group (for example a Microsoft 365 group or a Google Workspace organisational unit) needs the directory APIs. Tracked in an issue.
+- **Real printers and sending files.** Printers here are names the server prints to through `IPrintDispatcher`, which is simulated. See [05](05-open-decisions.md) and the open issues.
+- **Native phone sign-in** with the platform's own account picker. The web app works on phones today.
+- **A database.** People, printers and quotas are held in memory and are lost when the server restarts. Production needs `IPrintStore` backed by a database (issue #3).
diff --git a/docs/FAQ.md b/docs/FAQ.md
new file mode 100644
index 0000000..b873e9c
--- /dev/null
+++ b/docs/FAQ.md
@@ -0,0 +1,17 @@
+# Questions and answers
+
+Short answers. For error messages and what to do about them, read [Fixing problems](Fixing%20problems.md).
+
+**Is anything really printed?** Not yet. Printing goes through `IPrintDispatcher`, which is simulated. A real printer needs a real dispatcher ([issue #5](https://github.com/Hikki-dev/pull_printing_app/issues/5)).
+
+**Can I send my own file?** Not yet. The demo makes sample documents. See [issue #4](https://github.com/Hikki-dev/pull_printing_app/issues/4).
+
+**When do page limits start again?** On the 1st of every month, UTC.
+
+**What is the difference between the live demo and the full stack?** The live demo on Vercel runs entirely in your browser on sample data. The full stack runs the real server, with its sign-in, printers and limits. See [Hosting the demo](06-demo-hosting.md).
+
+**Do I lose my data if the server restarts?** Yes, for now. People, printers, limits and documents are held in memory until a database backs `IPrintStore` ([issue #3](https://github.com/Hikki-dev/pull_printing_app/issues/3)). Sign-in sessions survive a restart only if `Auth__SigningKey` is set.
+
+**Who can see my documents?** Only you. The server ignores any document that is not yours and waiting.
+
+**Is this a finished product?** No. It is a working demo and a prototype of the idea. See the Limits in the [README](../README.md#limits).
diff --git a/docs/Fixing problems.md b/docs/Fixing problems.md
new file mode 100644
index 0000000..f999503
--- /dev/null
+++ b/docs/Fixing problems.md
@@ -0,0 +1,60 @@
+# Fixing problems
+
+Quick answers first, then fixes. If your problem is not here, [open an issue](https://github.com/Hikki-dev/pull_printing_app/issues/new/choose) and say what you pressed, what you saw, and what you expected.
+
+## Quick answers
+
+The short ones are in [Questions and answers](FAQ.md). The fixes are below.
+
+## People printing
+
+| You see | Why | What to do |
+|---|---|---|
+| **Over your limit by N pages. Untick one.** | The documents ticked need more pages than you have left | Untick a document. Your limit starts again on the 1st |
+| **No pages left this month.** | You have used your pages | Ask your administrator for more, or wait for the 1st |
+| **No printer available** | No printer is set up, or all are switched off | Ask your administrator to add one |
+| **The printer could not print your documents. They are still waiting.** | The printer rejected them | Try again, or pick another printer. You were not charged |
+| **Your list has been refreshed.** | The list on screen was out of date (for example you printed on another device) | Check the list and press Print again |
+| **Your session has ended. Please sign in again.** | The session ran out (8 hours), or the server restarted | Sign in again |
+| **Cannot reach the print server.** | No connection, or a free host is waking up | Wait a minute and press **Try again** |
+| **Nothing waiting to print.** | You have no documents | In the demo, press **Send sample documents** |
+
+## People signing in
+
+| You see | Why | What to do |
+|---|---|---|
+| **That account is not allowed here** | Wrong organisation, wrong domain, or a personal account | Sign in with your work account |
+| **Your email address is not verified** | Google says the address is not verified | Verify it in your Google account |
+| **Your account did not tell us who you are** | The provider sent no identity | Tell your administrator |
+| **Sign-in did not work. Please try again.** | The provider or the server failed, or you cancelled | Try again. Administrators: see below |
+| Only a demo button, no work sign-in | Work sign-in is not set up, or its settings are incomplete | Administrators: see below |
+
+## Administrators
+
+| Problem | What to check |
+|---|---|
+| The Setup card lists things to do | Each line says what. They map to the settings in [Connecting your workspace](09-connecting-your-workspace.md#settings) |
+| Sign-in shows only the demo | Open `/api/auth/config`. If `provider` is `none`, a `Workspace__*` setting is missing. The server log names the missing one |
+| The provider says "redirect URI mismatch" | The address registered with Microsoft or Google must match exactly. The Setup card shows it, with a **Copy** button. It must be `https` |
+| Everyone is signed out whenever the server restarts | Set `Auth__SigningKey` to 32 or more random characters |
+| Someone who should be an administrator is not | Their email must be in `Workspace__Admins`, written as their work email. Microsoft: or assign the `PullPrint.Admin` app role. They must sign in again |
+| A printer's own screen asks which printer | Open the **Copy panel link** address, not the plain address. It ends with `?printer=` and the printer's id |
+| A panel link says No printer available | The printer in the link was removed or switched off |
+| A person is missing from the list | People appear the first time they sign in |
+| "Give everyone" changed someone I set by hand | It replaces every limit. Set their row again afterwards |
+| Quota boxes refuse a number | Whole numbers from 0 to 10000 only |
+
+## Running it
+
+| Problem | What to do |
+|---|---|
+| `flutter run` shows sample data only | That is the default. For a real server pass `--dart-define=USE_MOCK=false` ([README](../README.md#run-it-yourself)) |
+| The web app cannot reach the API | Build with `--dart-define=API_BASE_URL=...`, or serve the web build from the API's `wwwroot` so they share an address |
+| `dotnet run` says demo sign-in is off | Set `Demo__Enabled=true`, or run with `ASPNETCORE_ENVIRONMENT=Development` |
+| Sign-in works but you are bounced to sign-in at once | The signing key changed, or the server restarted. Set `Auth__SigningKey` |
+| First visit to a free host is slow | Free hosts sleep when idle and take about a minute to wake |
+| Tests fail on a fresh checkout | Run `flutter pub get`, then `flutter test` and `dotnet test backend.Tests`. CI runs the same |
+
+## Still stuck?
+
+Open an issue with the template. Say what you tried, and attach the server log with any secret removed. For anything about security, read [SECURITY.md](../SECURITY.md) first.
diff --git a/docs/Getting started.md b/docs/Getting started.md
new file mode 100644
index 0000000..6abe5a3
--- /dev/null
+++ b/docs/Getting started.md
@@ -0,0 +1,136 @@
+# Getting started
+
+This page walks through Pull Print one screen at a time, for the three kinds of people who use it: someone printing, someone at a printer's own screen, and an administrator. Every picture was taken from the running app.
+
+Click any picture on GitHub to open it full size.
+
+## Before you start
+
+You can try everything with nothing installed: open the [live demo](https://pull-print-demo.vercel.app). It runs on sample data, so nothing is really printed and no account is needed.
+
+To run your own copy, see the [README](../README.md#run-it-yourself). To use your organisation's accounts, see [Connecting your workspace](09-connecting-your-workspace.md).
+
+## If you are printing
+
+### Sign in
+
+
+
+Press the one button. There is no registration and no password: you sign in with your work account. In the demo, the same button opens a private sandbox and the banner at the top says so.
+
+Not sure what the demo is? Press **What is this?** in the banner.
+
+
+
+### Choose what to print
+
+
+
+* Only **your own** documents are listed, newest first.
+* The newest ones are ticked for you, stopping before anything goes over your limit.
+* The ring shows how many pages you have left **this month**. It starts again on the 1st.
+* Tap a document to tick or untick it. Tick **Select all** to choose everything.
+
+If you tick too much, Print switches off and says what to do:
+
+
+
+Untick a document until the button works again. Nothing is charged until a document really prints.
+
+### Pick a printer
+
+If more than one printer is set up, tap the printer name at the bottom.
+
+
+
+If you opened a printer's own link, the printer is already chosen and the name is not a button.
+
+### Print
+
+
+
+The confirmation names the printer, lists what printed and shows your pages left. If the printer rejected some documents, they are named and stay on your list, and you are not charged for them.
+
+## If you are at a printer's own screen
+
+An administrator opens each printer's **panel link** on the screen next to the printer. It is fixed to that printer, so there is no question about where to print.
+
+
+
+Sign in with your work account (the staff-card option is drawn but not built yet).
+
+
+
+Tap a document to include or leave it out, then press the large **Print** button. The printer's name and your pages left are at the top.
+
+
+
+Over the limit, the button is switched off and says so, the same as on a phone.
+
+
+
+The screen signs you out 20 seconds after printing, and after 60 seconds without a touch, so the next person never sees your documents. You can always press **Sign out**.
+
+## If you are an administrator
+
+Sign in with an account on your administrators list. You land on the administrator screen, which has everything in the order you need it.
+
+
+
+### 1. Check the setup
+
+The first card says **Setup is complete**, or **Finish setting up** and lists each thing still to do in plain words.
+
+
+
+With Microsoft or Google it also shows the exact sign-in address to register, with a **Copy** button.
+
+
+
+### 2. Add your printers
+
+
+
+Press **Add a printer**, enter a name and where it is.
+
+
+
+For each printer you can switch it **On or Off**, edit it, remove it, or press **Copy panel link**. Open the panel link on the screen next to that printer, in full screen. A switched-off printer is hidden from everyone but administrators, and nobody can print there.
+
+### 3. Set page limits
+
+
+
+* **New people start with** is the pages a month for anyone who signs in from now on.
+* **Give everyone** sets the same number for the whole organisation. It asks first, because it replaces every limit:
+
+ 
+
+* Each person has a row. Change the number and press **Save**. The bar shows pages used this month, and turns red when none are left.
+* People appear in the list the first time they sign in.
+
+### 4. Watch the jobs
+
+
+
+Search by person or file, and filter by status. A failed job says why, for example "printer offline".
+
+## Signing in with a work account
+
+When the server is set up for Microsoft 365 or Google Workspace, the button changes to match and says who can use it.
+
+ 
+
+Someone who is not allowed in sees the reason, and can try again:
+
+
+
+If the demo is still on, a **Try the demo instead** link is shown too. Turn the demo off for real use (`Demo__Enabled=false`).
+
+
+
+## What next
+
+* Something not working? See [Fixing problems](Fixing%20problems.md).
+* Connect your own accounts: [Connecting your workspace](09-connecting-your-workspace.md).
+* How the pieces fit and every route: [How it works](How%20it%20works.md).
diff --git a/docs/How it works.md b/docs/How it works.md
new file mode 100644
index 0000000..97496b5
--- /dev/null
+++ b/docs/How it works.md
@@ -0,0 +1,213 @@
+# How it works
+
+How the pieces fit, what the server decides, and every route with an example.
+
+## The pieces
+
+
+
+In detail:
+
+```
+Visitor's browser or phone
+ │
+ ▼
+Flutter app (frontend/lib)
+ screens ── PrintRepository ─┬─ MockPrintRepository sample data inside the app (offline demo, tests)
+ └─ HttpPrintRepository ──▶ ApiService ──▶ HTTPS
+ │
+ASP.NET Core API (backend) ▼
+ controllers: Auth · Printers · Jobs · Admin ── PrintStore (in memory) ── IPrintDispatcher (simulated)
+ sign-in: demo sandbox, or Microsoft / Google work account (OpenID Connect, done by the server)
+ session: one kind of server-signed token, whichever way the person signed in
+ limits: rate limits, size limits, sandbox caps
+```
+
+There are two ways to run the demo:
+
+| | Static (Vercel) | Full stack (Docker, for example Render) |
+|---|---|---|
+| What runs | The Flutter web app on built-in sample data | The API and the web app together |
+| Where data lives | In the visitor's browser tab | In the server's memory, one private sandbox per visitor |
+| Resets when | The page is reloaded | The server restarts, or 2 hours without use |
+| Needs a server | No | Yes |
+| Shows the real API and its rules | No | Yes |
+
+## Who decides what
+
+The app only shows things. **The server decides** who may do what, so a changed or hand-made request cannot get around the rules.
+
+| Rule | Where it is enforced |
+|---|---|
+| You need a valid, unexpired, correctly signed token | `Program.cs` (JWT bearer authentication) |
+| Admin routes need the Admin role | `AdminController`, `JobsController.All` (policy `Admin`) |
+| You only ever see and print your own waiting documents | `PrintStore.HeldJobs`, `PrintStore.Release` |
+| Printing never takes you over your page quota | `PrintStore.Release` (all or nothing) |
+| An administrator only reaches people in their own group | `PrintStore.AllJobs`, `Users`, `SetQuota` |
+| Quota changes are between 0 and 10000 pages | `AdminController` (`set-quota`, `default-quota`, `set-quota-all`) |
+| Only people from your organisation sign in | `WorkspaceIdentity.Map` (tenant, domain, verified email) |
+| Administrators are decided by the server | `Workspace__Admins`, or the Microsoft app role; never by the app |
+| Pages start again each month | `PrintStore` (period = UTC year and month) |
+| Printing only goes to a printer in your own group that is on | `PrintStore.Release` |
+| At most 50 documents per print, 12 waiting per person | `JobsController.Release`, `PrintStore.AddSample` |
+
+## Data
+
+- **PrintJob**: `id`, `userId`, `userName`, `fileName`, `pages`, `submittedAt`, `status` (`Held`, `Printed` or `Failed`), `failureReason`, `printerName` (once printed).
+- **User**: id (`g-…` for Google, `m-…` for Microsoft), display name, email, whether an administrator, page quota, pages used and the month they belong to, last seen, and a **sandbox id**.
+- **Printer**: `id`, `name`, `location`, `enabled`. Kept per sandbox, so a work organisation has one list and each demo visitor has their own three.
+- **Sandbox**: who can see and manage whom. Everyone who signs in for real shares the `default` group. Each demo visitor, and each demo administrator, gets a private one. A demo administrator's sandbox holds a private copy of four sample people.
+
+## Signing in
+
+**Demo.** `POST /api/auth/demo-login` creates a sandbox and returns a token signed by the server. It exists only when `Demo__Enabled` is true, and its tokens stop working the moment that is switched off.
+
+**Work account (Microsoft 365 or Google Workspace).** When the `Workspace__*` settings are complete the server does the whole sign-in, so the app holds no secrets:
+
+1. The app sends the browser to `GET /api/auth/login?returnTo=/…`. The server redirects to Microsoft or Google (authorization code flow with PKCE, `prompt=select_account`).
+2. The provider sends the browser back to `/api/auth/callback`. The server exchanges the code, then checks who it is (`WorkspaceIdentity.Map`): the right organisation, a verified email for Google, the right domain.
+3. `GET /api/auth/complete` adds the person if new (default pages a month), decides if they are an administrator, issues the server's own token and redirects to `returnTo#token=…`. A refused account goes to `returnTo#error=` with `wrong_account`, `unverified_email`, `no_identity` or `sign_in_failed`.
+4. The page keeps the fragment for the app and removes it from the address bar before the app starts. `returnTo` must be a path on this site, so sign-in cannot be used to send people elsewhere.
+
+Whatever way someone signed in, the token carries the same claims (`uid`, `name`, `role`, `kind`) and nothing else in the server cares which it was. Turning work sign-in or demo sign-in off makes that kind of token stop working at once. Setup steps: [09](09-connecting-your-workspace.md).
+
+## Errors
+
+Errors are JSON: `{ "error": "", "message": "", "pagesOver": }`.
+
+| Status | `error` | When |
+|---|---|---|
+| 400 | `no_jobs`, `too_many`, `bad_request` | Nothing chosen, more than 50 documents, an invalid quota |
+| 401 | | No token, or one that is wrong or expired. The app signs the person out with a message |
+| 403 | | Signed in but not allowed, for example a normal user on an admin route |
+| 404 | `not_found` | Documents that are not yours or not waiting, an unknown person, or demo sign-in switched off |
+| 409 | `quota_exceeded` | The documents need more pages than the person has left. Nothing prints |
+| 409 | `no_printer`, `printer_unavailable` | No printer is set up, or the chosen one is off or unknown. Nothing prints |
+| 409 | `too_many` | At most 50 printers |
+| 409 | `no_more_samples` | Demo only: twelve documents are already waiting, or all sample documents are in use |
+| 429 | | Too many requests from one address in a minute |
+| 500 | `server_error` | Something unexpected. The details stay in the server log |
+
+## Routes
+
+All routes except sign-in and `/healthz` need `Authorization: Bearer `.
+
+### `GET /api/auth/config`
+No token. What the sign-in screen offers.
+```json
+{ "provider": "google", "providerName": "Google", "domain": "example.com", "demo": false }
+```
+`provider` is `microsoft`, `google` or `none`.
+
+### `POST /api/auth/demo-login`
+```json
+// request
+{ "admin": false }
+// 200
+{ "token": "eyJ…", "userId": "demo-3f9a1c2b", "name": "Alice Tan", "isAdmin": false }
+```
+
+### `GET /api/auth/me`
+```json
+{ "userId": "demo-3f9a1c2b", "name": "Alice Tan", "isAdmin": false, "email": null }
+```
+
+### `GET /api/printers`
+```json
+[ { "id": "a190fbb8", "name": "Level 3 East", "location": "Third floor, east wing", "enabled": true } ]
+```
+Switched-off printers are listed only for administrators.
+
+### `GET /api/jobs/held`
+Your waiting documents, newest first.
+```json
+[ { "id": "a1b2c3d4", "userId": "demo-3f9a1c2b", "userName": "Alice Tan",
+ "fileName": "Q3 budget review.pdf", "pages": 12,
+ "submittedAt": "2026-10-22T09:00:00+00:00", "status": "Held", "failureReason": null } ]
+```
+
+### `GET /api/jobs/quota`
+```json
+{ "used": 12, "total": 50, "left": 38 }
+```
+
+### `POST /api/jobs/release`
+```json
+// request: send jobIds (a single jobId is also accepted). printerId is optional;
+// without it the first printer that is on is used
+{ "jobIds": ["a1b2c3d4", "e5f6a7b8"], "printerId": "a190fbb8" }
+// 200: only the documents that really printed are listed
+{ "printed": ["a1b2c3d4", "e5f6a7b8"], "pages": 15, "quota": { "used": 27, "total": 50, "left": 23 }, "printerName": "Level 3 East" }
+// 409: nothing printed, nothing charged
+{ "error": "quota_exceeded", "message": "Over your limit by 6 pages.", "pagesOver": 6 }
+```
+
+### `POST /api/jobs/sample` (demo only)
+Adds one sample document to your list and returns it. 409 `no_more_samples` when there are no more to add.
+
+### `GET /api/jobs` (administrators)
+Every job in the administrator's own group, newest first.
+
+### `GET /api/admin/setup` (administrators)
+What the **Setup** card shows.
+```json
+{ "provider": "Google", "providerName": "Google", "domain": "example.com", "demoEnabled": false,
+ "defaultQuota": 50, "people": 12, "printers": 0,
+ "redirectUri": "https://print.example.com/api/auth/callback",
+ "warnings": ["No printers yet. Add one so people can print."] }
+```
+`redirectUri` is the address to register with Microsoft or Google. `warnings` is empty when nothing is left to do.
+
+### `GET /api/admin/users` (administrators)
+```json
+[ { "userId": "…", "name": "Priya Nair", "email": null, "quota": { "used": 8, "total": 200, "left": 192 } } ]
+```
+
+### `POST /api/admin/set-quota` (administrators)
+```json
+{ "userId": "…", "quota": 80 }
+```
+200 on success, 404 if that person is not in the administrator's group, 400 if the number is outside 0 to 10000.
+
+### `POST /api/admin/default-quota`, `POST /api/admin/set-quota-all` (administrators)
+```json
+{ "quota": 80 }
+```
+`default-quota` sets the pages a month for people who sign in from now on. `set-quota-all` gives everyone in the group the same pages and replies `{ "changed": 12 }`. Both are 400 outside 0 to 10000.
+
+### `POST /api/admin/printers`, `PUT /api/admin/printers/{id}`, `DELETE /api/admin/printers/{id}` (administrators)
+```json
+{ "name": "Level 3 East", "location": "Third floor", "enabled": true }
+```
+`name` is required (up to 60 characters). `enabled` applies to `PUT`. Up to 50 printers. 404 for an unknown printer.
+
+### `GET /healthz`
+`{ "status": "ok" }`, no token needed. Used by hosts to check the server is up.
+
+## Settings
+
+Environment variables, with double underscores for the colon in a setting name.
+
+| Variable | Default | What it does |
+|---|---|---|
+| `Demo__Enabled` | `false` (`true` in the Docker image) | Allows demo sign-in and sample documents |
+| `Auth__SigningKey` | random at start | 32 or more characters. Set it so tokens survive a restart |
+| `Workspace__Provider` | empty | `Microsoft` or `Google`. Turns on work-account sign-in |
+| `Workspace__ClientId`, `__ClientSecret` | empty | From the app registration or OAuth client |
+| `Workspace__TenantId` | empty | Microsoft only: the directory id |
+| `Workspace__Domain` | empty | Required for Google. Optional for Microsoft: limits sign-in to one email domain |
+| `Workspace__Admins` | empty | Administrator email addresses, separated by commas or spaces |
+| `Workspace__AdminRole` | `PullPrint.Admin` | Microsoft app role that also makes an administrator |
+| `Workspace__DefaultQuota` | `50` | Pages a month for a first sign-in. Changeable on the administrator screen |
+| `RateLimit__LoginPerMinute` | `20` | Demo sign-ins a minute from one address |
+| `RateLimit__PerMinute` | `300` | All requests a minute from one address |
+| `Cors__AllowAnyOrigin` | `false` | Only for running the web app from a different address |
+
+Other limits are fixed in code: 300 sandboxes at once, sandboxes deleted after 2 hours idle, 16 KB request bodies.
+
+## Replacing the in-memory parts
+
+- **A database:** implement `IPrintStore` (`backend/services/PrintStore.cs`) and register it in `Program.cs`. The tests in `backend.Tests` describe the behaviour to keep.
+- **A real printer:** implement `IPrintDispatcher` (`backend/services/PrintDispatcher.cs`). Throw from `Print` to mark a job as failed; the message becomes the reason shown to administrators.
+- **Groups and directory:** quotas are per person. Per-group limits would read the Microsoft Graph or Google Admin SDK and are not built.
+- **Sending files:** nothing creates a waiting job except the demo sample route. Real submission is an open decision in [05](05-open-decisions.md).
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..3da33d6
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,29 @@
+# Documentation
+
+Guides for using and setting up Pull Print, and the design documents behind it. Start with **Getting started** if you are new.
+
+| Document | What it covers |
+|---|---|
+| [Getting started](Getting%20started.md) | Every screen with pictures: printing, the printer's own screen, administrators, work-account sign-in |
+| [09 Connecting your workspace](09-connecting-your-workspace.md) | Sign in with Microsoft 365 or Google Workspace, add printers, set page limits: the ten-minute setup |
+| [Fixing problems](Fixing%20problems.md) | Quick answers and what to do when something does not work |
+| [Questions and answers](FAQ.md) | Short answers: is anything printed, who sees my documents, what happens on restart |
+| [01 Product brief](01-product-brief.md) | Who uses it, the one job it must do fast, speed targets, scope |
+| [02 User flows](02-user-flows.md) | Step-by-step flows for printing, releasing and administering |
+| [03 Screen specs](03-screen-specs.md) | Each mockup with its purpose, contents, states and exact wording |
+| [04 Design guidelines](04-design-guidelines.md) | Colours, type, sizes, accessibility, and what we will not use |
+| [05 Open decisions](05-open-decisions.md) | Questions that change the design and need an answer |
+| [06 Hosting the demo](06-demo-hosting.md) | Putting the demo online for free, settings, what to expect |
+| [How it works](How%20it%20works.md) | How the pieces fit, who decides what, every route with an example |
+| [08 Review and fixes](08-review-and-fixes.md) | What went wrong from each user's point of view, how it was found, and the fix |
+
+## Pictures
+
+The screenshots and diagrams in `images/` are taken from the running app. [`tools/screenshots`](../tools/screenshots/README.md) explains how to make them again.
+
+## Mockups
+
+- Images used in the documents: [`design/screens/`](design/screens/) (PNG, 2x).
+- Editable source for each screen: [`design/source/`](design/source/) (`.dc.html`, one per screen). These come from the Claude Design canvas and open in it. Opened directly in a browser they render as a flat screen.
+
+The screens are mockups, not Flutter code. Sample names and numbers are made up.
diff --git a/docs/design/screens/01-phone-sign-in.png b/docs/design/screens/01-phone-sign-in.png
new file mode 100644
index 0000000..d179936
Binary files /dev/null and b/docs/design/screens/01-phone-sign-in.png differ
diff --git a/docs/design/screens/02-phone-my-jobs.png b/docs/design/screens/02-phone-my-jobs.png
new file mode 100644
index 0000000..cace01c
Binary files /dev/null and b/docs/design/screens/02-phone-my-jobs.png differ
diff --git a/docs/design/screens/03-phone-sent.png b/docs/design/screens/03-phone-sent.png
new file mode 100644
index 0000000..17fbe4f
Binary files /dev/null and b/docs/design/screens/03-phone-sent.png differ
diff --git a/docs/design/screens/04-panel-sign-in.png b/docs/design/screens/04-panel-sign-in.png
new file mode 100644
index 0000000..737e8f2
Binary files /dev/null and b/docs/design/screens/04-panel-sign-in.png differ
diff --git a/docs/design/screens/05-panel-release.png b/docs/design/screens/05-panel-release.png
new file mode 100644
index 0000000..0cd4aa9
Binary files /dev/null and b/docs/design/screens/05-panel-release.png differ
diff --git a/docs/design/screens/06-panel-printing.png b/docs/design/screens/06-panel-printing.png
new file mode 100644
index 0000000..45e34da
Binary files /dev/null and b/docs/design/screens/06-panel-printing.png differ
diff --git a/docs/design/screens/07-admin.png b/docs/design/screens/07-admin.png
new file mode 100644
index 0000000..e660be7
Binary files /dev/null and b/docs/design/screens/07-admin.png differ
diff --git a/docs/design/source/Admin.dc.html b/docs/design/source/Admin.dc.html
new file mode 100644
index 0000000..6e6d76e
--- /dev/null
+++ b/docs/design/source/Admin.dc.html
@@ -0,0 +1,117 @@
+
+
+
+
+Admin jobs and quotas
+
+
+
+
+
+
+
+