diff --git a/README.md b/README.md index 90f42bb..c35950f 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,10 @@ Give a remote job temporary access to an HTTPS service that requires a client certificate installed on your desktop. You choose the certificate, destination scope, and duration in the Companion. Your machine signs the TLS handshake. Your Integrator’s Gateway completes it and can read the traffic. -Countersign approval showing the Integrator branding, verified Integrator, requested host, two certificates, a selected fingerprint, duration, and Approve and Deny controls. + + + Countersign approval in the Integrator's colours, showing its name beside the verified origin, the checked request facts, two certificates with a selected fingerprint, duration presets, when access ends, and Deny and Approve controls. + **[Try it with curl](https://zeroae.github.io/countersign/try/).** Pair the Companion with the demo Integrator, pick one of the installed certificates, and compare its fingerprint with the one returned by the mTLS site. The demo runs its services and curl in Docker Compose. The Companion runs on your Linux desktop. @@ -24,7 +27,10 @@ Run `npx @zeroae/countersign` to open the desktop installer on Windows or macOS, ## How the handshake works -[![Countersign architecture showing the Workload and Gateway, the separate TLS connection to the protected site, and the desktop signing through the Broker.](docs/assets/diagrams/architecture.svg)](https://zeroae.github.io/countersign/architecture/) + + + Countersign architecture showing the Workload and Gateway, the separate TLS connection to the protected site, and the desktop signing through the Broker. + Each Integrator hosts its own Broker and Gateway. Solid arrows carry the job's traffic. Dashed arrows carry authorization and signing messages. One desktop Companion can pair with several Integrators. The default Gateway runs beside one Workload. A shared Gateway is also available for Linux hosts. diff --git a/docs/assets/screenshots/approval-branding-dark.png b/docs/assets/screenshots/approval-branding-dark.png new file mode 100644 index 0000000..0d93272 Binary files /dev/null and b/docs/assets/screenshots/approval-branding-dark.png differ diff --git a/docs/assets/screenshots/approval-branding.png b/docs/assets/screenshots/approval-branding.png index 19eee46..6c45b45 100644 Binary files a/docs/assets/screenshots/approval-branding.png and b/docs/assets/screenshots/approval-branding.png differ diff --git a/docs/assets/screenshots/approval-selected-dark.png b/docs/assets/screenshots/approval-selected-dark.png new file mode 100644 index 0000000..3e043a1 Binary files /dev/null and b/docs/assets/screenshots/approval-selected-dark.png differ diff --git a/docs/assets/screenshots/approval-selected.png b/docs/assets/screenshots/approval-selected.png index 6bd42eb..b510fdb 100644 Binary files a/docs/assets/screenshots/approval-selected.png and b/docs/assets/screenshots/approval-selected.png differ diff --git a/docs/assets/screenshots/approval-unselected-dark.png b/docs/assets/screenshots/approval-unselected-dark.png new file mode 100644 index 0000000..b2b0a36 Binary files /dev/null and b/docs/assets/screenshots/approval-unselected-dark.png differ diff --git a/docs/assets/screenshots/approval-unselected.png b/docs/assets/screenshots/approval-unselected.png index a20ffbb..03ef215 100644 Binary files a/docs/assets/screenshots/approval-unselected.png and b/docs/assets/screenshots/approval-unselected.png differ diff --git a/docs/assets/screenshots/branding-alternate-dark.png b/docs/assets/screenshots/branding-alternate-dark.png new file mode 100644 index 0000000..a6138a0 Binary files /dev/null and b/docs/assets/screenshots/branding-alternate-dark.png differ diff --git a/docs/assets/screenshots/branding-alternate.png b/docs/assets/screenshots/branding-alternate.png index ec85734..6a99d49 100644 Binary files a/docs/assets/screenshots/branding-alternate.png and b/docs/assets/screenshots/branding-alternate.png differ diff --git a/docs/assets/screenshots/branding-none-dark.png b/docs/assets/screenshots/branding-none-dark.png new file mode 100644 index 0000000..38cff5f Binary files /dev/null and b/docs/assets/screenshots/branding-none-dark.png differ diff --git a/docs/assets/screenshots/branding-none.png b/docs/assets/screenshots/branding-none.png new file mode 100644 index 0000000..2f861c8 Binary files /dev/null and b/docs/assets/screenshots/branding-none.png differ diff --git a/docs/assets/screenshots/branding-review-dark.png b/docs/assets/screenshots/branding-review-dark.png new file mode 100644 index 0000000..4ecab54 Binary files /dev/null and b/docs/assets/screenshots/branding-review-dark.png differ diff --git a/docs/assets/screenshots/branding-review.png b/docs/assets/screenshots/branding-review.png new file mode 100644 index 0000000..36f7234 Binary files /dev/null and b/docs/assets/screenshots/branding-review.png differ diff --git a/docs/assets/screenshots/dialog-remove-dark.png b/docs/assets/screenshots/dialog-remove-dark.png new file mode 100644 index 0000000..40cfd1b Binary files /dev/null and b/docs/assets/screenshots/dialog-remove-dark.png differ diff --git a/docs/assets/screenshots/dialog-remove.png b/docs/assets/screenshots/dialog-remove.png new file mode 100644 index 0000000..bfbf485 Binary files /dev/null and b/docs/assets/screenshots/dialog-remove.png differ diff --git a/docs/assets/screenshots/integrator-detail-dark.png b/docs/assets/screenshots/integrator-detail-dark.png new file mode 100644 index 0000000..289c4be Binary files /dev/null and b/docs/assets/screenshots/integrator-detail-dark.png differ diff --git a/docs/assets/screenshots/integrator-detail.png b/docs/assets/screenshots/integrator-detail.png new file mode 100644 index 0000000..e801820 Binary files /dev/null and b/docs/assets/screenshots/integrator-detail.png differ diff --git a/docs/assets/screenshots/integrators-list-dark.png b/docs/assets/screenshots/integrators-list-dark.png new file mode 100644 index 0000000..8d19933 Binary files /dev/null and b/docs/assets/screenshots/integrators-list-dark.png differ diff --git a/docs/assets/screenshots/integrators-list.png b/docs/assets/screenshots/integrators-list.png new file mode 100644 index 0000000..4c90d15 Binary files /dev/null and b/docs/assets/screenshots/integrators-list.png differ diff --git a/docs/assets/screenshots/pairing-companion-dark.png b/docs/assets/screenshots/pairing-companion-dark.png new file mode 100644 index 0000000..b71c55f Binary files /dev/null and b/docs/assets/screenshots/pairing-companion-dark.png differ diff --git a/docs/assets/screenshots/pairing-companion.png b/docs/assets/screenshots/pairing-companion.png index 24f8fdf..3d1e1ab 100644 Binary files a/docs/assets/screenshots/pairing-companion.png and b/docs/assets/screenshots/pairing-companion.png differ diff --git a/docs/assets/screenshots/queue-switch-dark.png b/docs/assets/screenshots/queue-switch-dark.png new file mode 100644 index 0000000..2cb7d4d Binary files /dev/null and b/docs/assets/screenshots/queue-switch-dark.png differ diff --git a/docs/assets/screenshots/queue-switch.png b/docs/assets/screenshots/queue-switch.png new file mode 100644 index 0000000..b414faa Binary files /dev/null and b/docs/assets/screenshots/queue-switch.png differ diff --git a/docs/assets/screenshots/raw/approval-selected-dark.png b/docs/assets/screenshots/raw/approval-selected-dark.png new file mode 100644 index 0000000..31017aa Binary files /dev/null and b/docs/assets/screenshots/raw/approval-selected-dark.png differ diff --git a/docs/assets/screenshots/raw/approval-selected.png b/docs/assets/screenshots/raw/approval-selected.png index 81e2f1a..64968c2 100644 Binary files a/docs/assets/screenshots/raw/approval-selected.png and b/docs/assets/screenshots/raw/approval-selected.png differ diff --git a/docs/assets/screenshots/raw/approval-unselected-dark.png b/docs/assets/screenshots/raw/approval-unselected-dark.png new file mode 100644 index 0000000..0e93ad8 Binary files /dev/null and b/docs/assets/screenshots/raw/approval-unselected-dark.png differ diff --git a/docs/assets/screenshots/raw/approval-unselected.png b/docs/assets/screenshots/raw/approval-unselected.png index 3940c2b..342fcb4 100644 Binary files a/docs/assets/screenshots/raw/approval-unselected.png and b/docs/assets/screenshots/raw/approval-unselected.png differ diff --git a/docs/assets/screenshots/raw/boxes.json b/docs/assets/screenshots/raw/boxes.json index de5c559..fe5a95f 100644 --- a/docs/assets/screenshots/raw/boxes.json +++ b/docs/assets/screenshots/raw/boxes.json @@ -51,66 +51,367 @@ ] } }, + "approval-selected-dark.png": { + "scale": 2, + "width": 660, + "height": 1140, + "boxes": { + "selected": [ + 24, + 660.3, + 636, + 791.9 + ], + "expiry": [ + 24, + 898.2, + 636, + 954 + ], + "header": [ + 20, + 12, + 429, + 66 + ], + "plate": [ + 514.2, + 1108, + 650, + 1134 + ], + "facts": [ + 24, + 225.3, + 636, + 422.7 + ], + "presets": [ + 24, + 842.2, + 636, + 886.2 + ] + } + }, "approval-selected.png": { "scale": 2, - "width": 704, - "height": 713, + "width": 660, + "height": 1140, "boxes": { "selected": [ - 32, - 402.6, - 672, - 491.6 + 24, + 660.3, + 636, + 791.9 ], "expiry": [ - 19, - 569.8, - 300, - 588.8 + 24, + 898.2, + 636, + 954 + ], + "header": [ + 20, + 12, + 429, + 66 + ], + "plate": [ + 514.2, + 1108, + 650, + 1134 ], - "branding": [ - 19, - 17, - 685, - 97.2 + "facts": [ + 24, + 225.3, + 636, + 422.7 + ], + "presets": [ + 24, + 842.2, + 636, + 886.2 ] } }, - "approval-unselected.png": { + "approval-unselected-dark.png": { "scale": 2, - "width": 704, - "height": 678, + "width": 660, + "height": 1140, "boxes": { "identities": [ - 32, - 313.6, - 672, - 491.6 + 24, + 444.7, + 636, + 791.9 ], - "approve": [ - 19, - 623.8, - 109.3, - 660.1 + "actions": [ + 362, + 1045, + 636, + 1089 + ], + "queue": [ + 24, + 132, + 636, + 150.1 + ] + } + }, + "approval-unselected.png": { + "scale": 2, + "width": 660, + "height": 1140, + "boxes": { + "identities": [ + 24, + 444.7, + 636, + 791.9 ], "actions": [ - 19, - 623.8, - 182.9, - 660.1 + 362, + 1045, + 636, + 1089 + ], + "queue": [ + 24, + 132, + 636, + 150.1 + ] + } + }, + "branding-alternate-dark.png": { + "scale": 2, + "width": 660, + "height": 952, + "boxes": { + "header": [ + 20, + 12, + 391.9, + 66 + ], + "approve": [ + 504, + 857, + 636, + 901 ] } }, "branding-alternate.png": { "scale": 2, - "width": 704, - "height": 609, + "width": 660, + "height": 952, + "boxes": { + "header": [ + 20, + 12, + 391.9, + 66 + ], + "approve": [ + 504, + 857, + 636, + 901 + ] + } + }, + "branding-none-dark.png": { + "scale": 2, + "width": 660, + "height": 927, "boxes": { - "branding": [ - 19, - 17, - 685, - 82.2 + "brand": [ + 20, + 18, + 191.2, + 56 + ], + "note": [ + 24, + 379.7, + 533.5, + 394.7 + ] + } + }, + "branding-none.png": { + "scale": 2, + "width": 660, + "height": 927, + "boxes": { + "brand": [ + 20, + 18, + 191.2, + 56 + ], + "note": [ + 24, + 379.7, + 533.5, + 394.7 + ] + } + }, + "branding-review-dark.png": { + "scale": 2, + "width": 660, + "height": 760, + "boxes": { + "review": [ + 41, + 276.3, + 619, + 383.4 + ], + "buttons": [ + 41, + 419.5, + 351.4, + 455.5 + ] + } + }, + "branding-review.png": { + "scale": 2, + "width": 660, + "height": 760, + "boxes": { + "review": [ + 41, + 276.3, + 619, + 383.4 + ], + "buttons": [ + 41, + 419.5, + 351.4, + 455.5 + ] + } + }, + "dialog-remove-dark.png": { + "scale": 2, + "width": 660, + "height": 760, + "boxes": { + "dialog": [ + 120, + 270.9, + 540, + 489.1 + ] + } + }, + "dialog-remove.png": { + "scale": 2, + "width": 660, + "height": 760, + "boxes": { + "dialog": [ + 120, + 270.9, + 540, + 489.1 + ] + } + }, + "integrator-detail-dark.png": { + "scale": 2, + "width": 660, + "height": 930, + "boxes": { + "notice": [ + 41, + 249.6, + 619, + 332.1 + ], + "approvals": [ + 41, + 368.8, + 619, + 635.5 + ], + "self": [ + 341.6, + 684, + 446.5, + 701 + ] + } + }, + "integrator-detail.png": { + "scale": 2, + "width": 660, + "height": 930, + "boxes": { + "notice": [ + 41, + 249.6, + 619, + 332.1 + ], + "approvals": [ + 41, + 368.8, + 619, + 635.5 + ], + "self": [ + 341.6, + 684, + 446.5, + 701 + ] + } + }, + "integrators-list-dark.png": { + "scale": 2, + "width": 660, + "height": 760, + "boxes": { + "rows": [ + 24, + 121.2, + 636, + 347 + ], + "pair": [ + 24, + 383.6, + 636, + 450.5 + ] + } + }, + "integrators-list.png": { + "scale": 2, + "width": 660, + "height": 760, + "boxes": { + "rows": [ + 24, + 121.2, + 636, + 347 + ], + "pair": [ + 24, + 383.6, + 636, + 450.5 ] } }, @@ -178,29 +479,129 @@ ] } }, + "pairing-companion-dark.png": { + "scale": 2, + "width": 660, + "height": 760, + "boxes": { + "facts": [ + 24, + 197.2, + 636, + 310 + ], + "code": [ + 24, + 324, + 636, + 455.9 + ] + } + }, "pairing-companion.png": { "scale": 2, - "width": 760, - "height": 299, + "width": 660, + "height": 760, + "boxes": { + "facts": [ + 24, + 197.2, + 636, + 310 + ], + "code": [ + 24, + 324, + 636, + 455.9 + ] + } + }, + "queue-switch-dark.png": { + "scale": 2, + "width": 660, + "height": 1004, + "boxes": { + "banner": [ + 24, + 132, + 636, + 171.6 + ], + "approve": [ + 504, + 909, + 636, + 953 + ], + "reason": [ + 24, + 913.2, + 318.9, + 947 + ] + } + }, + "queue-switch.png": { + "scale": 2, + "width": 660, + "height": 1004, "boxes": { - "confirmation": [ - 28, - 210.7, - 482.3, - 229.7 + "banner": [ + 24, + 132, + 636, + 171.6 + ], + "approve": [ + 504, + 909, + 636, + 953 + ], + "reason": [ + 24, + 913.2, + 318.9, + 947 + ] + } + }, + "scope-wildcard-dark.png": { + "scale": 2, + "width": 660, + "height": 1047, + "boxes": { + "scope": [ + 41, + 358, + 619, + 405.7 + ], + "warning": [ + 41, + 417.7, + 619, + 500.2 ] } }, "scope-wildcard.png": { "scale": 2, - "width": 704, - "height": 624, + "width": 660, + "height": 1047, "boxes": { "scope": [ - 19, - 229.4, - 401.5, - 273 + 41, + 358, + 619, + 405.7 + ], + "warning": [ + 41, + 417.7, + 619, + 500.2 ] } }, diff --git a/docs/assets/screenshots/raw/branding-alternate-dark.png b/docs/assets/screenshots/raw/branding-alternate-dark.png new file mode 100644 index 0000000..509fb37 Binary files /dev/null and b/docs/assets/screenshots/raw/branding-alternate-dark.png differ diff --git a/docs/assets/screenshots/raw/branding-alternate.png b/docs/assets/screenshots/raw/branding-alternate.png index 78387d3..728612a 100644 Binary files a/docs/assets/screenshots/raw/branding-alternate.png and b/docs/assets/screenshots/raw/branding-alternate.png differ diff --git a/docs/assets/screenshots/raw/branding-none-dark.png b/docs/assets/screenshots/raw/branding-none-dark.png new file mode 100644 index 0000000..44acce7 Binary files /dev/null and b/docs/assets/screenshots/raw/branding-none-dark.png differ diff --git a/docs/assets/screenshots/raw/branding-none.png b/docs/assets/screenshots/raw/branding-none.png new file mode 100644 index 0000000..dd7bb92 Binary files /dev/null and b/docs/assets/screenshots/raw/branding-none.png differ diff --git a/docs/assets/screenshots/raw/branding-review-dark.png b/docs/assets/screenshots/raw/branding-review-dark.png new file mode 100644 index 0000000..ea3d55d Binary files /dev/null and b/docs/assets/screenshots/raw/branding-review-dark.png differ diff --git a/docs/assets/screenshots/raw/branding-review.png b/docs/assets/screenshots/raw/branding-review.png new file mode 100644 index 0000000..a0698b8 Binary files /dev/null and b/docs/assets/screenshots/raw/branding-review.png differ diff --git a/docs/assets/screenshots/raw/dialog-remove-dark.png b/docs/assets/screenshots/raw/dialog-remove-dark.png new file mode 100644 index 0000000..ec2e3e3 Binary files /dev/null and b/docs/assets/screenshots/raw/dialog-remove-dark.png differ diff --git a/docs/assets/screenshots/raw/dialog-remove.png b/docs/assets/screenshots/raw/dialog-remove.png new file mode 100644 index 0000000..c9a0fed Binary files /dev/null and b/docs/assets/screenshots/raw/dialog-remove.png differ diff --git a/docs/assets/screenshots/raw/integrator-detail-dark.png b/docs/assets/screenshots/raw/integrator-detail-dark.png new file mode 100644 index 0000000..d7ca49d Binary files /dev/null and b/docs/assets/screenshots/raw/integrator-detail-dark.png differ diff --git a/docs/assets/screenshots/raw/integrator-detail.png b/docs/assets/screenshots/raw/integrator-detail.png new file mode 100644 index 0000000..9968e71 Binary files /dev/null and b/docs/assets/screenshots/raw/integrator-detail.png differ diff --git a/docs/assets/screenshots/raw/integrators-list-dark.png b/docs/assets/screenshots/raw/integrators-list-dark.png new file mode 100644 index 0000000..eae8b02 Binary files /dev/null and b/docs/assets/screenshots/raw/integrators-list-dark.png differ diff --git a/docs/assets/screenshots/raw/integrators-list.png b/docs/assets/screenshots/raw/integrators-list.png new file mode 100644 index 0000000..a59a646 Binary files /dev/null and b/docs/assets/screenshots/raw/integrators-list.png differ diff --git a/docs/assets/screenshots/raw/pairing-companion-dark.png b/docs/assets/screenshots/raw/pairing-companion-dark.png new file mode 100644 index 0000000..81c4d81 Binary files /dev/null and b/docs/assets/screenshots/raw/pairing-companion-dark.png differ diff --git a/docs/assets/screenshots/raw/pairing-companion.png b/docs/assets/screenshots/raw/pairing-companion.png index ef733f5..46e7af7 100644 Binary files a/docs/assets/screenshots/raw/pairing-companion.png and b/docs/assets/screenshots/raw/pairing-companion.png differ diff --git a/docs/assets/screenshots/raw/queue-switch-dark.png b/docs/assets/screenshots/raw/queue-switch-dark.png new file mode 100644 index 0000000..7f050f2 Binary files /dev/null and b/docs/assets/screenshots/raw/queue-switch-dark.png differ diff --git a/docs/assets/screenshots/raw/queue-switch.png b/docs/assets/screenshots/raw/queue-switch.png new file mode 100644 index 0000000..db24de2 Binary files /dev/null and b/docs/assets/screenshots/raw/queue-switch.png differ diff --git a/docs/assets/screenshots/raw/scope-wildcard-dark.png b/docs/assets/screenshots/raw/scope-wildcard-dark.png new file mode 100644 index 0000000..0f198ce Binary files /dev/null and b/docs/assets/screenshots/raw/scope-wildcard-dark.png differ diff --git a/docs/assets/screenshots/raw/scope-wildcard.png b/docs/assets/screenshots/raw/scope-wildcard.png index b580e31..e777571 100644 Binary files a/docs/assets/screenshots/raw/scope-wildcard.png and b/docs/assets/screenshots/raw/scope-wildcard.png differ diff --git a/docs/assets/screenshots/scope-wildcard-dark.png b/docs/assets/screenshots/scope-wildcard-dark.png new file mode 100644 index 0000000..6450dc5 Binary files /dev/null and b/docs/assets/screenshots/scope-wildcard-dark.png differ diff --git a/docs/assets/screenshots/scope-wildcard.png b/docs/assets/screenshots/scope-wildcard.png index e56845b..500443d 100644 Binary files a/docs/assets/screenshots/scope-wildcard.png and b/docs/assets/screenshots/scope-wildcard.png differ diff --git a/docs/companion.md b/docs/companion.md index 2169711..8a29be4 100644 --- a/docs/companion.md +++ b/docs/companion.md @@ -12,54 +12,80 @@ Choose the desktop artifact for your operating system and processor from the dis | macOS | Open the `.pkg` installer, then open **Countersign** from Applications. | A Keychain identity whose private key is accessible to Security.framework. | | Linux | Install the `.deb` with your package manager, or make the `.AppImage` executable and launch it in your desktop session. | A PKCS#11 token available through p11-kit or the configured module. Unlock your encrypted login keyring before pairing. | -Enable **Start at login** if this computer should receive requests after sign-in. Open the window again from the tray using **Open Countersign**. Linux users can also [build and install the local conda package](develop.md#install-with-conda-on-linux). +Enable **Start at login** under **Settings** if this computer should receive requests after sign-in. Open the window again from the tray using **Open Countersign**. Linux users can also [build and install the local conda package](develop.md#install-with-conda-on-linux). + +## Find your way around + +The window has three tabs. **Requests** shows one approval request at a time and opens by itself when a request arrives. **Integrators** lists your pairings, each with its own details page. **Settings** holds **Start at login**. The window follows your system's light or dark appearance. + +![The Integrators tab in Countersign's purple theme, listing portal.example (Harbor Ledger), audit.example (Lantern Audit, branding change to review) and jobs.example with their status, above the form to pair another Integrator.](assets/screenshots/integrators-list.png#gh-light-mode-only)![The Integrators tab in Countersign's purple theme, listing portal.example (Harbor Ledger), audit.example (Lantern Audit, branding change to review) and jobs.example with their status, above the form to pair another Integrator.](assets/screenshots/integrators-list-dark.png#gh-dark-mode-only) + +While a request, a pairing confirmation or an Integrator's details are on screen, the whole window takes on that Integrator's colours, with its logo, name and copy in the header beside its verified origin. Lists, Settings and Integrators that publish no branding use Countersign's purple theme. Whatever the colours, the Companion draws the request facts, warnings, certificate details and the **Deny** and **Approve** buttons the same way, and the countersign mark stays at the bottom right. [What a theme can change](reference/widget.md#brand-the-companion-prompt) ## Pair an Integrator -1. Get the Integrator's HTTPS origin from your signed-in service. Enter the full origin, including a nonstandard port, in **Integrator origin** and choose **Pair**. -2. In the browser, check the origin, sign into the intended account and enter the code displayed by your Companion. -3. Back in the Companion, check the verified origin, account and code before choosing **Confirm pairing**. The Integrator appears under **Paired Integrators**. A second Integrator gets its own pairing and connection. +1. Get the Integrator's HTTPS origin from your signed-in service. On the **Integrators** tab, enter the full origin, including a nonstandard port, in **Integrator origin** and choose **Pair**. +2. The Companion opens the Integrator in your browser and shows a pairing code. Sign into the intended account in the browser and enter that code. +3. Back in the Companion, check the verified origin, account and code before choosing **Confirm pairing**. The Integrator then appears in the list. A second Integrator gets its own pairing and connection. -The two confirmation screens are illustrated in the [demo walkthrough](try.md#pair-the-desktop). If a paired Integrator changes its logo, name, copy or colours, review the old and new appearance under **Review branding change**. Choose **Accept new branding** to adopt it. The verified origin and approval controls belong to the Companion. +![Companion in Harbor Ledger's colours asking the user to confirm the verified Integrator origin and account, with the pairing code 7B9D F613 D8 in large type above Cancel pairing and Confirm pairing.](assets/screenshots/pairing-companion.png#gh-light-mode-only)![Companion in Harbor Ledger's colours asking the user to confirm the verified Integrator origin and account, with the pairing code 7B9D F613 D8 in large type above Cancel pairing and Confirm pairing.](assets/screenshots/pairing-companion-dark.png#gh-dark-mode-only) + +The browser half of pairing is illustrated in the [demo walkthrough](try.md#pair-the-desktop). ## Decide what to approve -Open the local notification, choose **Open Companion** on the Integrator's site, or open the tray app. Read the verified origin and account first, then check that the Context corresponds to the job you started. **Requested host** identifies the immediate connection. **Approval covers** describes every destination the job can reach with this grant. +Open the local notification, choose **Open Companion** on the Integrator's site, or open the tray app. Requests wait in a queue and the Companion shows the oldest first, with a count of the others. Read the verified origin and account first under **Checked by Countersign**, then check that the Context corresponds to the job you started. **Requested host** identifies the immediate connection. **Approval covers** describes every destination the job can reach with this grant. + +![Companion in Harbor Ledger's colours with the second of two identically named certificates selected, the 1 h duration preset, Access ends 7:39 PM today, and the Deny and Approve buttons.](assets/screenshots/approval-selected.png#gh-light-mode-only)![Companion in Harbor Ledger's colours with the second of two identically named certificates selected, the 1 h duration preset, Access ends 7:39 PM today, and the Deny and Approve buttons.](assets/screenshots/approval-selected-dark.png#gh-dark-mode-only) + +The Companion lists the eligible installed certificates. With **two or more**, you must select one before **Approve** becomes available. When certificates share a name, the part of each SHA-256 fingerprint where they first differ is highlighted, and a pattern drawn from the fingerprint sits beside each one. Also compare the issuer and expiry. With one eligible certificate, it is selected and still needs your approval. If none qualify, or the certificate provider is unavailable, a warning explains why and you can deny the request. Only the selected public chain is sent to the Broker. -[![Companion with the second of two identically named certificates selected, its SHA-256 fingerprint, the duration, the resulting expiry and the decision controls.](assets/screenshots/approval-selected.png)](assets/screenshots/approval-selected.png) +Pick **15 min**, **1 h** or **8 h**, or choose **Custom** to enter minutes. The administrator's limit disables longer presets. **Access ends** shows the time the approval stops and how far away it is. If the selected certificate expires first, a warning says that access ends with the certificate. Approval lets this job use the certificate for further handshakes within that scope and duration. A native provider may separately prompt to unlock a key or token. -The Companion lists the eligible installed certificates. With **two or more**, you must select one before **Approve** becomes available. Use the issuer, expiry and SHA-256 fingerprint to distinguish identical names. With one eligible certificate, it is selected and still needs your approval. If none qualify, you can deny or resolve the provider issue. Only the selected public chain is sent to the Broker. +Each request that appears locks **Approve** for about a second, so a click meant for the previous screen cannot approve it. When the next request comes from a different Integrator, a banner reads **Now showing a request from** and the origin, and the window changes to that Integrator's colours. -Enter the duration in seconds and check **Expires by**. The initial default is one hour, subject to the administrator's limit and the selected certificate's expiry. Approval lets this job use the certificate for further handshakes within that scope and duration. A native provider may separately prompt to unlock a key or token. +![Companion after the queue moved on to a Lantern Audit request: a dark banner reads Now showing a request from audit.example, the window uses Lantern Audit's amber colours, and Approve is disabled with the reason that the request is from a different Integrator.](assets/screenshots/queue-switch.png#gh-light-mode-only)![Companion after the queue moved on to a Lantern Audit request: a dark banner reads Now showing a request from audit.example, the window uses Lantern Audit's amber colours, and Approve is disabled with the reason that the request is from a different Integrator.](assets/screenshots/queue-switch-dark.png#gh-dark-mode-only) ### Read a wildcard approval In this example, the job requested `reports.team.example:9444`. The administrator enabled approval for the whole `*.team.example:9444` entry. That can also cover `archive.team.example:9444` under the same policy. The apex, deeper names and other ports fall outside this scope. The normal setting even for a wildcard entry is an approval for the single requested host. -[![Companion shows reports.team.example:9444 as the requested host and *.team.example:9444 as the approval scope.](assets/screenshots/scope-wildcard.png)](assets/screenshots/scope-wildcard.png) +![Companion shows reports.team.example:9444 as the requested host and *.team.example:9444 as the approval scope, followed by a warning that the approval covers more than the requested host.](assets/screenshots/scope-wildcard.png#gh-light-mode-only)![Companion shows reports.team.example:9444 as the requested host and *.team.example:9444 as the approval scope, followed by a warning that the approval covers more than the requested host.](assets/screenshots/scope-wildcard-dark.png#gh-dark-mode-only) Choose **Deny** if the scope is wider than you intended. The Integrator can request access again after it changes the policy. If several desktops receive an offer, the first committed decision settles it for all of them. An approved grant uses the identity on the desktop that won the request. -## End access or remove a computer +## Manage an Integrator + +Choose an Integrator on the **Integrators** tab to open its details. The page shows the connection status, current approvals, the Companions paired to your account, and any security notices. **This computer** marks this Companion's own pairing in the device list. + +![Harbor Ledger's details page with a warning that another Companion connected to the account, three approvals with Revoke access and Retry revocation buttons, two paired Companions with this computer flagged, and the pairing actions.](assets/screenshots/integrator-detail.png#gh-light-mode-only)![Harbor Ledger's details page with a warning that another Companion connected to the account, three approvals with Revoke access and Retry revocation buttons, two paired Companions with this computer flagged, and the pairing actions.](assets/screenshots/integrator-detail-dark.png#gh-dark-mode-only) | Action | What happens | |---|---| | Close the window | The Companion stays in the tray and continues to receive requests and sign approved handshakes. | | Choose **Quit** in the tray | New handshakes require the approving desktop to reconnect. Established traffic can continue while its leases renew, up to the grant's expiry. | | Choose **Revoke access** on an approval | The Companion queues the revocation and shows when the Broker records it. From that point outstanding traffic has at most its existing lease budget. | -| Choose **Remove from this computer** | Deletes this computer's pairing key and local state. Use the Integrator's device controls to end the remote pairing and grants. | -| Choose **Revoke pairing at Integrator** | Opens the verified Integrator's device-management page. Select the pairing to forget. You can also use that page from another computer if this one is lost. | +| Choose **Remove from this computer** | After you confirm in the dialog, deletes this computer's pairing key and local state. Use the Integrator's device controls to end the remote pairing and grants. | +| Choose **Revoke pairing at Integrator** | After you confirm, opens the verified Integrator's device-management page. Select the pairing to forget. You can also use that page from another computer if this one is lost. | + +![A Companion dialog asking Remove jobs.example from this computer?, explaining that access already granted stays active until it is revoked at the Integrator, with Cancel and a red Remove from this computer button.](assets/screenshots/dialog-remove.png#gh-light-mode-only)![A Companion dialog asking Remove jobs.example from this computer?, explaining that access already granted stays active until it is revoked at the Integrator, with Cancel and a red Remove from this computer button.](assets/screenshots/dialog-remove-dark.png#gh-dark-mode-only) + +If another Companion connects to your account, a notice gives its connection information and device ID. Review the ID before choosing **Disconnect device** or **Disconnect all other devices**, and confirm in the dialog. Removing another device revokes its grants. An independent lease deadline bounds the remaining traffic. [How revocation works](architecture.md#when-access-ends) + +### Review a branding change + +If a paired Integrator changes its logo, name, copy or colours, its details page shows the current and proposed branding side by side. Choose **Accept new branding** to adopt it, which also changes the colours the window takes on for that Integrator. Choose **Keep current** to dismiss it. The Companion does not ask again about the same proposal, only about a later change. The verified origin and approval controls belong to the Companion either way. -If another Companion connects to your account, its entry includes connection information and a device ID. Review the ID before choosing **Disconnect device** or **Disconnect all other devices**. Removing another device revokes its grants. An independent lease deadline bounds the remaining traffic. [How revocation works](architecture.md#when-access-ends) +![Lantern Audit's details page showing its current amber branding beside a proposed purple one, with Accept new branding and Keep current buttons.](assets/screenshots/branding-review.png#gh-light-mode-only)![Lantern Audit's details page showing its current amber branding beside a proposed purple one, with Accept new branding and Keep current buttons.](assets/screenshots/branding-review-dark.png#gh-dark-mode-only) ## When an approval doesn't work | What you see | What to check | |---|---| -| No desktop notification | Open **Approval requests**, then check the connection for the specific Integrator. A web notification or deep link locates a pending request. It cannot approve one. | +| No desktop notification | Open the **Requests** tab, then check the Integrator's status on the **Integrators** tab. A web notification or deep link locates a pending request. It cannot approve one. | | No eligible installed certificate | Check that the identity is valid for client authentication, has its private key, and matches the issuer and signature schemes allowed for this destination. Ask the Integrator which identity it expects. | | Provider unavailable | Unlock the native provider and reconnect the token if applicable. On Linux verify that p11-kit can see the token in the same login session. Request access again. | -| Approved, but the job still cannot connect | Look for **Ready for handshakes** on the approving desktop. If the original connection attempt timed out, retry it from the job. The Integrator can distinguish an approval from an accepted upstream handshake. | +| Approved, but the job still cannot connect | Look for **Ready for handshakes** in the Integrator's details on the approving desktop. If the original connection attempt timed out, retry it from the job. The Integrator can distinguish an approval from an accepted upstream handshake. | | Revocation queued | Reconnect to the verified Integrator and use **Retry revocation**. If the desktop cannot reconnect, revoke through the Integrator. The lease cutoff starts from the Broker's recorded decision. | ## Install from npm diff --git a/docs/develop.md b/docs/develop.md index b02fc22..63f1dc7 100644 --- a/docs/develop.md +++ b/docs/develop.md @@ -69,7 +69,7 @@ pnpm exec playwright install chromium # once pnpm screenshots ``` -The script writes raw captures and `boxes.json`, the CSS-pixel box of each highlighted element, to `docs/assets/screenshots/raw/`. `scripts/annotate_screenshots.py`, run by the same command, reads those boxes and draws the callouts onto the copies the pages embed. Change the fixtures or selectors in the capture script and the labels in the annotation script, then look at every changed image before committing. Set `CHROMIUM_PATH` or pass `--browser` to use another Chromium build, and `--only widget,job-result` to recapture a few shots. Embed a demo shot with its `-dark` twin and the `#gh-light-mode-only` and `#gh-dark-mode-only` suffixes, as for diagrams. CI does not run the capture. +The script writes raw captures and `boxes.json`, the CSS-pixel box of each highlighted element, to `docs/assets/screenshots/raw/`. `scripts/annotate_screenshots.py`, run by the same command, reads those boxes and draws the callouts onto the copies the pages embed. Change the fixtures or selectors in the capture script and the labels in the annotation script, then look at every changed image before committing. Set `CHROMIUM_PATH` or pass `--browser` to use another Chromium build, and `--only widget,job-result` to recapture a few shots. Every shot has a `-dark` twin, the Companion's included. Embed both with the `#gh-light-mode-only` and `#gh-dark-mode-only` suffixes, as for diagrams. The Companion shots render `packages/companion/src` with a stubbed `window.countersign`; extend the stub when the preload API changes. CI does not run the capture. ## What CI and release tags produce diff --git a/docs/reference/widget.md b/docs/reference/widget.md index 19bf46b..08afb29 100644 --- a/docs/reference/widget.md +++ b/docs/reference/widget.md @@ -135,7 +135,11 @@ Serve a UTF-8 JSON manifest at `https:///.well-known/counters "displayName": "Finance workspace", "copy": "Quarterly reconciliation", "logo": "/assets/finance.png", - "colors": { "accent": "#235a44", "background": "#f3f8f5" } + "colors": { + "accent": "#235a44", + "background": "#f3f8f5", + "dark": { "accent": "#7fcfa8", "background": "#0f1c16" } + } } ``` @@ -144,12 +148,33 @@ Serve a UTF-8 JSON manifest at `https:///.well-known/counters | `version`, `displayName` | Version `1` and display name up to 80 UTF-16 code units. | | `copy` | Optional text up to 240 UTF-16 code units. Text fields reject control and format characters. | | `colors.accent`, `colors.background` | Optional six-digit hex colors. Defaults are `#164e63` and `#ffffff`. | +| `colors.dark` | Optional object with both `accent` and `background` as six-digit hex colors, used when the desktop is in dark mode. Without it the Companion derives dark colors from the light pair. | | `logo` | Optional relative or absolute same-origin PNG URL up to 1,024 UTF-16 code units. The download limit is 128 KiB and each dimension is at most 512 pixels. | -The manifest has an 8 KiB limit. The Companion stores accepted branding with its pairing. A changed manifest appearance or changed logo image is presented for review. The user can keep the old appearance. On first pairing, an unavailable or invalid manifest leaves the verified origin visible with neutral branding. [Theme validation](https://github.com/zeroae/countersign/blob/fbb5aa7c951f8b70a238f3351140aa44a6184adf/packages/companion/src/theme.js) +The manifest holds only these fields: hex colors and a PNG logo, with no CSS, fonts, SVG or HTML. It has an 8 KiB limit. The Companion stores accepted branding with its pairing. A change to any field, including `colors.dark` or the logo image at the same URL, is presented to the user for review on the Integrator's details page. The user can accept it or keep the current branding. On first pairing, an unavailable or invalid manifest leaves the Companion in its own theme, with the verified origin visible. [Theme validation](https://github.com/zeroae/countersign/blob/main/packages/companion/src/theme.js) + +### How the Companion uses your branding + +While one of your requests, your pairing confirmation or your details page is on screen, the whole Companion window takes on your colors: the header band, window background, surfaces, borders, tabs, links, focus ring and the **Approve** fill. The header shows your logo, display name and copy. Lists, settings and Integrators without a manifest use Countersign's purple theme. + +The Companion treats your two colors as a starting point. It derives the full palette in OKLCH, keeping your hue, and then adjusts lightness until every text and control pair meets WCAG AA contrast in both light and dark mode. A very light accent therefore becomes a darker header band and **Approve** fill, and a dark background stays dark only in dark mode. [Palette derivation](https://github.com/zeroae/countersign/blob/main/packages/companion/src/palette.js) + +![Companion approval for Harbor Ledger, the demo Integrator, in its teal colours. Callouts mark the header with its logo, name and copy beside the verified origin portal.example, the request facts box, and the fixed countersign mark at the bottom right.](../assets/screenshots/approval-branding.png#gh-light-mode-only)![Companion approval for Harbor Ledger, the demo Integrator, in its teal colours. Callouts mark the header with its logo, name and copy beside the verified origin portal.example, the request facts box, and the fixed countersign mark at the bottom right.](../assets/screenshots/approval-branding-dark.png#gh-dark-mode-only) + +![The same Companion approval screen for Lantern Audit, a second fictional Integrator, in its amber colours. Callouts mark its header and the Approve button, filled with its clamped accent.](../assets/screenshots/branding-alternate.png#gh-light-mode-only)![The same Companion approval screen for Lantern Audit, a second fictional Integrator, in its amber colours. Callouts mark its header and the Approve button, filled with its clamped accent.](../assets/screenshots/branding-alternate-dark.png#gh-dark-mode-only) + +### What stays the same in every theme + +No manifest value can change the labels, order or visibility of these parts, or recolor them: -![Companion approval for Harbor Ledger, the demo Integrator, with its blue branding banner and logo highlighted](../assets/screenshots/approval-branding.png) +1. The countersign mark at the bottom right of the window, on a fixed plate. +2. The verified origin, always next to your display name, for example "Harbor Ledger · portal.example ✓ verified". The name never appears alone. +3. The request facts: account, Context, requested host and approval scope, always present in the same order and wording, in clamped colors only. +4. Warnings and errors, such as a wildcard scope, an unavailable certificate provider, a certificate that ends access early, or no eligible certificate. They use a fixed component with an icon and fixed colors. +5. **Deny** and **Approve**, with fixed labels, **Deny** first, equal size, and **Deny** outlined. +6. Certificate details at full contrast: fingerprint, issuer, **Access ends** and the sentence saying the Gateway can read and send traffic until access ends. +7. When the queue moves to a request from a different Integrator, a fixed **Now showing a request from** banner, with **Approve** disabled for about a second and the reason shown. -![The same Companion approval screen for Lantern Audit, a second fictional Integrator, with its amber branding banner highlighted](../assets/screenshots/branding-alternate.png) +Your logo appears only in the header, never beside the decision controls. Branding never reaches desktop notifications, which carry only a generic message. -Compare the branding area in the two prompts. The verified origin, exact host and approval scope, selected certificate, duration and **Approve**/**Deny** controls are drawn by the Companion. +![A request from jobs.example, an Integrator without a manifest, in Countersign's purple theme with a note that the Integrator has not provided branding.](../assets/screenshots/branding-none.png#gh-light-mode-only)![A request from jobs.example, an Integrator without a manifest, in Countersign's purple theme with a note that the Integrator has not provided branding.](../assets/screenshots/branding-none-dark.png#gh-dark-mode-only) diff --git a/docs/specs/2026-11-17-countersign-design.md b/docs/specs/2026-11-17-countersign-design.md index 3cb2f76..ec0dc00 100644 --- a/docs/specs/2026-11-17-countersign-design.md +++ b/docs/specs/2026-11-17-countersign-design.md @@ -153,9 +153,13 @@ Broker policy binds trust and optional account-to-certificate mapping to the des ## Companion branding and notification channels -At pairing fetch `https:///.well-known/countersign.json` over validated HTTPS from the verified Integrator origin. Proposed manifest fields are schema version, plain-text display name, same-origin raster logo reference, accent/background colors and optional plain-text explanatory copy. Bound lengths, image bytes/dimensions and allowed color syntax; reject active content, redirects to other origins, markup, CSS, scripts, navigation and bidirectional control characters. Decode images to bounded local assets. Cache the normalized manifest, decoded logo, content digest and verified origin in the pairing. On a malformed/unavailable theme use neutral branding and show the verified origin. Refetch on reconnect with rate limits. A content change, including changed logo bytes at the same URL, produces a visible old/new review. Keep the accepted version until the person accepts the change. +At pairing fetch `https:///.well-known/countersign.json` over validated HTTPS from the verified Integrator origin. Proposed manifest fields are schema version, plain-text display name, same-origin raster logo reference, accent/background colors, an optional dark-mode accent/background pair (`colors.dark`) and optional plain-text explanatory copy. The manifest carries only hex colors and the PNG logo: no CSS, fonts, SVG or HTML. Bound lengths, image bytes/dimensions and allowed color syntax; reject active content, redirects to other origins, markup, CSS, scripts, navigation and bidirectional control characters. Decode images to bounded local assets. Cache the normalized manifest, decoded logo, content digest and verified origin in the pairing. On a malformed/unavailable theme use neutral branding and show the verified origin. Refetch on reconnect with rate limits. A content change, including changed dark colors or logo bytes at the same URL, produces a visible old/new review. Keep the accepted version until the person accepts the change. The person can also keep the current branding, which dismisses that proposal until the content changes again. -Only the authenticated receiving pairing selects its theme. Neither a request field nor a deep link can choose an origin, logo or copy. Render theme inside a bounded presentation area. Companion-owned unthemeable chrome always shows verified Integrator origin, account and Context, exact host:port, any broader wildcard scope, selected certificate (identity, issuer and fingerprint), effective duration and expiry, gateway trust disclosure, and **Approve / Deny** controls. No theme can cover, resize away, recolor or rename security controls. A long name, low-contrast color or logo resembling a button must leave the security decision legible and accessible. +Only the authenticated receiving pairing selects its theme. Neither a request field nor a deep link can choose an origin, logo or copy. While that pairing's request, pairing confirmation or detail view is on screen, the whole Companion window takes its theme: header band, window background, surfaces, borders, tabs, links, focus ring and the Approve fill. Lists, settings and pairings without a manifest use the Countersign theme. The main process follows the OS light/dark appearance and sets the window background from the stored theme of the pairing on screen, never from a renderer-supplied color. Derive the palette from the manifest colors in OKLCH and clamp lightness until every text and control pair meets WCAG AA in both appearances. The renderer receives validated hex values only and applies them as CSS custom properties under the existing CSP. The header shows the logo, display name and copy; the logo never appears in the content area beside the decision. + +Fixed in every theme, never themeable: (1) a countersign mark on a fixed plate at the bottom right of the window; (2) the verified origin beside the display name, which never appears alone; (3) the request facts, account, Context, exact host:port and approval scope, always present in the same order and wording, in clamped colors; (4) warnings and errors, including a broader wildcard scope, an unavailable provider, a certificate that ends access early and no eligible certificate, as a fixed component with an icon and fixed colors; (5) **Deny / Approve** with fixed labels, Deny first, equal size and Deny outlined; (6) certificate identity, issuer and fingerprint, effective duration and expiry, and the gateway trust disclosure at full contrast; (7) when the queue moves to a different pairing's request, a fixed banner naming its origin, with Approve disabled for about a second and the reason shown. Requests appear one at a time, oldest first, with a count of the rest. No theme value can change labels, order or visibility, or cover, resize away, recolor or rename security controls. A long name, low-contrast color or logo resembling a button must leave the security decision legible and accessible. Theme data never reaches notifications. + +The approved prototype is in [mockups/companion-theming](mockups/companion-theming/). Its **Middle ground** mode is the design; see [mockups/README.md](mockups/README.md). All three notification paths carry only an opaque high-entropy ID as application payload. Transport routing/subscription data remains necessary. No authority, certificate, host, Context, theme override or callback URL travels in a notification. @@ -252,7 +256,7 @@ Enter the printed HTTPS origin in the Companion. Sign in using the temporary log ### Configure an Integrator 1. Give the Broker a TLS server certificate, key, SQLite path, independent backend credential, Workload HMAC key and client trust anchors. Set `origin` to the public Integrator authority including its port. Set `listen` to the private listening address. Publish the exact WebSocket path `/v1/companion` under the Integrator HTTPS origin. Forward WebSocket upgrades with the `countersign.v1` subprotocol. Keep backend, admin and Gateway endpoints on authenticated service paths. -2. Serve `/.well-known/countersign.json` over HTTPS. A minimal manifest is `{"version":1,"displayName":"Example","colors":{"accent":"#164e63","background":"#ffffff"}}`. Optional fields are `copy` and a same-origin PNG `logo` URL. The Companion pins the origin at pairing and asks the user to accept later branding changes. +2. Serve `/.well-known/countersign.json` over HTTPS. A minimal manifest is `{"version":1,"displayName":"Example","colors":{"accent":"#164e63","background":"#ffffff"}}`. Optional fields are `copy`, `colors.dark` with its own `accent` and `background`, and a same-origin PNG `logo` URL. The Companion pins the origin at pairing and asks the user to accept later branding changes. 3. Register destinations in both processes with matching IDs, versions and patterns. For group approval set `whole_wildcard: true` in the Broker and `approval: "whole_wildcard"` in the Gateway. The default is one exact destination. Each Gateway entry has a `roots` PEM path for upstream server authentication. Internal destinations require an exact entry and explicit `private_networks` prefixes. Broker `client_ca_file` supplies the default client trust. Per-entry `client_trust` accepts `ca_file`, `user_fingerprints` and a revocation profile. The Gateway also accepts a per-entry `revocation` profile. CRL and OCSP files are bounded administrator-imported DER objects. 4. Start the Broker with `countersign-broker broker.json`. Authenticate users in the Integrator. The backend mints short-lived Workload credentials by posting the server-derived binding to `/v1/backend/workloads`. Write the token to the Gateway's protected credential path and refresh that file atomically. Put the sidecar listener on an endpoint reachable exclusively by its Workload. 5. Run `countersign-gateway serve gateway.json`. Deliver the four exports from `countersign-gateway env gateway.json` to the Workload. Mount the public CA at the same path read-only. On changes to destination rules, retire existing authority, update the version in both service configurations, and restart the sidecar. diff --git a/docs/specs/mockups/README.md b/docs/specs/mockups/README.md new file mode 100644 index 0000000..7e3fc57 --- /dev/null +++ b/docs/specs/mockups/README.md @@ -0,0 +1,22 @@ +# Design mockups + +The owner reviewed these clickable prototypes before the matching code was written. They are kept here as the design reference, next to the [design record](../2026-11-17-countersign-design.md). The handbook build skips everything under `docs/specs/`. + +| Mockup | Published prototype | Implemented in | +| --- | --- | --- | +| [Companion: whole-app Integrator theming](companion-theming/) | https://claude.ai/artifact/9j7jajgJrdWYaQUmcAHQfj | #13 | +| [Demo Integrator: Harbor Ledger site and Countersign widget](demo-integrator/) | https://claude.ai/artifact/KrQCjkZ2yBTwjTVj5b6yDc | #11 | + +## Reading them + +- **Running a prototype:** each one is a Claude artifact. `Main.dc.html` holds the markup, styles and logic, and `canvas.json` holds the canvas settings. Both depend on a runtime script that claude.ai provides, so opening `Main.dc.html` from disk will not run the prototype. To click through one, open its published link. The links are private; ask the owner for access. +- **Using the source:** the HTML, CSS and JavaScript are plain text. Read them for exact colours, spacing, wording and states, or diff them when a mockup changes. The Companion palette derivation (OKLCH with WCAG AA clamps) is in the companion mockup's script. + +## Which parts are decided + +- **Companion:** build the **Middle ground** mode. The **Strict** and **Open** modes exist only for comparison. The design record's "Companion branding and notification channels" section lists the elements that stay fixed in every theme. +- **Demo Integrator:** the layout and states are decided, but Harbor Ledger's colour changed afterwards. It is teal (`#0f6b6b` on `#eef6f4`; dark `#5cc8bd` on `#0f1f1e`), as in the Companion mockup, not the blue this mockup shows. + +## Changing a mockup + +Ask Claude to update the published artifact by its link. Then copy the new `Main.dc.html` and `canvas.json` here in the same pull request as the code change, so the reference and the implementation stay together. diff --git a/docs/specs/mockups/companion-theming/Main.dc.html b/docs/specs/mockups/companion-theming/Main.dc.html new file mode 100644 index 0000000..a48b8ca --- /dev/null +++ b/docs/specs/mockups/companion-theming/Main.dc.html @@ -0,0 +1,971 @@ + + + + +Countersign Companion prototype + + + + + + + + + +
+ + +
+
+ +
+ + countersign + + {{activeHost}} + +
+
+ +
+ + {{activeName}}{{activeCopy}} + + {{activeHost}} verified + +
+
+ +
+ +
+ +
+ +

{{banner}}

+
+
Request {{qPos}} of {{qTotal}} · oldest first{{qWaiting}}
+ +

Approval request

+

Let this job use a client certificate?

+ +
+

Checked by Countersign

+
+
Integrator
{{offer.origin}}
+
Account
{{offer.user}}
+
Context
{{offer.context}}
+
Requested host
{{offer.host}}
+
Approval covers
{{offer.scope}}
+
+ +
+ +

This approval covers more than the requested host.Any host matching {{offer.scope}}, such as archive.team.example:9444, can use the certificate until access ends. Deny if you only meant {{offer.host}}.

+
+
+
+ + +
+

Provided by {{originHost}}. Name, text and colours are not checked.

+
+ + + +
{{brand.name}}{{brand.copy}}
+
+
+
+ +

This Integrator has not provided branding, so Countersign's own theme is shown.

+
+ +
+ Certificate + +

{{dupCount}} certificates are named {{dupName}}. Compare the highlighted part of each fingerprint and the pattern beside it.

+
+ + + + +
+ No eligible certificate on this computer +

A certificate must allow client authentication, have its private key here, and match the issuers this destination accepts.

+

Ask the Integrator which certificate it expects, or deny this request.

+
+
+ + + +
+ + +
+

How long?

+
+ + + +
+ +
+ + Up to {{maxLabel}} +
+
+

Your administrator allows up to {{maxLabel}}, so longer presets are unavailable.

+
+ Access ends + {{untilTime}} + {{untilDay}} +
+ +
+ +

Shortened to the certificate's expiryThis certificate expires at {{certExpiry}}, so access ends then.

+
+
+
+
+ +

Until access ends, the Integrator's Gateway can read and send traffic to {{offer.scope}} using this certificate.

+
+ + +

Approved

+

The job can use your certificate

+
+

{{originHost}} can use {{selName}} ({{selShort}}) for {{offer.scope}} until {{untilTime}} {{untilDayShort}}.

+

Waiting for the Gateway. The approval shows Ready for handshakes once the first handshake is signed.

+
+
+ +

Denied

+

Request denied

+

{{originHost}} can request access again after it changes the request.

+
+ +
+ + +
+
+
+ +
+

{{reason}}

+ + +
+
+
+ + +
+ +

No pending requests

+

When a job asks to use one of your certificates, it opens here and Countersign notifies you. Closing this window keeps Countersign running in the tray.

+
+
+ + +
+

Pairing request

+

Confirm this pairing?

+
+

Checked by Countersign

+
+
Integrator
{{focus.origin}}
+
Account
{{focus.user}}
+
+
+
+

Pairing code

+

{{codeGrouped}}

+

Check that your browser shows the same code for this account, then confirm here. If anything differs, cancel.

+
+
+
+

Pairing lets {{focus.host}} send you approval requests. It cannot approve anything by itself.

+ + +
+
+ + +
+

{{flash}}

+

Paired Integrators

+ + + +

Pair another Integrator

+
+ + +
+

Countersign opens the Integrator in your browser. Sign in there and enter the code shown here.

+
+
+ + +
+
+

{{flash}}

+
+
+ + {{pr.origin}}{{pr.name}} · {{pr.user}} + {{pr.status}} +
+ + +
+ +

{{n.title}}{{n.meta}}. Check the device list below.

+
+
+ + +

Branding change to review

+
+
+

Current

+
{{pr.cur.name}}{{pr.cur.copyOrDash}}
+
+
+

Proposed by {{pr.host}}

+
{{pr.next.name}}{{pr.next.copyOrDash}}
+
+
+

Accepting also changes the colours this whole window takes on for {{pr.host}}.

+
+ + needs new IPC +
+
+ + +

Approvals

+ +
+
+ {{ap.host}} + {{ap.context}} · covers {{ap.scope}} · SHA-256 {{ap.short}} + {{ap.status}} · ends {{ap.until}} +
+ + + +
+
+
+ + +

Companions on this account

+ +
+
+ {{d.pairing}}This computer · needs new field + {{d.state}} · {{d.addr}} +
+ + + +
+
+
+ +
+ + + +
+
+
+
+ + +
+

Settings

+
+ +
+
+

Appearance

+

Follows your system's light or dark setting. While an Integrator's request is open, the window uses that Integrator's colours.

+
+
+

Closing and quitting

+

Closing this window keeps Countersign in the tray, receiving requests and signing approved handshakes. Choose Quit in the tray to stop it; new handshakes then wait until you reopen it.

+
+
+
+
+ +
+ countersign +
+
+ + +
+ +
+
+
+
+
+ + + diff --git a/docs/specs/mockups/companion-theming/canvas.json b/docs/specs/mockups/companion-theming/canvas.json new file mode 100644 index 0000000..c915909 --- /dev/null +++ b/docs/specs/mockups/companion-theming/canvas.json @@ -0,0 +1 @@ +{"v":3,"createdOnFiles":{"v":1,"at":"2026-11-18T02:30:00Z"},"title":"Countersign Companion redesign","launch":{"view":"focused","file":"Main.dc.html"},"pages":[],"boards":{"Main.dc.html":{"x":0,"y":0,"w":1200,"h":1180,"title":"Companion prototype","is_interactive":true}},"order":["Main.dc.html"],"notes":{},"designSystems":[]} diff --git a/docs/specs/mockups/demo-integrator/Main.dc.html b/docs/specs/mockups/demo-integrator/Main.dc.html new file mode 100644 index 0000000..d40db4f --- /dev/null +++ b/docs/specs/mockups/demo-integrator/Main.dc.html @@ -0,0 +1,426 @@ + + + + +Harbor Ledger demo Integrator + + + + + + + + + +
+
+ + +
+
+

Demo Integrator site — clickable mockups

+
+ Harbor Ledger page (Integrator owns it) + Countersign widget + Prototype-only control +
+
+ + +
+ Variant +
+ + +
+ + +
+
+ +
+ How access ended +
+ + + +
+
+
+
+ + +
+ +
+
+ +
+ Harbor Ledger + Client reporting workspace +
+
+ + + + +
+ Signed in as u-42 + +
+
+
+ + + +
+
+

Sign in

+

This demo uses a temporary secret. The launcher printed the path of the file that holds it.

+
+ + +
+ +
+
+
+ + + +
+ + +
+ +
+
+
+ Context +

Q3 close reconciliation

+
+ {{jobStatus}} +
+
+
Context ID
close-q3
+
Workload
export-981 · gen 1
+
Destination
ledger.partner.example:443
+
Companion
{{pairLabel}}
+
+
+ + + +
+ +

Use your client certificate for this job

+

The statement export reads from the partner ledger with your installed client certificate. Its private key stays on your computer. Pair the Countersign Companion once, then approve each job when it asks.

+
+ +

Companion paired

+

Confirm the account in your Companion too. When it shows Connected, choose Request access to start the job.

+
+
+
+ + + +
+

Pair your Companion

+
    +
  1. Open Countersign, choose Pair, and enter https://portal.example
  2. +
  3. Type the code the Companion shows. Signed in as u-42.
  4. +
  5. Confirm the account in the Companion when it asks.
  6. +
+
+
+ + +
+ +
+
+
+ + + +
+

Waiting for your approval

+

The job asked for ledger.partner.example:443. Its first request waits while you choose a certificate and a duration in the Companion.

+ +
+ +
+ Your Companion isn't connected + Open Countersign on your computer. The request stays pending until it times out at 7:52 PM; after that, request access again. +
+
+
+
+
+ + + +
+
+

Access approved

+ Access ends in {{countdown}} +
+
    + +
  • + {{p}} +
  • +
    +
+
+
Requested host
ledger.partner.example:443
+
Approval covers
ledger.partner.example:443
+
Certificate
CN=Demo user
+
Approval ID
ap_7QkV2mXrN4cWpL9sTbHe1A
+
SHA-256
c64a4b8b8bcdac1a7ac2bedcd13c520f4abfc07d5765d68df67f56ed0058f00b
+
+
+ + + + +
+

Closing the Companion can leave this connection usable until its lease expires. A new handshake needs the Companion online. Forget Companion 7B9DF613D8 and revoke its grants

+
+
+ + + +
+
+ +
+ {{endTitle}} + {{endBody}} +
+
+

A new request starts a fresh approval. If the job's original request already timed out, the job has to send another one after you approve.

+
+
+
+
+ + + +
+
+ + + +
+
+
+
+ Job export-981 · Q3 close reconciliation +

Statement fetched

+
+ HTTP 200 +
+
GET https://ledger.partner.example/statements/latest
+
+

Which key signed the handshake?

+
+
+ Fingerprint the site received + c64a4b8b8bcdac1a7ac2bedcd13c520f4abfc07d5765d68df67f56ed0058f00b + Subject: Demo user +
+
+ Certificate you selected in the Companion + c64a4b8b8bcdac1a7ac2bedcd13c520f4abfc07d5765d68df67f56ed0058f00b + CN=Demo user · Countersign demo client-ca +
+
+

+ Fingerprints match — the site saw the key you approved +

+

Matching subject names alone can't identify the key. Compare the full SHA-256 fingerprint.

+
+
+ + +
+
+
+
+
+ +
+
+
+ + + diff --git a/docs/specs/mockups/demo-integrator/canvas.json b/docs/specs/mockups/demo-integrator/canvas.json new file mode 100644 index 0000000..d007968 --- /dev/null +++ b/docs/specs/mockups/demo-integrator/canvas.json @@ -0,0 +1 @@ +{"v":3,"createdOnFiles":{"v":1,"at":"2026-11-18T01:40:00Z"},"title":"Demo Integrator mockups","launch":{"view":"focused","file":"Main.dc.html"},"pages":[],"boards":{"Main.dc.html":{"x":0,"y":0,"w":1280,"h":1180,"title":"Harbor Ledger demo Integrator — clickable flow","expand":"fill","is_interactive":true}},"order":["Main.dc.html"],"notes":{},"designSystems":[]} diff --git a/docs/try.md b/docs/try.md index 78e963b..75b0fd9 100644 --- a/docs/try.md +++ b/docs/try.md @@ -22,22 +22,22 @@ Replace the app path with your executable. If you have Chromium installed, you c The screenshots below are rendered from fixtures with the example names from [Add Countersign to a service](integrate.md): origin `https://portal.example`, account `u-42` and host `ledger.partner.example:443`. Your run shows the printed `https://localhost` origin, `demo-user` and `site.test:9444`. -1. Enter the printed HTTPS origin in the Companion’s **Integrator origin** field. Choose **Pair**. +1. Open the Companion’s **Integrators** tab. Enter the printed HTTPS origin in **Integrator origin** and choose **Pair**. The Companion shows a pairing code. 2. In the browser tab opened by the Companion, sign in with the temporary secret from the printed file. Enter the pairing code shown in the Companion and choose **Confirm pairing**. ![Harbor Ledger, the demo Integrator, asking for the code shown in the Companion, with the Countersign widget beside the form.](assets/screenshots/pairing-browser.png#gh-light-mode-only)![Harbor Ledger, the demo Integrator, asking for the code shown in the Companion, with the Countersign widget beside the form.](assets/screenshots/pairing-browser-dark.png#gh-dark-mode-only) -3. In the Companion, check that the origin and account belong to this demo. Choose **Confirm pairing**. The paired Integrator should show **Connected**. +3. In the Companion, check that the origin and account belong to this demo and that the code matches the browser. Choose **Confirm pairing**. The Integrator appears in the list with **Connected**. - ![Companion asking the user to confirm the verified Integrator origin, the account and the pairing code.](assets/screenshots/pairing-companion.png) + ![Companion in Harbor Ledger's colours asking the user to confirm the verified Integrator origin and account, with the pairing code 7B9D F613 D8 in large type above Cancel pairing and Confirm pairing.](assets/screenshots/pairing-companion.png#gh-light-mode-only)![Companion in Harbor Ledger's colours asking the user to confirm the verified Integrator origin and account, with the pairing code 7B9D F613 D8 in large type above Cancel pairing and Confirm pairing.](assets/screenshots/pairing-companion-dark.png#gh-dark-mode-only) ## Choose a certificate and verify it -Type `curl` at the launcher's prompt. The Workload already has the proxy address and the public sidecar CA. The first request waits while you decide. +Type `curl` at the launcher's prompt. The Workload already has the proxy address and the public sidecar CA. The first request waits while you decide, and the Companion opens its **Requests** tab. -![Companion listing two identically named certificates for the same host, with Approve disabled until one is selected.](assets/screenshots/approval-unselected.png) +![Companion showing the oldest of two waiting requests in Harbor Ledger's colours, with two identically named certificates whose fingerprints differ in the highlighted groups, and Approve disabled until one is selected.](assets/screenshots/approval-unselected.png#gh-light-mode-only)![Companion showing the oldest of two waiting requests in Harbor Ledger's colours, with two identically named certificates whose fingerprints differ in the highlighted groups, and Approve disabled until one is selected.](assets/screenshots/approval-unselected-dark.png#gh-dark-mode-only) -Read **Verified Integrator**, **Context**, **Requested host** and **Approval covers**. Choose one certificate, note its SHA-256 fingerprint, set the duration in seconds, and choose **Approve**. The site obtains the certificate from the authenticated TLS connection and returns its fingerprint. A capture from the demo returned: +Read **Integrator**, **Account**, **Context**, **Requested host** and **Approval covers** under **Checked by Countersign**. Choose one certificate, note its SHA-256 fingerprint, pick a duration, check **Access ends**, and choose **Approve**. The site obtains the certificate from the authenticated TLS connection and returns its fingerprint. A capture from the demo returned: ```json {"fingerprint":"c64a4b8b8bcdac1a7ac2bedcd13c520f4abfc07d5765d68df67f56ed0058f00b","subject":"Demo user"} @@ -49,6 +49,6 @@ Each launch creates fresh certificates. Compare the response to the fingerprint ## End access -Choose **Revoke access** under the approval in the Companion. Wait for **Broker recorded revocation**, then type `curl` again. A new connection from that Workload should fail. An explicit **Request access** from the Integrator starts a fresh approval. Type `quit` at the launcher prompt to remove the demo containers and disposable local state. +In the Companion, open **Integrators**, choose the demo Integrator and choose **Revoke access** under the approval. Wait for **Broker recorded revocation**, then type `curl` again. A new connection from that Workload should fail. An explicit **Request access** from the Integrator starts a fresh approval. Type `quit` at the launcher prompt to remove the demo containers and disposable local state. -If the request stalls, first look for **Connected** in the Companion, then for a pending request under **Approval requests**. An empty certificate list points to desktop identity discovery. A request that fails after approval needs a check of upstream trust and certificate acceptance. [Companion troubleshooting](companion.md#when-an-approval-doesnt-work) · [Integrator troubleshooting](integrate.md) +If the request stalls, first look for **Connected** in the Companion, then for a pending request on the **Requests** tab. An empty certificate list points to desktop identity discovery. A request that fails after approval needs a check of upstream trust and certificate acceptance. [Companion troubleshooting](companion.md#when-an-approval-doesnt-work) · [Integrator troubleshooting](integrate.md) diff --git a/examples/demo-integrator/compose_demo.py b/examples/demo-integrator/compose_demo.py index b472525..383adb1 100644 --- a/examples/demo-integrator/compose_demo.py +++ b/examples/demo-integrator/compose_demo.py @@ -139,8 +139,9 @@ def verify(desktop, browser, origin, fixture, curl, state, url): with web.expect_event("page", timeout=35000) as opened: desktop_page.get_by_role("button",name="Pair",exact=True).click() tab=opened.value - expect(desktop_page.locator("#pending")).to_contain_text("Pairing code") - code=desktop_page.locator("#pending").inner_text().split("Pairing code ")[-1].strip() + # The Companion shows the code grouped for reading, e.g. "7B9D F613 D8". + expect(desktop_page.locator("#pairing .code")).to_be_visible() + code=desktop_page.locator("#pairing .code").inner_text().replace(" ","") tab.get_by_label("Demo login secret").fill((fixture/"login.secret").read_text().strip()) tab.get_by_role("button",name="Sign in").click() tab.get_by_label("Code from your Companion").fill(code) @@ -154,7 +155,9 @@ def verify(desktop, browser, origin, fixture, curl, state, url): expect(choices).to_have_count(3,timeout=45000) approve=desktop_page.get_by_role("button",name="Approve",exact=True) expect(approve).to_be_disabled() - fingerprint=choices.last.locator("small").inner_text().removeprefix("SHA-256 ") + fingerprint="".join(choices.last.locator(".fp-g").all_inner_texts()) + if len(fingerprint)!=64: + raise RuntimeError("The Companion did not show a full SHA-256 fingerprint") choices.last.get_by_role("radio").check() approve.click() output,_=workload.communicate(timeout=60) @@ -248,7 +251,7 @@ def start(command): if args.verify: verify(desktop_endpoint,browser_endpoint,origin,fixture,curl,state,url) return - print(f"Enter {origin} in the Companion and choose Pair. Sign in to the demo tab using the secret from {fixture/'login.secret'}.") + print(f"In the Companion's Integrators tab, enter {origin} and choose Pair. Sign in to the demo tab using the secret from {fixture/'login.secret'}.") print("Enter the Companion pairing code in the browser and confirm the pairing in the Companion.") print("Type curl below to request https://site.test:9444/. Choose a certificate and approve in the Companion.") print(f"The Integrator's {origin}/job page shows the fingerprint the site received.") diff --git a/examples/demo-integrator/site-files.js b/examples/demo-integrator/site-files.js index 9740689..fb50841 100644 --- a/examples/demo-integrator/site-files.js +++ b/examples/demo-integrator/site-files.js @@ -15,4 +15,5 @@ export const contentSecurityPolicy = // The fictional brand the Companion shows for this demo. export const manifest = {version:1,displayName:'Harbor Ledger',copy:'Client reporting workspace', - logo:'/harbor-ledger.png',colors:{accent:'#0f6b6b',background:'#eef6f4'}}; + logo:'/harbor-ledger.png',colors:{accent:'#0f6b6b',background:'#eef6f4', + dark:{accent:'#5cc8bd',background:'#0f1f1e'}}}; diff --git a/examples/demo-integrator/test/e2e.py b/examples/demo-integrator/test/e2e.py index dbfe02f..d5616e5 100644 --- a/examples/demo-integrator/test/e2e.py +++ b/examples/demo-integrator/test/e2e.py @@ -124,8 +124,10 @@ def stop(): page.set_default_timeout(25000) page.get_by_label('Integrator origin').fill(origin) page.get_by_role('button',name='Pair',exact=True).click() - expect(page.locator('#pending')).to_contain_text('Pairing code',timeout=30000) - code=page.locator('#pending').inner_text().split('Pairing code ')[-1].strip() + # The Companion shows the code grouped for reading, e.g. "7B9D F613 D8". + expect(page.locator('#pairing .code')).to_be_visible(timeout=30000) + code=page.locator('#pairing .code').inner_text().replace(' ','') + assert code and code.isalnum(), code from urllib.parse import urlsplit,parse_qs attempt=parse_qs(urlsplit((private/'url').read_text().strip()).query)['attempt'][0] api('login',{'password':(fixture/'login.secret').read_text().strip()}) @@ -156,7 +158,8 @@ def stop(): approve=page.get_by_role('button',name='Approve',exact=True) expect(approve).to_be_disabled() selected=rows.last - fingerprint=selected.locator('small').inner_text().removeprefix('SHA-256 ') + fingerprint=''.join(selected.locator('.fp-g').all_inner_texts()) + assert len(fingerprint)==64, fingerprint selected.get_by_role('radio').check() approve.click() output,errors=curl.communicate(timeout=60) @@ -167,11 +170,16 @@ def stop(): if curl.poll() is None:curl.terminate();curl.wait(5) # Revocation is authenticated through the winning physical device. An automatic # retry of the same Workload and host must not create another approval. + page.get_by_role('button',name='Integrators',exact=True).click() + page.locator('#pairs .int-row').filter(has_text=origin).click() page.get_by_role('button',name='Revoke access',exact=True).click() - expect(page.locator('#pairs')).to_contain_text('Broker recorded revocation',timeout=15000) + expect(page.locator('#detail')).to_contain_text('Broker recorded revocation',timeout=15000) rejected=subprocess.run(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=15) assert rejected.returncode!=0 and not rejected.stdout, 'revoked access reached the site' - expect(page.locator('#requests .identity')).to_have_count(0) + # A new request would open the Requests tab and raise its count. + expect(page.locator('#detail')).to_be_visible() + expect(page.locator('#badge')).to_be_hidden() + expect(page.locator('.identity')).to_have_count(0) print(f'PASS: revoked access and suppressed automatic retry; selected one of {count} native identities; isolated curl and upstream confirmed {fingerprint}',flush=True) diff --git a/packages/companion/src/desktop.css b/packages/companion/src/desktop.css index 0d7059a..244045e 100644 --- a/packages/companion/src/desktop.css +++ b/packages/companion/src/desktop.css @@ -1,28 +1,199 @@ -:root { font-family: "Segoe UI", system-ui, sans-serif; color: #17252b; background: #f7f8f6; } +/* Colours come from CSS custom properties that renderer.js sets from + palette.js. The fallbacks below are the Countersign light theme. Rules + marked FIXED use colours no Integrator theme can change. */ +:root { + --band: #2b0548; --band-ink: #ffffff; --band-muted: #ddd0ea; --underline: #a1ca7c; + --ground: #f5f4f7; --surface: #ffffff; --raised: #f3f0f6; --ink: #1b1424; --muted: #554c60; --line: #d9d3e0; + --accent: #3d1466; --accent-soft: #f1eaf7; --primary: #224805; --on-primary: #ffffff; --focus: #2f6fd6; + --hot-bg: #ece0f6; --hot-ink: #2b0548; + --chk-surface: #ffffff; --chk-line: #cfcad6; --chk-ink: #1b1424; --chk-muted: #4f4859; + --warn-bg: #fff1d6; --warn-line: #b45309; --warn-ink: #4a1f00; --ok: #2f7a12; --danger: #a12a1c; + --on-danger: #ffffff; --danger-bg: #fdecea; --danger-ink: #5c130b; --note-bg: #1b1424; --note-ink: #ffffff; + --scrim: rgba(20, 12, 30, .45); + --sans: "Segoe UI", system-ui, -apple-system, "Helvetica Neue", Ubuntu, Cantarell, sans-serif; + --mono: ui-monospace, "Cascadia Mono", "SF Mono", Menlo, "DejaVu Sans Mono", monospace; + font-family: var(--sans); font-size: 14px; line-height: 1.45; color: var(--ink); background: var(--ground); + color-scheme: light; +} +@media (prefers-color-scheme: dark) { :root { color-scheme: dark; } } * { box-sizing: border-box; } -body { margin: 0; } -header { padding: 18px 28px; display: flex; gap: 6px; align-items: center; border-bottom: 1px solid #cbd4d3; background: white; color: black; } -header h1 { margin: 0; border-inline-start: 2px solid #2b0548; padding-inline-start: 8px; font-size: 1.25rem; font-weight: 600; text-transform: lowercase; } -.mark { width: 32px; height: 32px; fill: currentColor; } -main { max-width: 820px; margin: auto; padding: 6px 28px 28px; } -h2 { font-size: 1.2rem; margin: 1.4em 0 .65em; } -h3 { overflow-wrap: anywhere; } -form, .actions { display: flex; align-items: end; gap: .5rem; flex-wrap: wrap; } -input, select, button { font: inherit; padding: .48em .68em; } -input[type=url] { min-width: min(100%, 18rem); } -button { cursor: pointer; background: white; border: 1px solid #9eafad; border-radius: 5px; color: inherit; } -button:disabled { cursor: default; opacity: .52; } -button.approve { background: #145b53; color: white; border-color: transparent; } -:focus-visible { outline: 3px solid #307bdf; outline-offset: 2px; } -article { background: white; border: 1px solid #cbd4d3; border-radius: 8px; padding: 16px 18px; margin: .65rem 0; overflow-wrap: anywhere; } -.brand { max-height: 7rem; overflow: hidden; isolation: isolate; contain: content; padding: .6rem; border-inline-start: 4px solid; } -.brand img { max-width: 70px; max-height: 34px; object-fit: contain; vertical-align: middle; margin-right: .5rem; } -.brand strong { font-size: .94em; } -.brand p { margin: .25em 0; } -dl { display: grid; grid-template-columns: auto 1fr; gap: .35em .8em; align-items: baseline; } -dt { color: #445851; } -dd { margin: 0; } -fieldset { border: 1px solid #cbd4d3; margin: .8rem 0; } -label.identity { display: block; padding: .5rem 0; } -small { display: block; font-family: ui-monospace, monospace; overflow-wrap: anywhere; } -p[role=alert] { color: #9b301d; } +html, body { height: 100%; } +body { margin: 0; display: flex; flex-direction: column; background: var(--ground); color: var(--ink); } +[hidden] { display: none !important; } +:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +a { color: var(--accent); } +.ico { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.mono { font-family: var(--mono); font-size: 13.5px; } + +/* Header band: the Countersign mark, or the Integrator's logo, name and copy + beside its verified origin. Tabs sit at the bottom of the band. */ +.band { flex: none; background: var(--band); color: var(--band-ink); padding: 12px 20px 0; display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 4px 16px; } +.brandrow { display: flex; align-items: center; gap: 10px; padding-bottom: 12px; min-height: 30px; flex-wrap: wrap; min-width: 0; } +.mark { width: 26px; height: 26px; fill: var(--band-ink); flex: none; } +.wordmark { font-weight: 300; font-size: 21px; line-height: 1; padding-left: 10px; border-left: 1px solid var(--band-muted); } +.int-logo { width: 28px; height: 28px; object-fit: contain; flex: none; } +.int-text { display: flex; flex-direction: column; gap: 3px; min-width: 0; } +.int-name { font-weight: 600; font-size: 19px; line-height: 1.1; overflow-wrap: anywhere; } +.int-copy { font-size: 12.5px; color: var(--band-muted); overflow-wrap: anywhere; } +.int-copy:empty { display: none; } +/* FIXED: the verified origin beside the Integrator's name. */ +.verified-chip { display: inline-flex; align-items: center; gap: 5px; padding: 3px 9px; border-radius: 999px; background: #ffffff; color: #1b1424; border: 1px solid #1b1424; font: 500 12px var(--mono); overflow-wrap: anywhere; } +.verified-chip .ico { width: 14px; height: 14px; color: #1f6a12; } +.verified-chip b { font: 600 11px var(--sans); color: #1f6a12; } +.tabs { display: flex; gap: 2px; } +.tab { min-height: 44px; padding: 0 14px; border: 0; border-bottom: 3px solid transparent; background: transparent; color: var(--band-muted); font: 500 14px var(--sans); cursor: pointer; display: flex; align-items: center; gap: 8px; } +.tab[aria-current=page] { color: var(--band-ink); border-bottom-color: var(--underline); } +.badge { min-width: 20px; height: 20px; border-radius: 10px; background: var(--underline); color: var(--band); font: 600 12px var(--sans); display: inline-flex; align-items: center; justify-content: center; padding: 0 6px; } + +.content { flex: 1; overflow-y: auto; display: flex; flex-direction: column; min-height: 0; } +.view { flex: 1; display: flex; flex-direction: column; } +.pad { padding: 18px 24px 24px; flex: 1; } + +/* FIXED: the countersign plate and the error line. */ +.footer { flex: none; display: flex; justify-content: flex-end; align-items: center; gap: 10px; padding: 6px 10px; background: var(--ground); border-top: 1px solid var(--line); } +.plate { display: inline-flex; align-items: center; gap: 7px; padding: 4px 10px; border-radius: 6px; background: #ffffff; border: 1px solid #1b1424; color: #1b1424; line-height: 1; flex: none; } +.plate svg { width: 16px; height: 16px; fill: #1b1424; } +.plate .wm { font-weight: 400; font-size: 14px; padding-left: 7px; border-left: 1px solid #1b1424; } +.feedback { margin: 0 auto 0 0; display: flex; align-items: center; gap: 8px; font-size: 13px; padding: 6px 10px; border-radius: 6px; border: 2px solid var(--danger); background: var(--danger-bg); color: var(--danger-ink); } +.feedback:empty { display: none; } +.feedback .ico { color: var(--danger); } + +.eyebrow { margin: 0 0 4px; font: 600 12px var(--sans); letter-spacing: .06em; text-transform: uppercase; color: var(--muted); } +.h1 { margin: 0 0 16px; font-weight: 300; font-size: 26px; line-height: 1.2; color: var(--ink); } +.flash { margin: 0 0 14px; padding: 10px 12px; border-radius: 8px; background: var(--accent-soft); color: var(--ink); font-size: 13px; } +.queue { display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap; margin: 0 0 10px; font-size: 12.5px; color: var(--muted); } +.queue strong { color: var(--ink); } +/* FIXED: the queue banner. */ +.switch-banner { display: flex; align-items: center; gap: 10px; margin: 0 0 12px; padding: 10px 12px; border-radius: 8px; background: var(--note-bg); color: var(--note-ink); font-weight: 500; font-size: 13.5px; } + +/* Request facts, in clamped palette colours only. */ +.verified { background: var(--chk-surface); color: var(--chk-ink); border: 1px solid var(--chk-line); border-radius: 10px; padding: 14px 16px 16px; } +.verified-head { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 12.5px; margin: 0 0 10px; } +.facts { margin: 0; display: flex; flex-direction: column; gap: 8px; } +.fact { display: grid; grid-template-columns: 128px minmax(0, 1fr); gap: 12px; align-items: baseline; } +.fact dt { color: var(--chk-muted); font-size: 13px; } +.fact dd { margin: 0; overflow-wrap: anywhere; color: var(--chk-ink); } +.fact-origin dd { font-size: 16px; font-weight: 600; } +.fact.is-wide dd { font-weight: 600; } +.nobrand { margin: 14px 0 0; font-size: 12.5px; color: var(--muted); } + +/* FIXED: warnings and errors. */ +.alert { display: flex; gap: 10px; border-radius: 8px; padding: 10px 12px; font-size: 13px; border: 2px solid; margin-top: 12px; } +.alert .ico { width: 22px; height: 22px; } +.alert p { margin: 0; } +.alert strong { display: block; margin-bottom: 2px; } +.alert.warning { background: var(--warn-bg); border-color: var(--warn-line); color: var(--warn-ink); } +.alert.warning .ico { color: var(--warn-line); } +.alert.danger { background: var(--danger-bg); border-color: var(--danger); color: var(--danger-ink); } +.alert.danger .ico { color: var(--danger); } + +.certs { border: 0; margin: 22px 0 0; padding: 0; min-width: 0; display: flex; flex-direction: column; gap: 8px; } +.legend { padding: 0; margin: 22px 0 8px; font-weight: 600; font-size: 14px; color: var(--ink); } +.certs > .legend { margin-top: 0; } +.note { margin: 0 0 2px; font-size: 13px; color: var(--muted); } +.cert { display: flex; gap: 12px; align-items: flex-start; background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; cursor: pointer; } +.cert:has(input:checked) { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); } +.cert input { margin: 3px 0 0; width: 18px; height: 18px; accent-color: var(--accent); flex: none; } +.idc { display: grid; grid-template-columns: repeat(5, 7px); grid-auto-rows: 7px; gap: 1px; padding: 3px; background: var(--raised); border: 1px solid var(--line); border-radius: 5px; flex: none; } +.cert-body { min-width: 0; flex: 1; } +.cert-name { font-weight: 600; overflow-wrap: anywhere; } +/* Certificate details stay at full contrast. */ +.cert-meta { display: block; font-size: 13px; color: var(--ink); overflow-wrap: anywhere; } +.fp { margin-top: 6px; font: 12px/1.65 var(--mono); color: var(--ink); display: flex; flex-wrap: wrap; gap: 0 6px; } +.fp-label { font: 600 11.5px/1.9 var(--sans); margin-right: 2px; } +.fp-g.hot { background: var(--hot-bg); color: var(--hot-ink); font-weight: 600; border-radius: 3px; padding: 0 2px; } + +.seg { display: flex; flex-wrap: wrap; gap: 6px; } +.seg-btn { min-height: 44px; min-width: 72px; padding: 0 14px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); border-radius: 8px; font: 500 14px var(--sans); cursor: pointer; } +.seg-btn[aria-pressed=true] { border-color: var(--accent); background: var(--accent-soft); box-shadow: 0 0 0 1px var(--accent); } +.seg-btn:disabled { cursor: not-allowed; color: var(--muted); border-style: dashed; } +.custom { display: flex; align-items: center; gap: 10px; margin-top: 10px; flex-wrap: wrap; } +.custom label { display: flex; align-items: center; gap: 8px; font-size: 13px; } +.custom input { width: 90px; min-height: 40px; padding: 0 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); color: var(--ink); font: 14px var(--sans); } +.hint { font-size: 12.5px; color: var(--muted); } +.small-note { margin: 6px 0 0; font-size: 12.5px; color: var(--muted); } +.expires { margin-top: 12px; display: flex; align-items: baseline; flex-wrap: wrap; gap: 4px 10px; background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; } +.expires-label, .expires-day { font-size: 13px; color: var(--ink); } +.expires-time { font-weight: 300; font-size: 28px; line-height: 1; color: var(--ink); } +.consequence { margin: 16px 0 0; font-size: 13px; color: var(--ink); } + +/* FIXED: Deny and Approve keep their labels, order and equal size. */ +.actions { position: sticky; bottom: 0; background: var(--ground); border-top: 1px solid var(--line); padding: 12px 24px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; flex: none; } +.reason { flex: 1; min-width: 160px; margin: 0; font-size: 13px; color: var(--muted); } +.btn { min-height: 44px; padding: 0 18px; border-radius: 8px; font: 600 14px var(--sans); cursor: pointer; border: 1px solid var(--line); background: var(--surface); color: var(--ink); } +.btn.primary { background: var(--primary); color: var(--on-primary); border-color: transparent; } +.btn:disabled { opacity: .42; cursor: not-allowed; } +.btn.danger { background: var(--danger); color: var(--on-danger); border-color: transparent; } +.btn.small { min-height: 36px; padding: 0 12px; font-size: 13px; } +.actions .decision { width: 132px; padding: 0; } +.actions .outline, .actions .decision:not(.primary) { border: 1.5px solid var(--ink); color: var(--ink); background: var(--surface); } + +.result { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 18px; overflow-wrap: anywhere; } +.result p { margin: 0 0 10px; } +.result p:last-child { margin-bottom: 0; } +.code-box { margin-top: 14px; background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; } +.code { margin: 6px 0 4px; font: 600 36px/1.1 var(--mono); letter-spacing: .06em; color: var(--ink); } + +.card { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; margin-bottom: 14px; } +.card-head { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; } +.card-title { min-width: 0; flex: 1; } +.card-title strong { display: block; font-size: 15px; overflow-wrap: anywhere; } +.card-title span { font-size: 13px; color: var(--muted); overflow-wrap: anywhere; } +.swatch { width: 34px; height: 34px; border-radius: 8px; border: 1px solid var(--line); flex: none; } +.status { font-weight: 600; font-size: 12.5px; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } +.dot { width: 8px; height: 8px; border-radius: 4px; background: currentColor; } +.st-ok { color: var(--ok); } +.st-warn { color: var(--warn-ink); } +.st-muted { color: var(--muted); } +.sub { font-weight: 600; font-size: 11.5px; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); margin: 16px 0 4px; } +.row { display: flex; justify-content: space-between; gap: 6px 12px; align-items: center; flex-wrap: wrap; padding: 10px 0; border-top: 1px solid var(--line); } +.row-main { min-width: 0; flex: 1 1 220px; } +.row-main strong { display: block; overflow-wrap: anywhere; } +.row-main span { display: block; font-size: 12.5px; color: var(--muted); overflow-wrap: anywhere; } +.row-main span.st-ok { color: var(--ok); } +.row-main span.st-warn { color: var(--warn-ink); } +.row-main .tag, .tag { display: inline-block; margin-left: 8px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line); background: var(--raised); color: var(--ink); font: 600 11px var(--sans); vertical-align: middle; } +.int-row { width: 100%; text-align: left; display: flex; gap: 12px; align-items: center; background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; margin-bottom: 10px; cursor: pointer; color: var(--ink); font: inherit; } +.int-row .chev { color: var(--muted); font-size: 18px; } +.review { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin-top: 6px; } +.caption { margin: 0 0 4px; font-size: 12px; color: var(--muted); } +/* A small copy of the header band each branding would draw. */ +.preview { border-radius: 8px; overflow: hidden; border: 1px solid var(--line); } +.preview-band { display: flex; align-items: center; gap: 8px; padding: 10px 12px; color: #ffffff; min-height: 52px; } +.preview-band img { width: 24px; height: 24px; object-fit: contain; flex: none; } +.preview-band strong { display: block; font-size: 14px; overflow-wrap: anywhere; } +.preview-band span { display: block; font-size: 12px; overflow-wrap: anywhere; } +.preview-colors { display: flex; gap: 6px; align-items: center; padding: 6px 12px; background: var(--surface); font: 11.5px var(--mono); color: var(--ink); flex-wrap: wrap; } +.preview-colors i { display: inline-block; width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--line); vertical-align: -2px; margin-right: 3px; } +.btnrow { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; } +.form { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; } +.form label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; flex: 1 1 220px; } +.form input { min-height: 44px; padding: 0 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); color: var(--ink); font: 14px var(--sans); } +.check { display: flex; gap: 10px; align-items: flex-start; font-size: 14px; } +.check input { width: 20px; height: 20px; margin: 1px 0 0; accent-color: var(--accent); } +.check span span { display: block; font-size: 13px; color: var(--muted); } +.card-title-plain { margin: 0 0 6px; font-weight: 600; } +.idle { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 6px; padding: 40px 32px; color: var(--muted); } +.idle .ico { width: 40px; height: 40px; color: var(--line); stroke-width: 1.5; } +.idle h1 { margin: 6px 0 0; font-weight: 300; font-size: 24px; color: var(--ink); } +.idle p { margin: 0; max-width: 360px; } + +dialog { border: 0; padding: 20px; border-radius: 12px; max-width: min(420px, calc(100vw - 40px)); width: 100%; background: var(--surface); color: var(--ink); box-shadow: 0 18px 50px rgba(0, 0, 0, .35); } +dialog::backdrop { background: var(--scrim); } +dialog h2 { margin: 0 0 8px; font-weight: 600; font-size: 17px; overflow-wrap: anywhere; } +dialog p { margin: 0 0 16px; color: var(--muted); font-size: 14px; overflow-wrap: anywhere; } +dialog .btnrow { justify-content: flex-end; margin-top: 0; } + +@media (max-width: 520px) { + .band { padding: 12px 16px 0; } + .tab { padding: 0 10px; } + .pad { padding: 16px; } + .h1 { font-size: 22px; } + .fact { grid-template-columns: minmax(0, 1fr); gap: 0; } + .actions { padding: 12px 16px; } + .actions .decision { width: auto; flex: 1; } + .reason { flex-basis: 100%; } + .review { grid-template-columns: minmax(0, 1fr); } + .code { font-size: 30px; } + .int-name { font-size: 17px; } +} diff --git a/packages/companion/src/index.html b/packages/companion/src/index.html index 2df071a..672dd28 100644 --- a/packages/companion/src/index.html +++ b/packages/companion/src/index.html @@ -9,27 +9,40 @@ -
- -

Countersign

+
+
+ + countersign +
+ +
-
-
-

Pair an Integrator

-
-
-
-
-
-

Approval requests

-
-
-

Paired Integrators

- - -
+
+
+ + + + countersign + +
+ +

+

+
+ + +
+
diff --git a/packages/companion/src/main.js b/packages/companion/src/main.js index 43c4755..d20e3e0 100644 --- a/packages/companion/src/main.js +++ b/packages/companion/src/main.js @@ -1,4 +1,4 @@ -import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, Notification, safeStorage, shell, Tray } from 'electron'; +import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, nativeTheme, Notification, safeStorage, shell, Tray } from 'electron'; import { randomUUID } from 'node:crypto'; import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; @@ -7,12 +7,21 @@ import { integratorOrigin, approvalHint, displayText } from './origins.js'; import { readTheme } from './theme.js'; import { startsAtLogin, setStartAtLogin } from './login.js'; import { PairingStore } from './store.js'; +import { windowPalette } from './palette.js'; +import { orderQueue } from './queue.js'; const require = createRequire(import.meta.url); const path = relative => fileURLToPath(new URL(relative, import.meta.url)); const rendererUrl = new URL('index.html', import.meta.url).href; const sessions = new Map(); -let win, tray, store, native, exiting = false, pendingHint, accountConfirmation; +let win, tray, store, native, exiting = false, pendingHint, accountConfirmation, appearance = null; +// The window background follows the OS appearance and, while one is on +// screen, the theme of the pairing the renderer reports. The colour comes +// from the stored theme, never from the renderer. +function background() { + return windowPalette(sessions.get(appearance)?.record.theme ?? null, nativeTheme.shouldUseDarkColors).ground; +} +function paint() { if (win && !win.isDestroyed()) win.setBackgroundColor(background()); } function changed() { if (!win?.isDestroyed()) win?.webContents.send('desktop:changed'); } function show() { win?.show(); win?.focus(); } function handleHint(raw) { @@ -35,7 +44,7 @@ function attach(record) { confirmAccount: (origin, user, code) => new Promise(resolve => { accountConfirmation?.finish(false); const timer = setTimeout(() => confirmation.finish(false), 55000); - const confirmation = { id: randomUUID(), origin, user, code, finish: answer => { + const confirmation = { id: randomUUID(), pairing: record.id, origin, user, code, finish: answer => { clearTimeout(timer); if (accountConfirmation === confirmation) accountConfirmation = undefined; resolve(answer); @@ -102,7 +111,9 @@ function installHandlers() { pairings: all.filter(s => s.record.pairing).map(s => ({ id:s.record.id, origin:s.record.origin, user:s.record.user, status:s.status, theme:s.record.theme, pendingTheme:s.record.pendingTheme, - devices:s.devices.filter(d=>d.binding.pairing!==s.record.pairing), + // The Broker lists every Companion on the account. This computer is + // the one holding this pairing's own binding. + devices:s.devices.map(d => ({...d, self:d.binding.pairing===s.record.pairing})), notices:s.notices, approvals:Object.entries(s.record.receipts ?? {}).filter(([,r]) => r.until > Date.now() || r.revocation === 'pending').map(([id,r]) => ({ id, host:r.host || r.scope.pattern, scope:r.scope.pattern, context:r.workload.context, until:r.until, @@ -110,18 +121,20 @@ function installHandlers() { ready:[...s.activations.values()].includes(id), })), })), - confirmation: accountConfirmation && {id:accountConfirmation.id,origin:accountConfirmation.origin, - user:accountConfirmation.user,code:accountConfirmation.code}, - pending: all.filter(s => !s.record.pairing).map(s => s.record.origin + ' · ' + s.status).join('\n'), + confirmation: accountConfirmation && {id:accountConfirmation.id,pairing:accountConfirmation.pairing, + origin:accountConfirmation.origin,user:accountConfirmation.user,code:accountConfirmation.code, + theme:sessions.get(accountConfirmation.pairing)?.record.theme ?? null}, + pending: all.filter(s => !s.record.pairing).map(s => ({id:s.record.id, origin:s.record.origin, + status:s.status, code:s.code ?? null, theme:s.record.theme ?? null})), login: startsAtLogin(app), - offers: all.flatMap(s => [...s.offers.values()].filter(o => o.body.expires_at_ms > Date.now()).map(o => ({ - handle:o.handle, origin:s.record.origin, user:s.record.user, theme:s.record.theme, + offers: orderQueue(all.flatMap(s => [...s.offers.values()].filter(o => o.body.expires_at_ms > Date.now()).map(o => ({ + handle:o.handle, received:o.received, pairing:s.record.id, origin:s.record.origin, user:s.record.user, theme:s.record.theme, context:o.body.workload.context, host:o.body.initiating_host, scope:o.body.scope.pattern, providerUnavailable:o.providerUnavailable, maxDuration:o.body.max_duration_s, defaultDuration:o.body.default_duration_s, identities:o.identities.map(i => ({reference:i.selection, identity:certLabel(i.subject), issuer:certLabel(i.issuer), expiresAt:i.expiresAtMs, fingerprint:Buffer.from(i.certSha256,'base64').toString('hex')})), - }))), + })))), }; }); let enrolling = false; @@ -154,15 +167,20 @@ function installHandlers() { if (typeof enabled !== 'boolean') throw new TypeError(); setStartAtLogin(app, enabled); }); - action('theme', async (id,digest) => { - const s = sessions.get(id); - if (!s) throw new Error('Unknown pairing.'); - await store.update(id, r => { - if (!r?.pendingTheme || r.pendingTheme.digest !== digest) throw new Error('Branding changed.'); - return {...r, theme:r.pendingTheme, pendingTheme:null}; - }); - s.record = store.get(id); - changed(); + function review(accept) { + return async (id, digest) => { + const s = sessions.get(id); + if (!s?.record.pairing || typeof digest !== 'string') throw new Error('Unknown pairing.'); + await s.reviewBrand(digest, accept); + paint(); + }; + } + action('theme', review(true)); + action('keepTheme', review(false)); + action('appearance', id => { + if (id !== null && !sessions.has(id)) throw new Error('Unknown pairing.'); + appearance = id; + paint(); }); action('forgetOthers', (id, ids, all) => { const s = sessions.get(id); @@ -188,6 +206,8 @@ function installHandlers() { await native.retirePairingKey(session.record.locator); await store.update(id, () => null); sessions.delete(id); + if (appearance === id) appearance = null; + paint(); changed(); }); action('forget', async id => { @@ -204,7 +224,7 @@ function installHandlers() { function newWindow() { win = new BrowserWindow({width:660,height:760,minWidth:400,minHeight:400,show:false, icon:path('../assets/icon.png'), - backgroundColor:'#f7f8f6',webPreferences:{preload:path('preload.cjs'),sandbox:true,contextIsolation:true, + backgroundColor:background(),webPreferences:{preload:path('preload.cjs'),sandbox:true,contextIsolation:true, nodeIntegration:false,webSecurity:true,webviewTag:false}}); win.webContents.setWindowOpenHandler(() => ({action:'deny'})); win.webContents.on('will-navigate', event => event.preventDefault()); @@ -226,6 +246,7 @@ if (!app.requestSingleInstanceLock()) { store = new PairingStore(app.getPath('userData'),safeStorage); await store.load(); installHandlers(); + nativeTheme.on('updated', paint); await newWindow(); // The macOS template picks up the menu bar's current color and Retina scale. const trayIcon = process.platform === 'darwin' diff --git a/packages/companion/src/palette.js b/packages/companion/src/palette.js new file mode 100644 index 0000000..f8b56a8 --- /dev/null +++ b/packages/companion/src/palette.js @@ -0,0 +1,175 @@ +// Window palettes for the Companion. Shared by the main process (window +// background) and the renderer (CSS custom properties), so it uses no Node or +// DOM APIs. +// +// An Integrator's manifest supplies only an accent and a background colour, +// and optionally a dark pair. Every colour the window uses is derived from +// them in OKLCH and then clamped until text and controls meet WCAG AA +// contrast. Warnings, the verified-origin chip and the countersign plate use +// FIXED colours that no manifest can change. + +const HEX = /^#[0-9a-f]{6}$/; + +function rgb(hex) { return [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255); } +function lin(c) { return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); } +function unlin(c) { return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055; } + +export function oklch(hex) { + const [r, g, b] = rgb(hex).map(lin); + const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + const L = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s; + const A = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s; + const B = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s; + let h = Math.atan2(B, A) * 180 / Math.PI; + if (h < 0) h += 360; + return { l: L, c: Math.hypot(A, B), h }; +} + +function linear(L, C, H) { + const a = C * Math.cos(H * Math.PI / 180), b = C * Math.sin(H * Math.PI / 180); + const l = Math.pow(L + 0.3963377774 * a + 0.2158037573 * b, 3); + const m = Math.pow(L - 0.1055613458 * a - 0.0638541728 * b, 3); + const s = Math.pow(L - 0.0894841775 * a - 1.2914855480 * b, 3); + return [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, + -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, + -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s]; +} + +const inGamut = v => v.every(x => x >= -0.0005 && x <= 1.0005); + +// sRGB hex for an OKLCH colour. Out-of-gamut colours keep their lightness and +// hue and lose chroma until they fit. +export function hex(L, C, H) { + L = Math.min(1, Math.max(0, L)); + let v = linear(L, C, H); + if (!inGamut(v)) { + let lo = 0, hi = C; + for (let i = 0; i < 24; i++) { + const mid = (lo + hi) / 2; + if (inGamut(linear(L, mid, H))) lo = mid; else hi = mid; + } + v = linear(L, lo, H); + } + return '#' + v.map(x => Math.round(Math.min(1, Math.max(0, unlin(Math.min(1, Math.max(0, x))))) * 255) + .toString(16).padStart(2, '0')).join(''); +} + +function luminance(color) { + const [r, g, b] = rgb(color).map(lin); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +// WCAG 2 contrast ratio of two hex colours. +export function contrast(a, b) { + const x = luminance(a), y = luminance(b); + return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); +} + +// Step lightness in `dir` until the colour reaches `target` contrast against +// every colour in `against`. At the end of the range it returns black or +// white, which always clears the targets used here. +function fit(L, C, H, against, target, dir) { + const backgrounds = [].concat(against); + const ok = color => backgrounds.every(bg => contrast(color, bg) >= target); + let l = L, out = hex(l, C, H); + for (let i = 0; i < 120 && !ok(out); i++) { + l += dir * 0.01; + if (l < 0 || l > 1) return dir < 0 ? '#000000' : '#ffffff'; + out = hex(l, C, H); + } + return out; +} + +// Warnings, errors, the queue banner and dialogs' destructive buttons. +export function fixedPalette(dark) { + return dark + ? { 'warn-bg': '#3a2a05', 'warn-line': '#f5b544', 'warn-ink': '#ffe2a8', ok: '#a1ca7c', danger: '#f08a7a', + 'on-danger': '#2a0905', 'danger-bg': '#3a1410', 'danger-ink': '#ffd7d0', 'note-bg': '#f2eff5', + 'note-ink': '#1b1424', scrim: 'rgba(0,0,0,.6)' } + : { 'warn-bg': '#fff1d6', 'warn-line': '#b45309', 'warn-ink': '#4a1f00', ok: '#2f7a12', danger: '#a12a1c', + 'on-danger': '#ffffff', 'danger-bg': '#fdecea', 'danger-ink': '#5c130b', 'note-bg': '#1b1424', + 'note-ink': '#ffffff', scrim: 'rgba(20,12,30,.45)' }; +} + +// Countersign's own theme: purple band, green Approve. +export function countersignPalette(dark) { + return dark + ? { band: '#2b0548', 'band-ink': '#ffffff', 'band-muted': '#ddd0ea', underline: '#a1ca7c', ground: '#17131d', + surface: '#211b29', raised: '#2a2333', ink: '#f0ebf5', muted: '#b9afc4', line: '#3d3447', accent: '#d2b3ea', + 'accent-soft': '#2f2540', primary: '#a1ca7c', 'on-primary': '#11200a', focus: '#8fb8ff', 'hot-bg': '#3b2a4f', + 'hot-ink': '#ecdcfa' } + : { band: '#2b0548', 'band-ink': '#ffffff', 'band-muted': '#ddd0ea', underline: '#a1ca7c', ground: '#f5f4f7', + surface: '#ffffff', raised: '#f3f0f6', ink: '#1b1424', muted: '#554c60', line: '#d9d3e0', accent: '#3d1466', + 'accent-soft': '#f1eaf7', primary: '#224805', 'on-primary': '#ffffff', focus: '#2f6fd6', 'hot-bg': '#ece0f6', + 'hot-ink': '#2b0548' }; +} + +// The full palette for a validated theme ({accent, background, dark?}). +export function derivePalette(theme, dark) { + const A = oklch(theme.accent), H = A.h, C = Math.max(A.c, 0.02); + if (!dark) { + const Bg = oklch(theme.background), gh = Bg.c > 0.004 ? Bg.h : H; + const ground = hex(0.972, Math.min(Math.max(Bg.c, 0.008), 0.018), gh); + const surface = '#ffffff'; + const softC = Math.min(C, 0.04), accentSoft = hex(0.95, softC, H); + const band = fit(Math.min(A.l, 0.42), Math.min(C, 0.14), H, '#ffffff', 7, -1); + const hotBg = hex(0.92, Math.min(C, 0.06), H); + return { + band, 'band-ink': '#ffffff', 'band-muted': fit(0.88, Math.min(C, 0.05), H, band, 4.5, 1), + underline: fit(0.82, Math.min(C, 0.13), H, band, 4.5, 1), + ground, surface, raised: hex(0.95, Math.min(C, 0.02), H), ink: hex(0.23, Math.min(C, 0.03), H), + muted: fit(0.48, Math.min(C, 0.03), H, [ground, surface, accentSoft], 4.5, -1), + line: hex(0.86, Math.min(C, 0.035), H), + accent: fit(A.l, A.c, H, [surface, ground, accentSoft], 4.5, -1), 'accent-soft': accentSoft, + primary: fit(A.l, A.c, H, '#ffffff', 4.5, -1), 'on-primary': '#ffffff', + focus: fit(0.58, Math.max(C, 0.12), H, [ground, surface], 3, -1), 'hot-bg': hotBg, + 'hot-ink': fit(0.32, C, H, hotBg, 4.5, -1), + }; + } + const src = theme.dark; + const AD = src ? oklch(src.accent) : { l: Math.max(A.l, 0.78), c: Math.min(A.c, 0.13), h: H }; + const BD = src ? oklch(src.background) : { l: 0.19, c: Math.min(C, 0.02), h: H }; + const gl = Math.min(Math.max(BD.l, 0.15), 0.23), gc = Math.min(BD.c, 0.03); + const ground = hex(gl, gc, BD.h), surface = hex(gl + 0.05, gc, BD.h); + const accentSoft = hex(gl + 0.08, Math.min(AD.c, 0.05), AD.h); + const band = fit(0.34, Math.min(AD.c, 0.10), AD.h, '#ffffff', 7, -1); + const onPrimary = hex(0.18, Math.min(AD.c, 0.03), AD.h); + const hotBg = hex(0.32, Math.min(AD.c, 0.07), AD.h); + return { + band, 'band-ink': '#ffffff', 'band-muted': fit(0.88, Math.min(AD.c, 0.05), AD.h, band, 4.5, 1), + underline: fit(0.82, Math.min(AD.c, 0.13), AD.h, band, 4.5, 1), + ground, surface, raised: hex(gl + 0.09, gc, BD.h), ink: hex(0.95, 0.01, AD.h), + muted: fit(0.78, Math.min(AD.c, 0.02), AD.h, [ground, surface, accentSoft], 4.5, 1), + line: hex(gl + 0.17, gc, BD.h), + accent: fit(Math.max(AD.l, 0.7), AD.c, AD.h, [surface, ground, accentSoft], 4.5, 1), 'accent-soft': accentSoft, + primary: fit(Math.max(AD.l, 0.72), AD.c, AD.h, onPrimary, 4.5, 1), 'on-primary': onPrimary, + focus: fit(0.75, Math.max(AD.c, 0.12), AD.h, [ground, surface], 3, 1), 'hot-bg': hotBg, + 'hot-ink': fit(0.92, Math.min(AD.c, 0.05), AD.h, hotBg, 4.5, 1), + }; +} + +const validColor = value => typeof value === 'string' && HEX.test(value); + +// True for a theme the main process normalized: lowercase six-digit hex only. +export function validTheme(theme) { + if (!theme || typeof theme !== 'object' || !validColor(theme.accent) || !validColor(theme.background)) return false; + if (theme.dark === undefined || theme.dark === null) return true; + return typeof theme.dark === 'object' && validColor(theme.dark.accent) && validColor(theme.dark.background); +} + +// Every CSS custom property the window uses. Without a valid theme the +// Countersign palette applies. The request-facts card is tinted only with +// clamped palette colours. +export function windowPalette(theme, dark) { + const branded = validTheme(theme); + const palette = { ...fixedPalette(dark), ...(branded ? derivePalette(theme, dark) : countersignPalette(dark)) }; + Object.assign(palette, branded + ? { 'chk-surface': palette['accent-soft'], 'chk-line': palette.accent, 'chk-ink': palette.ink, + 'chk-muted': palette.muted } + : dark + ? { 'chk-surface': '#1d1b21', 'chk-line': '#3a3640', 'chk-ink': '#f2eff5', 'chk-muted': '#b9b3c1' } + : { 'chk-surface': '#ffffff', 'chk-line': '#cfcad6', 'chk-ink': '#1b1424', 'chk-muted': '#4f4859' }); + return palette; +} diff --git a/packages/companion/src/preload.cjs b/packages/companion/src/preload.cjs index 4310a9b..8d8db5a 100644 --- a/packages/companion/src/preload.cjs +++ b/packages/companion/src/preload.cjs @@ -7,6 +7,8 @@ contextBridge.exposeInMainWorld('countersign', { decide: (offer, selection, seconds) => ipcRenderer.invoke('desktop:decide', offer, selection, seconds), deny: offer => ipcRenderer.invoke('desktop:deny', offer), theme: (pairing, digest) => ipcRenderer.invoke('desktop:theme', pairing, digest), + keepTheme: (pairing, digest) => ipcRenderer.invoke('desktop:keepTheme', pairing, digest), + appearance: pairing => ipcRenderer.invoke('desktop:appearance', pairing), forgetOthers: (pairing, ids, all) => ipcRenderer.invoke('desktop:forgetOthers', pairing, ids, all), revoke: (pairing, approval) => ipcRenderer.invoke('desktop:revoke', pairing, approval), removeLocal: pairing => ipcRenderer.invoke('desktop:removeLocal', pairing), diff --git a/packages/companion/src/queue.js b/packages/companion/src/queue.js new file mode 100644 index 0000000..8fb0a0a --- /dev/null +++ b/packages/companion/src/queue.js @@ -0,0 +1,24 @@ +// Approval queue rules, shared by the main process and the renderer, so it +// uses no Node or DOM APIs. + +// Oldest request first. Requests that arrived in the same millisecond keep a +// stable order. +export function orderQueue(offers) { + return [...offers].sort((a, b) => a.received - b.received || (a.handle < b.handle ? -1 : a.handle > b.handle ? 1 : 0)); +} + +export function originHost(origin) { + return new URL(origin).host; +} + +// What the window does when the request on screen changes. Any newly shown +// request locks Approve briefly, so a click meant for the previous screen +// cannot approve it. A request from a different pairing also announces the +// change, because the window's colours change with it. +export function headChange(previous, next) { + if (!next || next.handle === previous?.handle) return { lock: false, banner: null }; + const switched = !!previous && previous.pairing !== next.pairing; + return { lock: true, banner: switched ? 'Now showing a request from ' + originHost(next.origin) : null }; +} + +export const LOCK_MS = 1000; diff --git a/packages/companion/src/renderer.js b/packages/companion/src/renderer.js index e6f2d19..78885c4 100644 --- a/packages/companion/src/renderer.js +++ b/packages/companion/src/renderer.js @@ -1,166 +1,771 @@ +import { validTheme, windowPalette } from './palette.js'; +import { headChange, LOCK_MS, originHost } from './queue.js'; + const api = window.countersign; const $ = id => document.getElementById(id); -const selections = new Map(); +const SVG = 'http://www.w3.org/2000/svg'; +const darkQuery = window.matchMedia('(prefers-color-scheme: dark)'); + +// Local state. Everything that can approve lives in the main process; this +// only remembers what the person is looking at and has chosen so far. +const view = { tab: null, detail: null, flash: '' }; +const choices = new Map(); // offer handle -> { reference, preset, minutes } +let state = null; // last snapshot +let known = null; // offer handles already seen +let confirmationSeen = null; +let shown = null; // the request last drawn in the approval view +let lockedUntil = 0, banner = null, bannerUntil = 0, timer; +let decided = null; // { offer, approved, until, cert } after this window decided +let originDraft = ''; +let confirmed = null; // enrollment the person confirmed, while it finishes +let appearance; +// ------------------------------------------------------------------ helpers function element(tag, text, className) { const node = document.createElement(tag); - if (text !== undefined) node.textContent = text; + if (text !== undefined && text !== null) node.textContent = text; if (className) node.className = className; return node; } +function icon(kind) { + const paths = { + shield: ['M12 3l7 3v5c0 4.5-3 8.4-7 10-4-1.6-7-5.5-7-10V6z', 'M8.5 12l2.5 2.5 4.5-5'], + shieldEmpty: ['M12 3l7 3v5c0 4.5-3 8.4-7 10-4-1.6-7-5.5-7-10V6z'], + warning: ['M12 3l9.5 17h-19z', 'M12 10v4.5', 'M12 17.5v.5'], + error: ['M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z', 'M12 7.5v5.5', 'M12 16.5v.5'], + check: ['M5 12.5l4.5 4.5L19 7.5'], + arrow: ['M4 12h14', 'M13 6l6 6-6 6'], + }; + const svg = document.createElementNS(SVG, 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('aria-hidden', 'true'); + svg.setAttribute('class', 'ico'); + for (const d of paths[kind]) { + const path = document.createElementNS(SVG, 'path'); + path.setAttribute('d', d); + svg.append(path); + } + return svg; +} + +function feedback(text) { + $('feedback').replaceChildren(...(text ? [icon('error'), element('span', text)] : [])); +} + async function run(action) { try { - $('feedback').textContent = ''; + feedback(''); await action(); } catch { - $('feedback').textContent = 'This action could not be completed. Check the connection and try again.'; + feedback('This action could not be completed. Check the connection and try again.'); } } -function button(label, action, className) { +function button(label, action, className = 'btn') { const node = element('button', label, className); node.type = 'button'; - node.addEventListener('click', () => run(action)); + node.addEventListener('click', () => run(async () => { + await action(); + draw(); + })); + return node; +} + +// FIXED component for warnings and errors: icon, title and text in colours +// no theme sets. +function alert(kind, title, text) { + const box = element('div', undefined, 'alert ' + kind); + box.setAttribute('role', kind === 'danger' ? 'alert' : 'note'); + const body = element('p'); + body.append(element('strong', title), document.createTextNode(text)); + box.append(icon(kind === 'danger' ? 'error' : 'warning'), body); + return box; +} + +function fact(term, value, className = '', mono = false) { + const row = element('div', undefined, ('fact ' + className).trim()); + row.append(element('dt', term), element('dd', value, mono ? 'mono' : undefined)); + return row; +} + +function checkedFacts(rows) { + const section = element('section', undefined, 'verified'); + section.setAttribute('aria-label', 'Checked by Countersign'); + const head = element('p', undefined, 'verified-head'); + head.append(icon('shield'), document.createTextNode('Checked by Countersign')); + const list = element('dl', undefined, 'facts'); + list.append(...rows); + section.append(head, list); + return section; +} + +const time = ms => new Date(ms).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); +const shortDate = ms => new Date(ms).toLocaleDateString([], { month: 'short', day: 'numeric' }); +const dateTime = ms => new Date(ms).toLocaleString([], { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' }); +function day(ms) { + const start = d => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); + const diff = Math.round((start(new Date(ms)) - start(new Date())) / 86400000); + return diff === 0 ? 'today, ' + shortDate(ms) : diff === 1 ? 'tomorrow, ' + shortDate(ms) : shortDate(ms); +} +function span(seconds) { + if (seconds < 3600) return Math.max(1, Math.round(seconds / 60)) + ' min'; + const hours = Math.floor(seconds / 3600), minutes = Math.round((seconds % 3600) / 60); + return minutes ? hours + ' h ' + minutes + ' min' : hours + ' h'; +} +const groups = hex => hex.match(/.{1,4}/g) ?? []; +const branded = theme => validTheme(theme) && typeof theme.name === 'string'; + +// ------------------------------------------------------------------ theming +function applyTheme(theme, pairing, host) { + const palette = windowPalette(branded(theme) ? theme : null, darkQuery.matches); + for (const [key, value] of Object.entries(palette)) document.documentElement.style.setProperty('--' + key, value); + const own = branded(theme); + $('brand-countersign').hidden = own; + $('brand-integrator').hidden = !own; + if (own) { + $('int-name').textContent = theme.name; + $('int-copy').textContent = theme.copy || ''; + const logo = $('int-logo'); + const png = typeof theme.logo === 'string' && theme.logo.startsWith('data:image/png;base64,'); + logo.hidden = !png; + if (png) logo.src = theme.logo; else logo.removeAttribute('src'); + $('int-origin').replaceChildren(icon('check'), element('span', host), document.createTextNode(' '), element('b', 'verified')); + $('int-origin').setAttribute('aria-label', 'Verified origin ' + host); + } + const id = own ? pairing : null; + if (id !== appearance) { + appearance = id; + void api.appearance(id).catch(() => {}); + } +} + +// --------------------------------------------------------------- approvals +const PRESETS = [{ id: '15m', label: '15 min', seconds: 900 }, { id: '1h', label: '1 h', seconds: 3600 }, + { id: '8h', label: '8 h', seconds: 28800 }, { id: 'custom', label: 'Custom' }]; + +function choiceFor(offer) { + let choice = choices.get(offer.handle); + if (!choice) { + const preset = PRESETS.find(p => p.seconds === offer.defaultDuration && p.seconds <= offer.maxDuration); + choice = { reference: null, preset: preset ? preset.id : 'custom', + minutes: String(Math.max(1, Math.round(Math.min(offer.defaultDuration, offer.maxDuration) / 60))) }; + choices.set(offer.handle, choice); + } + if (offer.identities.length === 1) choice.reference = offer.identities[0].reference; + return choice; +} + +function seconds(offer, choice) { + if (choice.preset !== 'custom') return PRESETS.find(p => p.id === choice.preset).seconds; + const minutes = Number(choice.minutes); + return Number.isSafeInteger(minutes) ? minutes * 60 : NaN; +} + +// Where the first fingerprint among same-named certificates differs. +function divergence(cert, identities) { + const others = identities.filter(other => other !== cert && other.identity === cert.identity); + if (!others.length) return -1; + let first = 64; + for (const other of others) { + let i = 0; + while (i < 64 && other.fingerprint[i] === cert.fingerprint[i]) i++; + first = Math.min(first, i); + } + return first; +} + +function identicon(fingerprint) { + const hue = parseInt(fingerprint.slice(0, 3), 16) % 360; + const on = darkQuery.matches ? 'hsl(' + hue + ' 60% 68%)' : 'hsl(' + hue + ' 55% 40%)'; + const grid = element('span', undefined, 'idc'); + grid.setAttribute('aria-hidden', 'true'); + for (let row = 0; row < 5; row++) for (let column = 0; column < 5; column++) { + const cell = element('span'); + const mirrored = column < 3 ? column : 4 - column; + if (parseInt(fingerprint[3 + row * 3 + mirrored], 16) % 2 === 0) cell.style.background = on; + grid.append(cell); + } + return grid; +} + +function certificateCard(offer, cert, choice) { + const label = element('label', undefined, 'cert identity'); + const input = element('input'); + input.type = 'radio'; + input.name = 'certificate'; + input.dataset.key = 'cert-' + cert.reference; + input.checked = choice.reference === cert.reference; + input.addEventListener('change', () => { choice.reference = cert.reference; draw(); }); + const body = element('span', undefined, 'cert-body'); + const fp = element('span', undefined, 'fp'); + fp.append(element('span', 'SHA-256', 'fp-label')); + const first = divergence(cert, offer.identities); + groups(cert.fingerprint).forEach((text, i) => { + const start = i * 4; + fp.append(element('span', text, 'fp-g' + (first >= 0 && start + 4 > first && start < first + 8 ? ' hot' : ''))); + }); + body.append(element('span', cert.identity, 'cert-name'), + element('span', 'Issued by ' + cert.issuer + ' · valid until ' + dateTime(cert.expiresAt), 'cert-meta'), fp); + label.append(input, identicon(cert.fingerprint), body); + return label; +} + +function approvalView(offer, locked) { + const pad = element('div', undefined, 'pad'); + pad.id = 'requests'; + if (banner && Date.now() < bannerUntil) { + const note = element('p', undefined, 'switch-banner'); + note.setAttribute('role', 'status'); + note.append(icon('arrow'), document.createTextNode(banner)); + pad.append(note); + } + const waiting = state.offers.length - 1; + const queue = element('div', undefined, 'queue'); + queue.setAttribute('role', 'status'); + const position = element('span'); + position.append(element('strong', 'Request 1 of ' + state.offers.length), document.createTextNode(' · oldest first')); + queue.append(position, element('span', waiting ? waiting + ' more waiting' : 'No others waiting')); + pad.append(queue, element('p', 'Approval request', 'eyebrow'), element('h1', 'Let this job use a client certificate?', 'h1')); + + const wide = offer.scope !== offer.host; + const facts = checkedFacts([fact('Integrator', offer.origin, 'fact-origin', true), fact('Account', offer.user), + fact('Context', offer.context), fact('Requested host', offer.host, '', true), + fact('Approval covers', offer.scope, wide ? 'is-wide' : '', true)]); + if (wide) facts.append(alert('warning', 'This approval covers more than the requested host.', + 'Any host matching ' + offer.scope + ' can use the certificate until access ends. Deny if you only meant ' + offer.host + '.')); + pad.append(facts); + if (!branded(offer.theme)) pad.append(element('p', 'This Integrator has not provided branding, so Countersign\'s own theme is shown.', 'nobrand')); + + const choice = choiceFor(offer); + const { identities } = offer; + const selected = identities.find(cert => cert.reference === choice.reference) ?? null; + const picker = element('fieldset', undefined, 'certs'); + picker.append(element('legend', 'Certificate', 'legend')); + const sameName = identities.length > 1 && identities.every(cert => cert.identity === identities[0].identity); + if (sameName) picker.append(element('p', identities.length + ' certificates are named ' + identities[0].identity + + '. Compare the highlighted part of each fingerprint and the pattern beside it.', 'note')); + for (const cert of identities) picker.append(certificateCard(offer, cert, choice)); + if (!identities.length) picker.append(offer.providerUnavailable + ? alert('danger', 'The certificate provider is unavailable', 'Unlock or reconnect it, then request access again from the job. On Linux, check that p11-kit sees the token in this login session.') + : alert('warning', 'No eligible certificate on this computer', 'A certificate must allow client authentication, have its private key here, and match the issuers this destination accepts. Ask the Integrator which certificate it expects, or deny this request.')); + pad.append(picker); + + const duration = seconds(offer, choice); + const validDuration = Number.isSafeInteger(duration) && duration >= 1 && duration <= offer.maxDuration; + const now = Date.now(); + const end = now + (validDuration ? duration : 0) * 1000; + const until = selected ? Math.min(end, selected.expiresAt) : end; + if (identities.length) { + const group = element('div'); + group.setAttribute('role', 'group'); + group.setAttribute('aria-labelledby', 'duration-title'); + const title = element('p', 'How long?', 'legend'); + title.id = 'duration-title'; + const seg = element('div', undefined, 'seg'); + for (const preset of PRESETS) { + const node = element('button', preset.label, 'seg-btn'); + node.type = 'button'; + node.dataset.key = 'preset-' + preset.id; + node.disabled = !!preset.seconds && preset.seconds > offer.maxDuration; + node.setAttribute('aria-pressed', String(choice.preset === preset.id)); + node.addEventListener('click', () => { choice.preset = preset.id; draw(); }); + seg.append(node); + } + group.append(title, seg); + if (choice.preset === 'custom') { + const custom = element('div', undefined, 'custom'); + const label = element('label', 'Minutes'); + const input = element('input'); + input.type = 'number'; + input.min = '1'; + input.max = String(Math.floor(offer.maxDuration / 60)); + input.value = choice.minutes; + input.dataset.key = 'minutes'; + input.addEventListener('input', () => { choice.minutes = input.value; draw(); }); + label.append(input); + custom.append(label, element('span', 'Up to ' + span(offer.maxDuration), 'hint')); + group.append(custom); + } + if (PRESETS.some(p => p.seconds > offer.maxDuration)) { + group.append(element('p', 'Your administrator allows up to ' + span(offer.maxDuration) + ', so longer presets are unavailable.', 'small-note')); + } + const ends = element('div', undefined, 'expires'); + ends.setAttribute('aria-live', 'polite'); + ends.append(element('span', 'Access ends', 'expires-label'), element('span', validDuration ? time(until) : '—', 'expires-time'), + element('span', validDuration ? day(until) + ' · in ' + span(Math.round((until - now) / 1000)) : 'Choose a duration', 'expires-day')); + group.append(ends); + if (selected && validDuration && selected.expiresAt < end) { + group.append(alert('warning', 'Shortened to the certificate\'s expiry', + 'This certificate expires at ' + time(selected.expiresAt) + ' ' + day(selected.expiresAt) + ', so access ends then.')); + } + pad.append(group); + } + pad.append(element('p', 'Until access ends, the Integrator\'s Gateway can read and send traffic to ' + offer.scope + ' using this certificate.', 'consequence')); + + let reason; + if (locked) reason = 'Approve unlocks in a moment: ' + (banner && Date.now() < bannerUntil ? 'this request is from a different Integrator.' : 'this request just arrived.'); + else if (!identities.length) reason = 'No certificate can be approved for this request. You can deny it.'; + else if (!selected) reason = 'Choose a certificate to continue.'; + else if (!validDuration) reason = 'Choose a duration up to ' + span(offer.maxDuration) + '.'; + else if (until <= now) reason = 'This certificate has expired.'; + else reason = 'Approves ' + selected.identity + ' (' + groups(selected.fingerprint.slice(0, 8)).join(' ') + ') for ' + span(Math.round((until - now) / 1000)) + '.'; + const disabled = locked || !selected || !validDuration || until <= now; + + const actions = element('div', undefined, 'actions'); + const deny = button('Deny', async () => { + await api.deny(offer.handle); + decided = { offer, approved: false }; + shown = { handle: offer.handle, pairing: offer.pairing }; + }, 'btn decision'); + const approve = button('Approve', async () => { + if (Date.now() < lockedUntil) return; + await api.decide(offer.handle, selected.reference, duration); + decided = { offer, approved: true, until, cert: selected }; + shown = { handle: offer.handle, pairing: offer.pairing }; + }, 'btn decision primary'); + approve.disabled = disabled; + approve.dataset.key = 'approve'; + deny.dataset.key = 'deny'; + const why = element('p', reason, 'reason'); + why.id = 'reason'; + actions.append(why, deny, approve); + return [pad, actions]; +} + +function resultView() { + const pad = element('div', undefined, 'pad'); + pad.id = 'requests'; + const { offer, approved, until, cert } = decided; + const host = originHost(offer.origin); + pad.append(element('p', approved ? 'Approved' : 'Denied', 'eyebrow'), + element('h1', approved ? 'The job can use your certificate' : 'Request denied', 'h1')); + const box = element('div', undefined, 'result'); + if (approved) { + box.append(element('p', host + ' can use ' + cert.identity + ' (' + groups(cert.fingerprint.slice(0, 8)).join(' ') + + ') for ' + offer.scope + ' until ' + time(until) + ' ' + day(until) + '.'), + element('p', 'Waiting for the Gateway. The approval shows Ready for handshakes under Integrators once the first handshake is signed.', 'small-note')); + } else { + box.append(element('p', host + ' can request access again after it changes the request.')); + } + pad.append(box); + const next = state.offers[0]; + const row = element('div', undefined, 'btnrow'); + row.append(next + ? button('Next request · ' + originHost(next.origin), () => { decided = null; draw(); }, 'btn primary') + : button('View Integrators', () => go('integrators'), 'btn')); + pad.append(row); + return [pad]; +} + +function idleView() { + const idle = element('div', undefined, 'idle'); + idle.id = 'requests'; + idle.append(icon('shieldEmpty'), element('h1', 'No pending requests'), + element('p', 'When a job asks to use one of your certificates, it opens here and Countersign notifies you. Closing this window keeps Countersign running in the tray.')); + if (!state.pairings.length) idle.append(button('Pair an Integrator', () => go('integrators'), 'btn')); + return [idle]; +} + +// ------------------------------------------------------------- integrators +function pairingView(enrollment, confirmation) { + const pad = element('div', undefined, 'pad'); + pad.id = 'pairing'; + const origin = confirmation?.origin ?? enrollment.origin; + const host = originHost(origin); + const code = confirmation?.code ?? enrollment?.code; + pad.append(element('p', 'Pairing request', 'eyebrow'), + element('h1', confirmation ? 'Confirm this pairing?' : enrollment.id === confirmed ? 'Finishing the pairing' : + code ? 'Enter this code in your browser' : 'Connecting to ' + host, 'h1')); + const rows = [fact('Integrator', origin, 'fact-origin', true)]; + if (confirmation) rows.push(fact('Account', confirmation.user)); + pad.append(checkedFacts(rows)); + if (code && enrollment?.id !== confirmed) { + const box = element('div', undefined, 'code-box'); + const value = element('p', groups(code).join(' '), 'code'); + value.setAttribute('aria-label', 'Pairing code ' + code.split('').join(' ')); + box.append(element('p', 'Pairing code', 'eyebrow'), value, element('p', confirmation + ? 'Check that your browser shows the same code for this account, then confirm here. If anything differs, cancel.' + : 'Countersign opened ' + host + ' in your browser. Sign in there and enter this code.', 'small-note')); + pad.append(box); + } else if (enrollment?.id === confirmed) { + pad.append(element('p', 'Waiting for ' + host + ' to finish. The Integrator appears under Paired Integrators once it connects.', 'small-note')); + } else if (enrollment) { + pad.append(element('p', enrollment.status, 'small-note')); + } + if (!confirmation) return [pad]; + const actions = element('div', undefined, 'actions'); + actions.append(element('p', 'Pairing lets ' + host + ' send you approval requests. It cannot approve anything by itself.', 'reason'), + button('Cancel pairing', () => api.confirmPair(confirmation.id, false), 'btn outline'), + button('Confirm pairing', async () => { + await api.confirmPair(confirmation.id, true); + confirmed = confirmation.pairing; + view.detail = null; + }, 'btn primary')); + return [pad, actions]; +} + +function swatch(theme) { + const chip = element('span', undefined, 'swatch'); + chip.setAttribute('aria-hidden', 'true'); + chip.style.background = windowPalette(branded(theme) ? theme : null, darkQuery.matches).primary; + return chip; +} + +function statusOf(pairing) { + const node = element('span', undefined, 'status ' + (pairing.status === 'Connected' ? 'st-ok' : 'st-muted')); + node.append(element('span', undefined, 'dot'), document.createTextNode(pairing.status)); return node; } -function branding(theme) { - const area = element('aside', undefined, 'brand'); - area.ariaLabel = 'Integrator branding'; - if (theme.logo) { +function flash(pad) { + if (!view.flash) return; + const note = element('p', view.flash, 'flash'); + note.setAttribute('role', 'status'); + pad.append(note); +} + +function listView() { + const pad = element('div', undefined, 'pad'); + flash(pad); + pad.append(element('h1', 'Paired Integrators', 'h1')); + const list = element('div'); + list.id = 'pairs'; + for (const pairing of state.pairings) { + const row = element('button', undefined, 'int-row'); + row.type = 'button'; + row.dataset.key = 'pairing-' + pairing.id; + const title = element('span', undefined, 'card-title'); + const count = pairing.approvals.length; + const summary = pairing.pendingTheme ? 'branding change to review' : count + (count === 1 ? ' approval' : ' approvals'); + title.append(element('strong', pairing.origin, 'mono'), + element('span', [branded(pairing.theme) ? pairing.theme.name : null, pairing.user, summary].filter(Boolean).join(' · '))); + const chevron = element('span', '›', 'chev'); + chevron.setAttribute('aria-hidden', 'true'); + row.append(swatch(pairing.theme), title, statusOf(pairing), chevron); + row.addEventListener('click', () => { view.detail = pairing.id; view.flash = ''; draw(); }); + list.append(row); + } + if (!state.pairings.length) list.append(element('p', 'No Integrators are paired with this computer yet.', 'note')); + pad.append(list, element('p', state.pairings.length ? 'Pair another Integrator' : 'Pair an Integrator', 'sub')); + const form = element('form', undefined, 'form'); + form.id = 'pair'; + const label = element('label', 'Integrator origin'); + const input = element('input'); + input.id = 'origin'; + input.type = 'url'; + input.placeholder = 'https://integrator.example'; + input.required = true; + input.value = originDraft; + input.dataset.key = 'origin'; + input.addEventListener('input', () => { originDraft = input.value; }); + label.append(input); + const submit = element('button', 'Pair', 'btn'); + submit.type = 'submit'; + form.append(label, submit); + form.addEventListener('submit', event => { + event.preventDefault(); + void run(async () => { + await api.pair(input.value); + originDraft = ''; + draw(); + }); + }); + pad.append(form, element('p', 'Countersign opens the Integrator in your browser. Sign in there and enter the code shown here.', 'small-note')); + return [pad]; +} + +// A small copy of the header band a branding would draw. +function preview(theme) { + if (!branded(theme)) return element('p', 'This branding cannot be shown.', 'note'); + const box = element('div', undefined, 'preview'); + const palette = windowPalette(theme, darkQuery.matches); + const band = element('div', undefined, 'preview-band'); + band.style.background = palette.band; + if (typeof theme.logo === 'string' && theme.logo.startsWith('data:image/png;base64,')) { const logo = element('img'); logo.alt = ''; logo.src = theme.logo; - area.append(logo); - } - area.style.borderColor = theme.accent; - area.style.backgroundColor = theme.background; - area.append(element('strong', theme.name), element('p', theme.copy)); - return area; -} - -function offerCard(offer) { - const card = element('article'); - if (offer.theme) card.append(branding(offer.theme)); - card.append(element('h3', 'Use a client certificate?')); - const facts = element('dl'); - for (const [key, value] of [ - ['Verified Integrator', offer.origin], ['Account', offer.user], ['Context', offer.context], - ['Requested host', offer.host], ['Approval covers', offer.scope], - ]) facts.append(element('dt', key), element('dd', value)); - card.append(facts); - const picker = element('fieldset'); - picker.append(element('legend', 'Certificate')); - const { identities } = offer; - const previous = selections.get(offer.handle); - let selection = identities.length === 1 ? identities[0] : - identities.find(item => item.reference === previous?.reference); - const duration = element('input'); - duration.type = 'number'; - duration.min = '1'; - duration.max = String(offer.maxDuration); - duration.value = String(previous?.seconds ?? offer.defaultDuration); - const expiry = element('p'); - const approve = button('Approve', () => api.decide(offer.handle, selection.reference, Number(duration.value)), 'approve'); - function update() { - const seconds = Number(duration.value); - const until = Math.min(Date.now() + seconds * 1000, selection?.expiresAt ?? 0); - approve.disabled = !selection || !Number.isSafeInteger(seconds) || seconds < 1 || - seconds > offer.maxDuration || until <= Date.now(); - expiry.textContent = approve.disabled ? '' : 'Expires by ' + new Date(until).toLocaleString(); - selections.set(offer.handle, { reference: selection?.reference, seconds }); - } - for (const cert of identities) { - const label = element('label', undefined, 'identity'); - const input = element('input'); - input.type = 'radio'; - input.name = 'certificate-' + offer.handle; - input.checked = cert === selection; - input.addEventListener('change', () => { selection = cert; update(); }); - label.append(input, document.createTextNode(cert.identity), element('div', 'Issued by ' + cert.issuer), - element('div', 'Valid until ' + new Date(cert.expiresAt).toLocaleString()), - element('small', 'SHA-256 ' + cert.fingerprint)); - picker.append(label); - } - if (!identities.length) picker.append(element('p', offer.providerUnavailable ? - 'The certificate provider is unavailable. Unlock or reconnect it and request access again.' : - 'No eligible installed certificate is available for this request.')); - const label = element('label', 'Duration (seconds) '); - label.append(duration); - duration.addEventListener('input', update); - update(); - const actions = element('div', undefined, 'actions'); - actions.append(approve, button('Deny', () => api.deny(offer.handle))); - card.append(picker, label, expiry, element('p', 'The Gateway can read and send traffic to the approved destination until access ends.'), actions); - return card; + band.append(logo); + } + const text = element('div'); + const copy = element('span', theme.copy || 'No description'); + copy.style.color = palette['band-muted']; + text.append(element('strong', theme.name), copy); + band.append(text); + const colors = element('div', undefined, 'preview-colors'); + const swatchOf = (label, value) => { + const item = element('span'); + const chip = element('i'); + if (/^#[0-9a-f]{6}$/.test(value)) chip.style.background = value; + item.append(chip, document.createTextNode(label + ' ' + value)); + return item; + }; + colors.append(swatchOf('accent', theme.accent), swatchOf('background', theme.background)); + if (theme.dark) colors.append(swatchOf('dark accent', theme.dark.accent), swatchOf('dark background', theme.dark.background)); + box.append(band, colors); + return box; } -let revision = 0; -async function render() { - const current = ++revision; - const state = await api.snapshot(); - if (revision !== current) return; - const handles = new Set(state.offers.map(offer => offer.handle)); - for (const key of selections.keys()) if (!handles.has(key)) selections.delete(key); - $('requests').replaceChildren(...(state.offers.length ? state.offers.map(offerCard) : [element('p', 'No pending requests.')])); - $('pairs').replaceChildren(...state.pairings.map(pairing => { - const card = element('article'); - card.append(element('strong', pairing.origin), element('p', pairing.user + ' · ' + pairing.status)); - if (pairing.pendingTheme) { - card.append(element('h3', 'Review branding change')); - if (pairing.theme) card.append(branding(pairing.theme)); - card.append(branding(pairing.pendingTheme), button('Accept new branding', () => api.theme(pairing.id, pairing.pendingTheme.digest))); - } - for (const notice of pairing.notices) { - card.append(element('p', (notice.kind === 'concurrent_devices' ? 'Another Companion connected' : 'Companion security event') + - ' · ' + new Date(notice.occurred_at_ms).toLocaleString() + ' · ' + (notice.observed_address || 'Address unavailable') + - ' · ' + (notice.actor?.pairing || '') + ' · ' + notice.kind)); +function openDialog({ title, body, confirm, danger, action }) { + const dialog = $('dialog'); + $('dialog-title').textContent = title; + $('dialog-body').textContent = body; + const ok = $('dialog-confirm'); + ok.textContent = confirm; + ok.className = 'btn ' + (danger ? 'danger' : 'primary'); + ok.onclick = () => { dialog.close(); void run(action); }; + $('dialog-cancel').onclick = () => dialog.close(); + dialog.showModal(); + $('dialog-cancel').focus(); +} + +function detailView(pairing) { + const pad = element('div', undefined, 'pad'); + const host = originHost(pairing.origin); + const back = element('div', undefined, 'btnrow'); + back.style.margin = '0 0 12px'; + back.append(button('‹ All Integrators', () => { view.detail = null; view.flash = ''; draw(); }, 'btn small')); + pad.append(back); + flash(pad); + const card = element('article', undefined, 'card'); + card.id = 'detail'; + const head = element('div', undefined, 'card-head'); + const title = element('span', undefined, 'card-title'); + title.append(element('strong', pairing.origin, 'mono'), + element('span', [branded(pairing.theme) ? pairing.theme.name : 'No branding', pairing.user].join(' · '))); + head.append(swatch(pairing.theme), title, statusOf(pairing)); + card.append(head); + + for (const notice of pairing.notices) { + card.append(alert('warning', notice.kind === 'concurrent_devices' ? 'Another Companion connected to this account' : 'Companion security event', + dateTime(notice.occurred_at_ms) + ' from ' + (notice.observed_address || 'an unknown address') + + (notice.actor?.pairing ? ', device ' + notice.actor.pairing : '') + '. Check the devices below.')); + } + + if (pairing.pendingTheme) { + card.append(element('p', 'Branding change to review', 'sub')); + const review = element('div', undefined, 'review'); + const current = element('div'); + current.append(element('p', 'Current', 'caption'), pairing.theme ? preview(pairing.theme) : element('p', 'No branding', 'note')); + const proposed = element('div'); + proposed.append(element('p', 'Proposed by ' + host, 'caption'), preview(pairing.pendingTheme)); + review.append(current, proposed); + card.append(review, element('p', 'Accepting also changes the colours this whole window takes on for ' + host + '.', 'small-note')); + const row = element('div', undefined, 'btnrow'); + const digest = pairing.pendingTheme.digest; + row.append(button('Accept new branding', async () => { + await api.theme(pairing.id, digest); + view.flash = 'New branding accepted for ' + host + '.'; + }, 'btn small'), button('Keep current', async () => { + await api.keepTheme(pairing.id, digest); + view.flash = 'Kept the current branding for ' + host + '.'; + }, 'btn small')); + card.append(row); + } + + if (pairing.approvals.length) { + card.append(element('p', 'Approvals', 'sub')); + for (const approval of pairing.approvals) { + const status = approval.revocation === 'pending' ? 'Revocation queued for Broker confirmation' : + approval.revocation === 'recorded' ? 'Broker recorded revocation. Existing traffic ends at its lease deadline' : + approval.ready ? 'Ready for handshakes' : 'Approved on this device'; + const tone = approval.revocation === 'pending' ? 'st-warn' : approval.revocation === 'recorded' ? '' : approval.ready ? 'st-ok' : ''; + const row = element('div', undefined, 'row'); + const main = element('div', undefined, 'row-main'); + main.append(element('strong', approval.host, 'mono'), + element('span', approval.context + ' · covers ' + approval.scope + ' · SHA-256 ' + groups(approval.fingerprint.slice(0, 8)).join(' ')), + element('span', status + ' · ends ' + time(approval.until) + ' ' + day(approval.until), tone || undefined)); + row.append(main); + if (approval.revocation !== 'recorded') { + row.append(button(approval.revocation ? 'Retry revocation' : 'Revoke access', () => api.revoke(pairing.id, approval.id), 'btn small')); + } + card.append(row); } - if (pairing.devices.length) { - const forget = (devices,all) => { - const ids = devices.map(d => d.binding); - if (window.confirm('Forget these pairings and revoke their grants? ' + ids.map(d=>d.pairing).join(', '))) { - return api.forgetOthers(pairing.id,ids,all); - } - }; - for (const d of pairing.devices) { - card.append(element('p', d.binding.pairing + ' · ' + (d.connected?'Connected':'Offline') + - ' · ' + (d.observed_address || 'Address unavailable')),button('Disconnect device',()=>forget([d],false))); + } + + const others = pairing.devices.filter(device => !device.self); + const disconnect = (devices, all) => () => api.forgetOthers(pairing.id, devices.map(d => d.binding), all); + if (pairing.devices.length) { + card.append(element('p', 'Companions on this account', 'sub')); + for (const device of pairing.devices) { + const row = element('div', undefined, 'row'); + const main = element('div', undefined, 'row-main'); + const name = element('strong', device.binding.pairing, 'mono'); + if (device.self) name.append(element('span', 'This computer', 'tag')); + main.append(name, element('span', (device.connected ? 'Connected' : 'Offline') + ' · ' + (device.observed_address || 'Address unavailable'))); + row.append(main); + if (!device.self) { + row.append(button('Disconnect device', () => openDialog({ + title: 'Disconnect device ' + device.binding.pairing + '?', + body: 'Its grants for ' + pairing.origin + ' are revoked. Traffic it already has stops by its current lease deadline.', + confirm: 'Disconnect device', danger: true, action: async () => { + await disconnect([device], false)(); + view.flash = 'Disconnect requested for ' + device.binding.pairing + '. Its grants are revoked.'; + }, + }), 'btn small')); } - if(pairing.devices.length > 1) card.append(button('Disconnect all other devices',()=>forget(pairing.devices,true))); + card.append(row); } - for (const approval of pairing.approvals) { - const status = approval.revocation === 'pending' ? 'Revocation queued for Broker confirmation' : - approval.revocation === 'recorded' ? 'Broker recorded revocation. Existing traffic ends at its lease deadline.' : - approval.ready ? 'Ready for handshakes' : 'Approved on this device'; - card.append(element('h3', approval.host), element('p', approval.context + ' · ' + approval.scope), - element('small', 'SHA-256 ' + approval.fingerprint), - element('p', status + ' · Expires ' + new Date(approval.until).toLocaleString())); - if (approval.revocation !== 'recorded') card.append(button(approval.revocation ? 'Retry revocation' : 'Revoke access', () => api.revoke(pairing.id, approval.id))); + } + + const row = element('div', undefined, 'btnrow'); + if (others.length > 1) { + row.append(button('Disconnect all other devices', () => openDialog({ + title: 'Disconnect all other devices?', + body: 'Every other Companion paired to ' + pairing.user + ' at ' + pairing.origin + ' loses its pairing and grants. This computer stays paired.', + confirm: 'Disconnect all others', danger: true, action: async () => { + await disconnect(others, true)(); + view.flash = 'Disconnect requested for every other device.'; + }, + }), 'btn small')); + } + row.append(button('Revoke pairing at Integrator', () => openDialog({ + title: 'Revoke this pairing at ' + host + '?', + body: 'Countersign opens ' + pairing.origin + '/countersign/devices in your browser. Choose the pairing to forget there; its grants end with it.', + confirm: 'Open in browser', danger: false, action: async () => { + await api.forget(pairing.id); + view.flash = 'Opened the device page of ' + host + ' in your browser.'; + }, + }), 'btn small'), button('Remove from this computer', () => openDialog({ + title: 'Remove ' + host + ' from this computer?', + body: 'Deletes this computer\'s pairing key for ' + pairing.origin + '. Access already granted stays active until you revoke it at the Integrator.', + confirm: 'Remove from this computer', danger: true, action: async () => { + await api.removeLocal(pairing.id); + view.detail = null; + view.flash = 'Removed ' + host + ' from this computer.'; + }, + }), 'btn small')); + card.append(row); + pad.append(card); + return [pad]; +} + +function settingsView() { + const pad = element('div', undefined, 'pad'); + pad.append(element('h1', 'Settings', 'h1')); + const login = element('div', undefined, 'card'); + const label = element('label', undefined, 'check'); + const box = element('input'); + box.type = 'checkbox'; + box.id = 'login'; + box.checked = state.login; + box.dataset.key = 'login'; + box.addEventListener('change', () => run(() => api.login(box.checked))); + const text = element('span', 'Start at login'); + text.append(element('span', 'Receive requests as soon as you sign in to this computer.')); + label.append(box, text); + login.append(label); + const appearanceCard = element('div', undefined, 'card'); + appearanceCard.append(element('p', 'Appearance', 'card-title-plain'), element('p', + 'Follows your system\'s light or dark setting. While an Integrator\'s request, pairing or details are open, the window uses that Integrator\'s colours.', 'small-note')); + const quit = element('div', undefined, 'card'); + quit.append(element('p', 'Closing and quitting', 'card-title-plain'), element('p', + 'Closing this window keeps Countersign in the tray, receiving requests and signing approved handshakes. Choose Quit in the tray to stop it; new handshakes then wait until you reopen it.', 'small-note')); + pad.append(login, appearanceCard, quit); + return [pad]; +} + +// ------------------------------------------------------------------ drawing +function go(tab) { + if ($('dialog').open) $('dialog').close(); + view.tab = tab; + view.detail = null; + view.flash = ''; + decided = null; + draw(); +} + +function draw() { + if (!state) return; + clearTimeout(timer); + const focused = document.activeElement?.dataset?.key; + const enrollment = state.pending[0]; + const confirmation = state.confirmation; + let parts, theme = null, pairing = null, host = ''; + + if (view.tab === 'requests') { + const head = state.offers[0]; + if (decided) { + parts = resultView(); + ({ theme, pairing } = decided.offer); + host = originHost(decided.offer.origin); + } else if (head) { + const change = headChange(shown, head); + if (change.lock) lockedUntil = Date.now() + LOCK_MS; + if (change.banner) { banner = change.banner; bannerUntil = Date.now() + 3500; } + shown = { handle: head.handle, pairing: head.pairing }; + parts = approvalView(head, Date.now() < lockedUntil); + ({ theme, pairing } = head); + host = originHost(head.origin); + } else { + parts = idleView(); } - card.append(button('Remove from this computer', () => { - if (window.confirm('Delete this local pairing key? Use the Integrator to revoke existing remote access.')) return api.removeLocal(pairing.id); - })); - card.append(button('Revoke pairing at Integrator', () => { - if (window.confirm('Forget the pairing with ' + pairing.origin + ' and revoke its grants?')) return api.forget(pairing.id); - })); - return card; - })); - $('pending').textContent = state.pending ?? ''; - if (state.confirmation) { - const c = state.confirmation; - $('pending').replaceChildren(element('p', c.origin + ' · ' + c.user + ' · ' + c.code), - button('Confirm pairing', () => api.confirmPair(c.id, true)), - button('Cancel pairing', () => api.confirmPair(c.id, false))); - } - $('login').checked = state.login; -} - -$('pair').addEventListener('submit', event => { - event.preventDefault(); - void run(() => api.pair($('origin').value)); -}); -$('login').addEventListener('change', () => run(() => api.login($('login').checked))); -api.changed(() => run(render)); -void run(render); + } else if (view.tab === 'integrators') { + const detail = state.pairings.find(p => p.id === view.detail); + if (!detail) view.detail = null; + if (confirmation || enrollment) { + parts = pairingView(enrollment, confirmation); + theme = confirmation ? confirmation.theme : enrollment.theme; + pairing = confirmation ? confirmation.pairing : enrollment.id; + host = originHost(confirmation?.origin ?? enrollment.origin); + } else if (detail) { + parts = detailView(detail); + ({ theme } = detail); + pairing = detail.id; + host = originHost(detail.origin); + } else { + parts = listView(); + } + } else { + parts = settingsView(); + } + + applyTheme(theme, pairing, host); + const section = element('section', undefined, 'view'); + section.append(...parts); + $('content').replaceChildren(section); + for (const tab of document.querySelectorAll('.tab')) { + if (tab.dataset.tab === view.tab) tab.setAttribute('aria-current', 'page'); + else tab.removeAttribute('aria-current'); + } + const count = state.offers.length; + $('badge').hidden = !count; + $('badge').textContent = String(count); + $('badge').setAttribute('aria-label', count + ' pending'); + if (focused) document.querySelector('[data-key="' + CSS.escape(focused) + '"]')?.focus(); + + // Re-draw when the Approve lock or the banner runs out. + const wake = [lockedUntil, bannerUntil].filter(at => at > Date.now()); + if (wake.length) timer = setTimeout(draw, Math.min(...wake) - Date.now() + 20); +} + +let revision = 0; +async function refresh() { + const current = ++revision; + const next = await api.snapshot(); + if (revision !== current) return; + const handles = new Set(next.offers.map(offer => offer.handle)); + for (const key of choices.keys()) if (!handles.has(key)) choices.delete(key); + if (view.tab === null) view.tab = next.pairings.length || next.offers.length ? 'requests' : 'integrators'; + // A new request opens the Requests tab; a pairing to confirm opens Integrators. + if (known && [...handles].some(handle => !known.has(handle)) && view.tab !== 'requests') { + if ($('dialog').open) $('dialog').close(); + view.tab = 'requests'; + view.detail = null; + decided = null; + } + known = handles; + if (next.confirmation && next.confirmation.id !== confirmationSeen && view.tab !== 'integrators') { + if ($('dialog').open) $('dialog').close(); + view.tab = 'integrators'; + } + confirmationSeen = next.confirmation?.id ?? null; + state = next; + draw(); +} + +for (const tab of document.querySelectorAll('.tab')) tab.addEventListener('click', () => go(tab.dataset.tab)); +darkQuery.addEventListener('change', draw); +api.changed(() => run(refresh)); +void run(refresh); diff --git a/packages/companion/src/session.js b/packages/companion/src/session.js index 2131f04..6ccbba2 100644 --- a/packages/companion/src/session.js +++ b/packages/companion/src/session.js @@ -3,7 +3,7 @@ import { createHash, randomUUID } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; import WebSocket from 'ws'; import { displayText } from './origins.js'; -import { readTheme, refreshTheme } from './theme.js'; +import { readTheme, refreshTheme, reviewTheme } from './theme.js'; function authority(origin) { const url = new URL(origin); @@ -85,7 +85,8 @@ export class Session extends EventEmitter { const r = this.record; if (type === 'pairing_pending' && !this.device && !r.pairing && !this.attempt) { this.attempt = body.attempt; - this.status = 'Pairing code ' + displayText(body.code, 32); + this.code = displayText(body.code, 32); + this.status = 'Pairing code ' + this.code; this.emit('changed'); await this.launchPairing(r.origin, body.attempt); return; @@ -96,7 +97,7 @@ export class Session extends EventEmitter { body.issued_at_ms > Date.now() + 1000 || body.expires_at_ms - body.issued_at_ms > 60000 || (r.pairing ? body.purpose.reconnect?.pairing !== r.pairing || body.user !== r.user || body.key !== r.key : !this.attempt || body.purpose.pair?.attempt !== this.attempt)) throw new Error('Invalid pairing challenge.'); - if (!r.pairing && !await this.confirmAccount(r.origin, displayText(body.user), this.status)) { + if (!r.pairing && !await this.confirmAccount(r.origin, displayText(body.user), this.code)) { this.stop(); return; } @@ -156,7 +157,7 @@ export class Session extends EventEmitter { providerUnavailable = true; } if (!current() || body.expires_at_ms <= Date.now()) return; - this.offers.set(approval, { handle: randomUUID(), body, identities, providerUnavailable }); + this.offers.set(approval, { handle: randomUUID(), received: Date.now(), body, identities, providerUnavailable }); this.emit('changed'); } else if (type === 'revoke_recorded') { if (this.revokeRequests.get(id) !== body.id) return; @@ -215,6 +216,13 @@ export class Session extends EventEmitter { this.emit('changed'); } + // Accept the pending branding, or keep the current one. + async reviewBrand(digest, accept) { + await this.store.update(this.record.id, r => reviewTheme(r, digest, accept)); + this.record = this.store.get(this.record.id); + this.emit('changed'); + } + async decide(offer, selection, seconds) { const { body } = offer; if (this.offers.get(body.binding.approval) !== offer || body.expires_at_ms <= Date.now() || diff --git a/packages/companion/src/theme.js b/packages/companion/src/theme.js index 6cf5af8..02b7a64 100644 --- a/packages/companion/src/theme.js +++ b/packages/companion/src/theme.js @@ -25,6 +25,13 @@ function color(input) { return input.toLowerCase(); } +// An optional pair for dark appearance. Without it the Companion derives the +// dark palette from the light colours. +function darkColors(input) { + if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Expected dark theme colors.'); + return { accent: color(input.accent), background: color(input.background) }; +} + // Accept PNG only. Check dimensions before the desktop decoder allocates, then // re-encode the decoded image so that only local raster bytes reach the UI. async function logoData(origin, locator, fetcher, decodeLogo) { @@ -53,6 +60,9 @@ export async function readTheme(origin, fetcher, decodeLogo) { copy: displayText(manifest.copy ?? '', 240), accent: color(manifest.colors?.accent ?? '#164e63'), background: color(manifest.colors?.background ?? '#ffffff'), + // Present only when the manifest sets it, so the digests of manifests + // without dark colours stay as they were. + ...(manifest.colors?.dark === undefined ? {} : { dark: darkColors(manifest.colors.dark) }), logo: manifest.logo === undefined ? null : await logoData(origin, displayText(manifest.logo, 1024), fetcher, decodeLogo), }; @@ -60,9 +70,21 @@ export async function readTheme(origin, fetcher, decodeLogo) { return { digest, ...theme }; } +// A download that matches the accepted theme clears any review. One the +// person chose to keep their current branding over is not offered again; +// a further change is. export function refreshTheme(pairing, downloaded) { if (pairing.theme?.digest === downloaded.digest) { - return { ...pairing, pendingTheme: null }; + return { ...pairing, pendingTheme: null, declinedTheme: null }; } - return { ...pairing, pendingTheme: downloaded }; + if (pairing.declinedTheme === downloaded.digest) return { ...pairing, pendingTheme: null }; + return { ...pairing, pendingTheme: downloaded, declinedTheme: null }; +} + +// Accept or keep: settle a pending review only if it is still the one shown. +export function reviewTheme(pairing, digest, accept) { + if (!pairing?.pendingTheme || pairing.pendingTheme.digest !== digest) throw new Error('Branding changed.'); + return accept + ? { ...pairing, theme: pairing.pendingTheme, pendingTheme: null, declinedTheme: null } + : { ...pairing, pendingTheme: null, declinedTheme: digest }; } diff --git a/packages/companion/test/theming.test.js b/packages/companion/test/theming.test.js new file mode 100644 index 0000000..a7d89d9 --- /dev/null +++ b/packages/companion/test/theming.test.js @@ -0,0 +1,145 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { test } from 'node:test'; +import { contrast, countersignPalette, derivePalette, fixedPalette, validTheme, windowPalette } from '../src/palette.js'; +import { readTheme, refreshTheme, reviewTheme } from '../src/theme.js'; +import { headChange, orderQueue } from '../src/queue.js'; + +const site = 'https://integrator.test'; +const manifest = value => async () => Response.json(value); + +// Text pairs and their WCAG AA targets. The band carries white text and must +// clear 7:1; focus rings and other non-text marks need 3:1. +const PAIRS = [ + ['band-ink', 'band', 7], ['band-muted', 'band', 4.5], ['underline', 'band', 4.5], ['band', 'underline', 4.5], + ['ink', 'ground', 4.5], ['ink', 'surface', 4.5], ['ink', 'accent-soft', 4.5], ['muted', 'ground', 4.5], + ['muted', 'surface', 4.5], ['accent', 'surface', 4.5], ['accent', 'ground', 4.5], ['on-primary', 'primary', 4.5], + ['focus', 'ground', 3], ['focus', 'surface', 3], ['hot-ink', 'hot-bg', 4.5], ['chk-ink', 'chk-surface', 4.5], + ['chk-muted', 'chk-surface', 4.5], ['warn-ink', 'warn-bg', 4.5], ['danger-ink', 'danger-bg', 4.5], + ['on-danger', 'danger', 4.5], ['note-ink', 'note-bg', 4.5], +]; + +test('derived palettes clamp every text pair to WCAG AA, however hostile the manifest colours', () => { + const levels = ['00', '1d', '66', '80', '99', 'cc', 'e6', 'ff']; + const colors = []; + for (const r of levels) for (const g of levels) for (const b of levels) colors.push('#' + r + g + b); + const backgrounds = ['#ffffff', '#000000', '#ffff00', '#e6f0f7', '#202020']; + let checked = 0; + for (const accent of colors) for (const background of backgrounds) for (const dark of [false, true]) { + for (const theme of [{ accent, background }, { accent, background, dark: { accent: background, background: accent } }]) { + const palette = windowPalette(theme, dark); + for (const value of Object.values(palette)) assert.match(value, /^(#[0-9a-f]{6}|rgba\([\d,. ]+\))$/); + for (const [fg, bg, target] of PAIRS) { + const ratio = contrast(palette[fg], palette[bg]); + assert.ok(ratio >= target, `${fg} on ${bg} is ${ratio.toFixed(2)} for ${JSON.stringify(theme)} dark=${dark}`); + checked++; + } + } + } + assert.ok(checked > 100000); +}); + +test('the Countersign theme applies without a valid theme, and fixed colours never follow a manifest', () => { + for (const dark of [false, true]) { + for (const invalid of [null, undefined, {}, { accent: 'red', background: '#ffffff' }, + { accent: '#ABCDEF', background: '#ffffff' }, { accent: '#123456', background: '#ffffff', dark: { accent: '#123456' } }, + { accent: '#123456', background: 'url(x)' }]) { + assert.equal(validTheme(invalid), false); + assert.deepEqual(windowPalette(invalid, dark), windowPalette(null, dark)); + } + const branded = windowPalette({ accent: '#ff00ff', background: '#00ff00' }, dark); + for (const [key, value] of Object.entries(fixedPalette(dark))) assert.equal(branded[key], value); + assert.equal(windowPalette(null, dark).band, countersignPalette(dark).band); + assert.equal(countersignPalette(dark).band, '#2b0548'); + } + assert.equal(countersignPalette(false).primary, '#224805'); + assert.equal(countersignPalette(true).primary, '#a1ca7c'); +}); + +test('colors.dark drives the dark palette; without it the dark palette is derived', () => { + const light = { accent: '#1d5f8a', background: '#e6f0f7' }; + const derived = derivePalette(light, true); + const teal = derivePalette({ ...light, dark: { accent: '#5cc8bd', background: '#0f1f1e' } }, true); + assert.notDeepEqual(derived, teal); + assert.deepEqual(derivePalette(light, false), derivePalette({ ...light, dark: { accent: '#5cc8bd', background: '#0f1f1e' } }, false)); + // Dark grounds stay dark even when a manifest asks for a light one. + const bright = derivePalette({ ...light, dark: { accent: '#ffffff', background: '#ffffff' } }, true); + assert.ok(contrast(bright.ground, '#000000') < 3); +}); + +test('the manifest accepts an optional colors.dark pair, validated like the other colours', async () => { + const base = { version: 1, displayName: 'Example', colors: { accent: '#164E63', background: '#FFFFFF' } }; + const plain = await readTheme(site, manifest(base)); + assert.equal(Object.hasOwn(plain, 'dark'), false); + // Manifests without dark colours keep the digest they had before the field existed. + const { digest, ...fields } = plain; + assert.deepEqual(Object.keys(fields), ['name', 'copy', 'accent', 'background', 'logo']); + assert.equal(digest, createHash('sha256').update(JSON.stringify(fields)).digest('hex')); + + const withDark = await readTheme(site, manifest({ ...base, colors: { ...base.colors, dark: { accent: '#5CC8BD', background: '#0f1f1e' } } })); + assert.deepEqual(withDark.dark, { accent: '#5cc8bd', background: '#0f1f1e' }); + assert.equal(withDark.accent, '#164e63'); + assert.notEqual(withDark.digest, plain.digest); + const otherDark = await readTheme(site, manifest({ ...base, colors: { ...base.colors, dark: { accent: '#5cc8bd', background: '#101f1e' } } })); + assert.notEqual(otherDark.digest, withDark.digest); + // A dark-colour change alone is a branding change that needs review. + assert.equal(refreshTheme({ theme: withDark, pendingTheme: null }, otherDark).pendingTheme, otherDark); + + for (const dark of [null, '#000000', [], { accent: '#5cc8bd' }, { background: '#0f1f1e' }, + { accent: '#5cc8bd', background: 'black' }, { accent: '#5cc8bd', background: '#0f1f1e;color:red' }, + { accent: 'var(--x)', background: '#0f1f1e' }]) { + await assert.rejects(readTheme(site, manifest({ ...base, colors: { ...base.colors, dark } })), JSON.stringify(dark)); + } +}); + +test('Keep current dismisses a branding change until the Integrator changes it again', async () => { + const { Session } = await import('../src/session.js'); + const theme = await readTheme(site, manifest({ version: 1, displayName: 'Example' })); + const proposed = await readTheme(site, manifest({ version: 1, displayName: 'Example', copy: 'New copy' })); + const later = await readTheme(site, manifest({ version: 1, displayName: 'Example', copy: 'Other copy' })); + let stored = { id: 'local', origin: site, pairing: 'p', theme, pendingTheme: proposed }; + const store = { get: () => structuredClone(stored), update: async (_id, change) => { stored = change(structuredClone(stored)); } }; + const session = new Session({ record: store.get(), store }); + let changed = 0; + session.on('changed', () => changed++); + + await assert.rejects(session.reviewBrand('stale-digest', false), /Branding changed/); + assert.equal(stored.pendingTheme.digest, proposed.digest); + await session.reviewBrand(proposed.digest, false); + assert.equal(stored.theme.digest, theme.digest); + assert.equal(stored.pendingTheme, null); + assert.equal(stored.declinedTheme, proposed.digest); + assert.equal(session.record.pendingTheme, null); + assert.equal(changed, 1); + // The same download on reconnect is not offered again; a further change is. + assert.equal(refreshTheme(stored, proposed).pendingTheme, null); + assert.equal(refreshTheme(stored, later).pendingTheme, later); + assert.equal(refreshTheme(stored, theme).declinedTheme, null); + await assert.rejects(session.reviewBrand(proposed.digest, true), /Branding changed/); + + stored = refreshTheme(stored, later); + await session.reviewBrand(later.digest, true); + assert.equal(stored.theme.digest, later.digest); + assert.equal(stored.pendingTheme, null); + assert.throws(() => reviewTheme({ ...stored }, later.digest, true), /Branding changed/); + session.stop(); +}); + +test('requests queue oldest first and a change of Integrator is announced and locks Approve', () => { + const offers = [ + { handle: 'c', received: 30, pairing: 'one', origin: 'https://one.example' }, + { handle: 'b', received: 10, pairing: 'two', origin: 'https://two.example:8443' }, + { handle: 'a', received: 30, pairing: 'one', origin: 'https://one.example' }, + { handle: 'd', received: 20, pairing: 'one', origin: 'https://one.example' }, + ]; + assert.deepEqual(orderQueue(offers).map(o => o.handle), ['b', 'd', 'a', 'c']); + assert.deepEqual(offers.map(o => o.handle), ['c', 'b', 'a', 'd']); + + const [b, d, a] = orderQueue(offers); + assert.deepEqual(headChange(null, b), { lock: true, banner: null }); + assert.deepEqual(headChange(b, b), { lock: false, banner: null }); + assert.deepEqual(headChange(d, a), { lock: true, banner: null }); + assert.deepEqual(headChange(b, d), { lock: true, banner: 'Now showing a request from one.example' }); + assert.deepEqual(headChange(d, b), { lock: true, banner: 'Now showing a request from two.example:8443' }); + assert.deepEqual(headChange(b, undefined), { lock: false, banner: null }); +}); diff --git a/scripts/annotate_screenshots.py b/scripts/annotate_screenshots.py index e224d12..d8f9a48 100644 --- a/scripts/annotate_screenshots.py +++ b/scripts/annotate_screenshots.py @@ -30,34 +30,55 @@ OUTSET, LINE, RADIUS, FONT, GAP = 4, 3, 5, 12, 6 # output name -> (raw source, [(box key from boxes.json, label, placement[, anchor key])]) -# Placement puts the label to the "right" of the box, "below-end" or +# Placement puts the label to the "right" or "left" of the box, "below-end" or # "above-end" (under or over it, flush with its right edge), or "inside-end" # (inside its top-right corner). With an anchor key the label is placed # against that box instead of the highlighted one. CALLOUTS: dict[str, tuple[str, list[tuple[str, ...]]]] = { "approval-unselected.png": ("approval-unselected.png", [ - ("identities", "Same name: compare issuer, expiry, SHA-256", "inside-end"), - ("approve", "Disabled until you choose", "right", "actions"), + ("identities", "Same name: compare the highlighted fingerprints", "inside-end"), + ("actions", "Fixed labels, order and size", "above-end"), ]), "approval-selected.png": ("approval-selected.png", [ ("selected", "Selected certificate", "inside-end"), - ("expiry", "Approval ends here", "right"), + ("expiry", "Approval ends here", "inside-end"), ]), "approval-branding.png": ("approval-selected.png", [ - ("branding", "Integrator branding", "below-end"), + ("header", "Branding + verified origin", "right"), + ("facts", "Request facts: fixed rows and order", "inside-end"), + ("plate", "Fixed Countersign mark", "left"), ]), "scope-wildcard.png": ("scope-wildcard.png", [ - ("scope", "Exact host vs. what approval covers", "right"), + ("scope", "Exact host vs. what approval covers", "above-end"), ]), "branding-alternate.png": ("branding-alternate.png", [ - ("branding", "Integrator branding", "below-end"), + ("header", "Branding + verified origin", "right"), + ("approve", "Clamped accent colour", "above-end"), + ]), + "branding-none.png": ("branding-none.png", [ + ("brand", "No manifest", "right"), + ]), + "queue-switch.png": ("queue-switch.png", [ + ("banner", "Fixed banner", "inside-end"), + ("approve", "Locked for a moment", "above-end"), ]), "pairing-browser.png": ("pairing-browser.png", [ ("code", "Code from the Companion", "inside-end"), ]), "pairing-companion.png": ("pairing-companion.png", [ - ("confirmation", "Check origin, account and code", "right"), + ("facts", "Check origin and account", "inside-end"), + ("code", "Same code as the browser", "inside-end"), + ]), + "integrators-list.png": ("integrators-list.png", []), + "integrator-detail.png": ("integrator-detail.png", [ + ("notice", "Security notice", "inside-end"), + ("self", "Known from this pairing", "right"), + ]), + "branding-review.png": ("branding-review.png", [ + ("review", "Old and new branding", "above-end"), + ("buttons", "Accept or keep", "right"), ]), + "dialog-remove.png": ("dialog-remove.png", []), "widget.png": ("widget.png", [ ("page", "Integrator page", "below-end"), ("widget", "Countersign widget", "below-end"), @@ -105,6 +126,8 @@ def box(key: str) -> tuple[float, float, float, float]: w, h = right - left + 2 * pad_x, bottom - top + 2 * pad_y if placement == "right": bx, by = x1 + GAP * k, (y0 + y1 - h) / 2 + elif placement == "left": + bx, by = x0 - GAP * k - w, (y0 + y1 - h) / 2 elif placement == "below-end": bx, by = x1 - w, y1 + GAP * k elif placement == "above-end": diff --git a/scripts/capture_screenshots.mjs b/scripts/capture_screenshots.mjs index 891459d..efab8e7 100644 --- a/scripts/capture_screenshots.mjs +++ b/scripts/capture_screenshots.mjs @@ -45,22 +45,51 @@ const certificate = (reference, fingerprint) => ({ }); const harborLogo = 'data:image/png;base64,' + (await readFile(new URL('site/harbor-ledger.png', DEMO_DIR))).toString('base64'); -const harbor = { digest: 'harbor', name: manifest.displayName, copy: manifest.copy, logo: harborLogo, - accent: manifest.colors.accent, background: manifest.colors.background }; +const harbor = { digest: 'harbor', name: manifest.displayName, copy: manifest.copy, + accent: manifest.colors.accent, background: manifest.colors.background, dark: manifest.colors.dark, logo: harborLogo }; // A second fictional Integrator, to show that branding belongs to the pairing. -const lantern = { digest: 'lantern', name: 'Lantern Audit', copy: 'Engagement evidence room', logo: null, - accent: '#9a4a0c', background: '#fbefe2' }; +// It sets no dark colours, so the Companion derives them. +const lantern = { digest: 'lantern', name: 'Lantern Audit', copy: 'Engagement evidence room', + accent: '#d9822b', background: '#fdf6ee', logo: null }; +const lanternNext = { digest: 'lantern-2', name: 'Lantern Audit', copy: 'Evidence room for FY26 fieldwork', + accent: '#7a3e9d', background: '#f4edf9', logo: null }; +const AUDIT = 'https://audit.example'; +const JOBS = 'https://jobs.example'; const job = { user: 'u-42', context: 'close-q3', title: 'Q3 close reconciliation', workload: 'export-981', workload_generation: 1, host: 'ledger.partner.example:443' }; const offer = (extra = {}) => ({ - handle: 'offer-1', origin: PORTAL, user: job.user, context: job.context, theme: harbor, - host: job.host, scope: job.host, providerUnavailable: false, maxDuration: 28800, defaultDuration: 3600, + handle: 'offer-1', received: NOW.getTime() - 5000, pairing: 'harbor', origin: PORTAL, user: job.user, + context: job.context, theme: harbor, host: job.host, scope: job.host, providerUnavailable: false, + maxDuration: 28800, defaultDuration: 3600, identities: [certificate('first', fingerprints.first), certificate('selected', fingerprints.selected)], ...extra, }); -const snapshot = (extra = {}) => ({ offers: [], pairings: [], pending: '', confirmation: null, login: false, ...extra }); +const lanternOffer = (extra = {}) => offer({ handle: 'offer-2', received: NOW.getTime() - 2000, pairing: 'lantern', + origin: AUDIT, user: 'analyst-7', context: 'fy26-fieldwork', theme: lantern, host: 'evidence.audit.example:443', + scope: 'evidence.audit.example:443', identities: [certificate('selected', fingerprints.selected)], ...extra }); +const snapshot = (extra = {}) => ({ offers: [], pairings: [], pending: [], confirmation: null, login: true, ...extra }); const approvalId = '85b80155-ac10-487f-a024-5216ec7f8ced'; -const device = { binding: { pairing: '7b9df613-d84e-4c1a-9a0e-2f6b1c3d5e7a', key: 'k1', channel_generation: 1 }, +const binding = pairing => ({ pairing, key: 'k-' + pairing.slice(0, 4), channel_generation: 1 }); +const device = { binding: binding('7b9df613-d84e-4c1a-9a0e-2f6b1c3d5e7a'), connected: true, connected_at_ms: NOW.getTime() - 600000, observed_address: '198.51.100.24' }; +const otherDevice = { binding: binding('91ab3c5e-0f27-4b8e-a6d1-c2e4f8a90b13'), connected: true, + connected_at_ms: NOW.getTime() - 1680000, observed_address: '203.0.113.24' }; +const approval = (id, extra) => ({ id, host: job.host, scope: job.host, context: job.context, + until: NOW.getTime() + 3600000, fingerprint: fingerprints.selected, revocation: undefined, ready: true, ...extra }); +const pairings = [ + { id: 'harbor', origin: PORTAL, user: job.user, status: 'Connected', theme: harbor, pendingTheme: null, + devices: [{ ...device, self: true }, { ...otherDevice, self: false }], + notices: [{ id: 'n1', kind: 'concurrent_devices', occurred_at_ms: NOW.getTime() - 1680000, + observed_address: '203.0.113.24', actor: { pairing: otherDevice.binding.pairing } }], + approvals: [approval('a1'), + approval('a2', { host: 'reports.team.example:9444', scope: '*.team.example:9444', until: NOW.getTime() + 5400000, + revocation: 'pending', ready: false }), + approval('a3', { context: 'close-q2', until: NOW.getTime() + 1200000, revocation: 'recorded', ready: false })] }, + { id: 'lantern', origin: AUDIT, user: 'analyst-7', status: 'Offline', theme: lantern, pendingTheme: lanternNext, + devices: [], notices: [], approvals: [] }, + { id: 'jobs', origin: JOBS, user: job.user, status: 'Connected', theme: null, pendingTheme: null, + devices: [{ ...device, binding: binding('c3d1e8a2-5b7f-4e09-9a61-3f2b8d4c7e15'), self: true }], notices: [], + approvals: [approval('a4', { context: 'nightly-export', until: NOW.getTime() + 7200000 })] }, +]; // ------------------------------------------------------------- page helpers async function newPage(browser, options) { @@ -71,24 +100,47 @@ async function newPage(browser, options) { return page; } -async function companion(browser, state) { - const page = await newPage(browser, { viewport: { width: 760, height: 1600 }, colorScheme: 'light' }); +// The Companion window, 660 pixels wide like the app, made tall enough that +// nothing scrolls. `state` is the snapshot the main process would return. +async function companion(browser, scheme, state) { + const page = await newPage(browser, { viewport: { width: 660, height: 760 }, colorScheme: scheme }); await page.route(COMPANION + '**', async route => { const path = new URL(route.request().url()).pathname.slice(1) || 'index.html'; if (!/^[a-z.]+\.(html|js|css)$/.test(path)) return route.fulfill({ status: 404 }); await route.fulfill({ body: await readFile(new URL(path, COMPANION_SRC)), contentType: types[extname(path)] }); }); - // Stands in for preload.cjs. Only snapshot() returns data; the actions do nothing. + // Stands in for preload.cjs. Only snapshot() returns data; the actions do + // nothing. update() swaps the snapshot and announces it like the main process. await page.addInitScript(state => { const nothing = async () => {}; + let listener = () => {}; window.countersign = { snapshot: async () => state, pair: nothing, confirmPair: nothing, decide: nothing, - deny: nothing, theme: nothing, forgetOthers: nothing, revoke: nothing, removeLocal: nothing, - forget: nothing, login: nothing, changed: () => () => {} }; + deny: nothing, theme: nothing, keepTheme: nothing, appearance: nothing, forgetOthers: nothing, revoke: nothing, + removeLocal: nothing, forget: nothing, login: nothing, changed: callback => { listener = callback; return () => {}; } }; + window.update = next => { state = next; listener(); }; }, state); await page.goto(COMPANION + 'index.html'); + await page.locator('#content > .view').waitFor(); + // Each newly shown request locks Approve for a second. The page clock is + // fixed, so move it past the lock. + await page.clock.setFixedTime(NOW.getTime() + 1500); + await page.waitForFunction(() => !document.querySelector('#reason')?.textContent.startsWith('Approve unlocks')); return page; } +// Grow the window until the content no longer scrolls. +async function fit(page) { + const extra = await page.evaluate(() => { + const content = document.getElementById('content'); + return content.scrollHeight - content.clientHeight; + }); + if (extra > 0) await page.setViewportSize({ width: 660, height: 760 + extra }); +} +const window_ = async page => { + await fit(page); + return { x: 0, y: 0, ...page.viewportSize() }; +}; + // `api` answers the demo backend's /api routes; see examples/demo-integrator/integrator.js. async function portal(browser, colorScheme, api) { const page = await newPage(browser, { viewport: { width: 960, height: 1400 }, colorScheme }); @@ -180,56 +232,95 @@ const content = async (page, margin = 12) => { }; // ------------------------------------------------------------------- shots +// Each Companion shot runs once per color scheme. const companionShots = { - async 'approval-unselected'(browser) { - const page = await companion(browser, snapshot({ offers: [offer()] })); - await page.locator('#requests article').waitFor(); - await capture(page, 'approval-unselected.png', { clip: around('#requests article', 0), selectors: { - identities: '#requests label.identity', approve: '#requests button.approve', - actions: '#requests .actions button', + async 'approval-unselected'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ offers: [offer(), lanternOffer()], pairings })); + await capture(page, name, { clip: window_, selectors: { + identities: '#requests .certs', actions: '.actions .decision', queue: '#requests .queue', } }); }, - async 'approval-selected'(browser) { - const page = await companion(browser, snapshot({ offers: [offer()] })); - await page.locator('#requests label.identity').nth(1).locator('input').check(); - await capture(page, 'approval-selected.png', { clip: around('#requests article', 0), selectors: { - selected: '#requests label.identity:has(input:checked)', - expiry: { selector: '#requests article > p:has-text("Expires by")', text: true }, - branding: '#requests .brand', + async 'approval-selected'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ offers: [offer()], pairings })); + await page.locator('#requests .identity').nth(1).locator('input').check(); + await capture(page, name, { clip: window_, selectors: { + selected: '#requests .identity:has(input:checked)', expiry: '#requests .expires', + header: '#brand-integrator', plate: '.plate', + facts: '#requests .verified', presets: '#requests .seg', } }); }, - async 'scope-wildcard'(browser) { - const page = await companion(browser, snapshot({ offers: [offer({ + async 'scope-wildcard'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ pairings, offers: [offer({ host: 'reports.team.example:9444', scope: '*.team.example:9444', identities: [certificate('selected', fingerprints.selected)], })] })); - await page.locator('#requests article').waitFor(); - await capture(page, 'scope-wildcard.png', { clip: around('#requests article', 0), selectors: { - scope: { selector: '#requests dl > :is(dt, dd):nth-child(n+7)', text: true }, + await capture(page, name, { clip: window_, selectors: { + scope: '#requests .fact:nth-child(n+4)', warning: '#requests .verified .alert', } }); }, - async 'branding-alternate'(browser) { - const page = await companion(browser, snapshot({ offers: [offer({ - origin: 'https://audit.example', user: 'analyst-7', context: 'fy26-fieldwork', theme: lantern, - host: 'evidence.audit.example:443', scope: 'evidence.audit.example:443', + async 'branding-alternate'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ pairings, offers: [lanternOffer()] })); + await capture(page, name, { clip: window_, selectors: { + header: '#brand-integrator', approve: '.actions .primary', + } }); + }, + async 'branding-none'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ pairings, offers: [offer({ + pairing: 'jobs', origin: JOBS, theme: null, context: 'nightly-export', identities: [certificate('selected', fingerprints.selected)], })] })); - await page.locator('#requests article').waitFor(); - await capture(page, 'branding-alternate.png', { clip: around('#requests article', 0), selectors: { - branding: '#requests .brand', + await capture(page, name, { clip: window_, selectors: { + brand: '#brand-countersign', note: { selector: '#requests .nobrand', text: true }, + } }); + }, + async 'queue-switch'(browser, scheme, name) { + const first = snapshot({ pairings, offers: [offer(), lanternOffer()] }); + const page = await companion(browser, scheme, first); + // The Harbor Ledger request is decided elsewhere; Lantern Audit's moves up. + await page.evaluate(next => window.update(next), { ...first, offers: [lanternOffer()] }); + await page.locator('.switch-banner').waitFor(); + await capture(page, name, { clip: window_, selectors: { + banner: '.switch-banner', approve: '.actions .primary', reason: { selector: '#reason', text: true }, } }); }, - async 'pairing-companion'(browser) { - const page = await companion(browser, snapshot({ - pending: PORTAL + ' · Pairing code 7B9DF613D8', - confirmation: { id: 'confirmation-1', origin: PORTAL, user: job.user, code: 'Pairing code 7B9DF613D8' }, + async 'pairing-companion'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ + pending: [{ id: 'harbor', origin: PORTAL, status: 'Pairing code 7B9DF613D8', code: '7B9DF613D8', theme: harbor }], + confirmation: { id: 'confirmation-1', pairing: 'harbor', origin: PORTAL, user: job.user, code: '7B9DF613D8', theme: harbor }, })); - await page.locator('#origin').fill(PORTAL); await page.getByRole('button', { name: 'Cancel pairing' }).waitFor(); - await capture(page, 'pairing-companion.png', { clip: down('#enrollment'), selectors: { - confirmation: { selector: '#pending > p', text: true }, + await capture(page, name, { clip: window_, selectors: { + facts: '#pairing .verified', code: '#pairing .code-box', + } }); + }, + async 'integrators-list'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ pairings })); + await page.getByRole('button', { name: 'Integrators' }).click(); + await capture(page, name, { clip: window_, selectors: { rows: '#pairs', pair: '#pair' } }); + }, + async 'integrator-detail'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ pairings })); + await page.getByRole('button', { name: 'Integrators' }).click(); + await page.locator('#pairs .int-row').first().click(); + await capture(page, name, { clip: window_, selectors: { + notice: '#detail .alert', approvals: '#detail .row:has(.mono:text-is("' + job.host + '"))', + self: '#detail .tag', } }); }, + async 'branding-review'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ pairings })); + await page.getByRole('button', { name: 'Integrators' }).click(); + await page.locator('#pairs .int-row').nth(1).click(); + await capture(page, name, { clip: window_, selectors: { review: '#detail .review', buttons: '#detail .review + p + .btnrow button' } }); + }, + async 'dialog-remove'(browser, scheme, name) { + const page = await companion(browser, scheme, snapshot({ pairings })); + await page.getByRole('button', { name: 'Integrators' }).click(); + await page.locator('#pairs .int-row').nth(2).click(); + await page.getByRole('button', { name: 'Remove from this computer' }).click(); + await page.locator('dialog[open]').waitFor(); + await capture(page, name, { clip: window_, selectors: { dialog: 'dialog[open]' } }); + }, }; // Each demo shot runs once per color scheme. @@ -289,10 +380,7 @@ const sidecarFile = new URL('boxes.json', RAW); Object.assign(sidecar, only ? JSON.parse(await readFile(sidecarFile, 'utf8').catch(() => '{}')) : {}); const browser = await chromium.launch(args.browser ? { executablePath: args.browser } : {}); try { - for (const [name, shot] of Object.entries(companionShots)) { - if (!only || only.has(name)) await shot(browser); - } - for (const [name, shot] of Object.entries(portalShots)) { + for (const [name, shot] of [...Object.entries(companionShots), ...Object.entries(portalShots)]) { if (only && !only.has(name)) continue; await shot(browser, 'light', name + '.png'); await shot(browser, 'dark', name + '-dark.png');