Compare commits
20 Commits
v0.2.0
...
5d1e8f2309
| Author | SHA1 | Date | |
|---|---|---|---|
| 5d1e8f2309 | |||
| bf146c07e7 | |||
| a17ed96b54 | |||
| c7e6d66750 | |||
| 8da75b4ca7 | |||
| 4ad8653a06 | |||
| cfcb7a7dc2 | |||
| 814005d267 | |||
| d7bc7fbd36 | |||
| 7bde22713f | |||
| 566c286f87 | |||
| 0ad4c6b09c | |||
| ebc1398906 | |||
| cf48b3014c | |||
| 43bb004ae7 | |||
| f4693af3df | |||
| c702a347dc | |||
| fb480973b7 | |||
| 26ba278eb3 | |||
| 952af3f107 |
@@ -19,4 +19,4 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
docker run --rm -v "$PWD:/repo" -w /repo \
|
docker run --rm -v "$PWD:/repo" -w /repo \
|
||||||
-e REGISTRY_TOKEN -e REGISTRY_USER -e REPO_TOKEN -e REPOSITORY -e SERVER_URL \
|
-e REGISTRY_TOKEN -e REGISTRY_USER -e REPO_TOKEN -e REPOSITORY -e SERVER_URL \
|
||||||
node:24.19.0-alpine3.24 node registry-cleanup/cleanup.ts
|
node:24.20.0-alpine3.24 node registry-cleanup/cleanup.ts
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ jobs:
|
|||||||
GIT_TAG: ${{ github.ref_name }}
|
GIT_TAG: ${{ github.ref_name }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
docker run --rm -v "$PWD:/repo" -w /repo node:24.19.0-alpine3.24 \
|
docker run --rm -v "$PWD:/repo" -w /repo node:24.20.0-alpine3.24 \
|
||||||
node release-tooling/contract-version.ts "$GIT_TAG" src/plugin-host/plugin.ts
|
node release-tooling/contract-version.ts "$GIT_TAG" src/plugin-host/plugin.ts
|
||||||
- name: Promote the commit-hash image to semver + latest
|
- name: Promote the commit-hash image to semver + latest
|
||||||
env:
|
env:
|
||||||
@@ -98,9 +98,9 @@ jobs:
|
|||||||
VERSION=${INPUT_VERSION:-${GIT_TAG#v}}
|
VERSION=${INPUT_VERSION:-${GIT_TAG#v}}
|
||||||
VERSION=${VERSION#v}
|
VERSION=${VERSION#v}
|
||||||
# An empty dispatch input falls back to the branch name, so gate this like a tag.
|
# An empty dispatch input falls back to the branch name, so gate this like a tag.
|
||||||
docker run --rm -v "$PWD:/repo" -w /repo node:24.19.0-alpine3.24 \
|
docker run --rm -v "$PWD:/repo" -w /repo node:24.20.0-alpine3.24 \
|
||||||
node release-tooling/contract-version.ts "$VERSION" src/plugin-host/plugin.ts
|
node release-tooling/contract-version.ts "$VERSION" src/plugin-host/plugin.ts
|
||||||
docker run --rm -v "$PWD:/repo" -w /repo \
|
docker run --rm -v "$PWD:/repo" -w /repo \
|
||||||
-e DOCKERHUB_REPO -e DOCKERHUB_TOKEN -e DOCKERHUB_USER \
|
-e DOCKERHUB_REPO -e DOCKERHUB_TOKEN -e DOCKERHUB_USER \
|
||||||
node:24.19.0-alpine3.24 \
|
node:24.20.0-alpine3.24 \
|
||||||
node release-tooling/dockerhub-overview.ts "$VERSION"
|
node release-tooling/dockerhub-overview.ts "$VERSION"
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ jobs:
|
|||||||
-e RENOVATE_PLATFORM=gitea \
|
-e RENOVATE_PLATFORM=gitea \
|
||||||
-e RENOVATE_REPOSITORIES=${{ github.repository }} \
|
-e RENOVATE_REPOSITORIES=${{ github.repository }} \
|
||||||
-e RENOVATE_TOKEN \
|
-e RENOVATE_TOKEN \
|
||||||
renovate/renovate:44.39.2
|
renovate/renovate:44.53.0
|
||||||
|
|
||||||
# After the renovate job, cut ONE tag covering the renovate-bot commits merged to main since the
|
# After the renovate job, cut ONE tag covering the renovate-bot commits merged to main since the
|
||||||
# last tag (batch per run). Targets origin/main — the real post-merge tip; the checkout SHA is the
|
# last tag (batch per run). Targets origin/main — the real post-merge tip; the checkout SHA is the
|
||||||
@@ -58,11 +58,11 @@ jobs:
|
|||||||
if [ -z "$BUMPS" ]; then
|
if [ -z "$BUMPS" ]; then
|
||||||
echo "Renovate commits since ${LATEST}, but none carry Release-Bump — nothing reached a running Plainpages; skipping"; exit 0
|
echo "Renovate commits since ${LATEST}, but none carry Release-Bump — nothing reached a running Plainpages; skipping"; exit 0
|
||||||
fi
|
fi
|
||||||
NEXT=$(docker run --rm -v "$PWD:/repo" -w /repo node:24.19.0-alpine3.24 \
|
NEXT=$(docker run --rm -v "$PWD:/repo" -w /repo node:24.20.0-alpine3.24 \
|
||||||
node release-tooling/next-version.ts "$LATEST" $BUMPS)
|
node release-tooling/next-version.ts "$LATEST" $BUMPS)
|
||||||
# Read the constant off origin/main, not the checkout, which lags the merges this run made.
|
# Read the constant off origin/main, not the checkout, which lags the merges this run made.
|
||||||
git show origin/main:src/plugin-host/plugin.ts \
|
git show origin/main:src/plugin-host/plugin.ts \
|
||||||
| docker run -i --rm -v "$PWD:/repo" -w /repo node:24.19.0-alpine3.24 \
|
| docker run -i --rm -v "$PWD:/repo" -w /repo node:24.20.0-alpine3.24 \
|
||||||
node release-tooling/contract-version.ts "$NEXT" -
|
node release-tooling/contract-version.ts "$NEXT" -
|
||||||
echo "Releasing $LATEST -> $NEXT"
|
echo "Releasing $LATEST -> $NEXT"
|
||||||
git tag "$NEXT" origin/main
|
git tag "$NEXT" origin/main
|
||||||
|
|||||||
@@ -182,6 +182,15 @@ Revisit only if the stated reason stops holding.
|
|||||||
example it keeps the route table and the in-handler guard deriving from one function, so 29 routes
|
example it keeps the route table and the in-handler guard deriving from one function, so 29 routes
|
||||||
× 2 gate sites cannot drift. Generalised, it would make authorization a function of the transport
|
× 2 gate sites cannot drift. Generalised, it would make authorization a function of the transport
|
||||||
verb — a route table must answer "what does this need?" on its own.
|
verb — a route table must answer "what does this need?" on its own.
|
||||||
|
- **A gate is one of three, and `session` is a first-class one.** A route or nav node names exactly
|
||||||
|
one of `public`, `session`, `permission` (discovery refuses two), and `src/auth/gate.ts` is the one
|
||||||
|
home of the rule the router and the menu both read. `session` exists because a plugin whose data is
|
||||||
|
the visitor's own — their upstream account, their own tokens — has no distinction a permission could
|
||||||
|
name; the alternative, granting every newly registered user a permission, couples the identity
|
||||||
|
lifecycle to a Keto write that nothing retries when it fails.
|
||||||
|
- **The reference plugin's two shift pages duplicate a view model and markup on purpose.** An example
|
||||||
|
is read far more often than it is changed, and each page reads top to bottom on its own. **Valid
|
||||||
|
while `examples/plugins/scheduling` stays a teaching artifact rather than a maintained product.**
|
||||||
- **A `:read`-only holder must never be shown a write affordance.** The list/detail models carry
|
- **A `:read`-only holder must never be shown a write affordance.** The list/detail models carry
|
||||||
`canWrite` and the views drop create/save/delete/add/remove; the permission picker still renders,
|
`canWrite` and the views drop create/save/delete/add/remove; the permission picker still renders,
|
||||||
disabled, because *seeing* who holds what is the point of `:read`. A **write-intent GET** (a create
|
disabled, because *seeing* who holds what is the point of `:read`. A **write-intent GET** (a create
|
||||||
@@ -254,8 +263,11 @@ Revisit only if the stated reason stops holding.
|
|||||||
open-state style and the old-browser fallback both read; the partial **requires a caller-named
|
open-state style and the old-browser fallback both read; the partial **requires a caller-named
|
||||||
`id`** and fails loud without one, since that is the `popovertarget` idref (never generate one —
|
`id`** and fails loud without one, since that is the `popovertarget` idref (never generate one —
|
||||||
nondeterministic HTML forecloses the caching decision); and **neither `aria-expanded` nor
|
nondeterministic HTML forecloses the caching decision); and **neither `aria-expanded` nor
|
||||||
`aria-haspopup` is written**, because a zero-JS invoker cannot keep the first truthful and the
|
`aria-haspopup` is written**: every engine maintains the first itself on a declarative
|
||||||
second would promise `role="menu"` semantics these panels don't implement. `<details>` stays where
|
`popovertarget` invoker, so a hand-written one replaces a live state with a static lie, and the
|
||||||
|
second would promise `role="menu"` semantics these panels don't implement. **That guarantee is the
|
||||||
|
declarative attribute's alone** — open a panel from script and no engine applies it, so
|
||||||
|
"enhancing" one of these triggers is what would cost it its accessibility. `<details>` stays where
|
||||||
it means disclosure rather than popup: the nav tree. `shell.ejs` hand-rolls the same block for the
|
it means disclosure rather than popup: the nav tree. `shell.ejs` hand-rolls the same block for the
|
||||||
profile menu (its trigger composes escaped user values and its one item is a CSRF POST form) — keep
|
profile menu (its trigger composes escaped user values and its one item is a CSRF POST form) — keep
|
||||||
the two in step.
|
the two in step.
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
# Node 24 runs TypeScript directly (type stripping) — no build step. Pinned exact tag.
|
# Node 24 runs TypeScript directly (type stripping) — no build step. Pinned exact tag.
|
||||||
FROM node:24.19.0-alpine3.24
|
FROM node:24.20.0-alpine3.24
|
||||||
|
|
||||||
# Above WORKDIR so dev's `.:/app` bind mount can't shadow them; a volume at /app/node_modules
|
# Above WORKDIR so dev's `.:/app` bind mount can't shadow them; a volume at /app/node_modules
|
||||||
# instead leaves a root-owned dir in the checkout (the daemon creates mount destinations as root).
|
# instead leaves a root-owned dir in the checkout (the daemon creates mount destinations as root).
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ folder under `plugins/` goes live after a restart. Create `plugins/hello/plugin.
|
|||||||
import { definePlugin } from "@plainpages/plugin-api";
|
import { definePlugin } from "@plainpages/plugin-api";
|
||||||
|
|
||||||
export default definePlugin({
|
export default definePlugin({
|
||||||
apiVersion: "0.2.0",
|
apiVersion: "0.4.0",
|
||||||
nav: [{ href: "/hello", id: "hello", label: "Hello", public: true }],
|
nav: [{ href: "/hello", id: "hello", label: "Hello", public: true }],
|
||||||
routes: [
|
routes: [
|
||||||
{ method: "GET", path: "/", public: true, handler: () => ({ html: "<h1>Hello from my plugin</h1>" }) },
|
{ method: "GET", path: "/", public: true, handler: () => ({ html: "<h1>Hello from my plugin</h1>" }) },
|
||||||
@@ -231,6 +231,7 @@ Against the reference plugins' actual routes:
|
|||||||
| Request | Gate | alice | bob | carol | anonymous |
|
| Request | Gate | alice | bob | carol | anonymous |
|
||||||
| --- | --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- | --- |
|
||||||
| `GET /scheduling` | `public: true` | ✅ | ✅ | ✅ | ✅ |
|
| `GET /scheduling` | `public: true` | ✅ | ✅ | ✅ | ✅ |
|
||||||
|
| `GET /scheduling/mine` | `session: true` | ✅ | ✅ | ✅ | → `/login` |
|
||||||
| `GET /scheduling/shifts` | `scheduling:read` | ✅ | ✅ | 403 | → `/login` |
|
| `GET /scheduling/shifts` | `scheduling:read` | ✅ | ✅ | 403 | → `/login` |
|
||||||
| `GET /scheduling/shifts/new` | `scheduling:write` | ✅ | 403 | 403 | → `/login` |
|
| `GET /scheduling/shifts/new` | `scheduling:write` | ✅ | 403 | 403 | → `/login` |
|
||||||
| `POST /scheduling/shifts` | `scheduling:write` | ✅ | 403 | 403 | → `/login` |
|
| `POST /scheduling/shifts` | `scheduling:write` | ✅ | 403 | 403 | → `/login` |
|
||||||
@@ -349,7 +350,7 @@ import { definePlugin } from "@plainpages/plugin-api";
|
|||||||
import { listThings, createThings } from "./handlers.ts";
|
import { listThings, createThings } from "./handlers.ts";
|
||||||
|
|
||||||
export default definePlugin({
|
export default definePlugin({
|
||||||
apiVersion: "0.2.0", // semver string of the host contract this plugin was built against (see Versioning)
|
apiVersion: "0.4.0", // semver string of the host contract this plugin was built against (see Versioning)
|
||||||
|
|
||||||
// Nav fragment, merged into the global menu and permission-filtered per user.
|
// Nav fragment, merged into the global menu and permission-filtered per user.
|
||||||
// `icon` is a Lucide icon by its sprite id (src/ui/icons.ts).
|
// `icon` is a Lucide icon by its sprite id (src/ui/icons.ts).
|
||||||
@@ -389,13 +390,14 @@ A plugin may be routes-only, nav-only, or hooks-only — every collection field
|
|||||||
|
|
||||||
### Routes & handlers
|
### Routes & handlers
|
||||||
|
|
||||||
A route is `{ method, path, permission?, public?, handler }`. `path` is **relative to the plugin's
|
A route is `{ method, path, permission?, public?, session?, handler }`. `path` is **relative to the plugin's
|
||||||
mount path `/<id>`** (so `path: "/:id"` in the `things` plugin serves `/things/:id`); the host matches
|
mount path `/<id>`** (so `path: "/:id"` in the `things` plugin serves `/things/:id`); the host matches
|
||||||
`method` + the resolved full path, extracts `:name` segments into `ctx.params.name`, runs the
|
`method` + the resolved full path, extracts `:name` segments into `ctx.params.name`, runs the
|
||||||
`permission` gate ([a coarse JWT-claim check](#nav--permission-gates)), then calls the handler with
|
`permission` gate ([a coarse JWT-claim check](#nav--permission-gates)), then calls the handler with
|
||||||
the [request context](#requestcontext). A failed gate redirects an **anonymous** visitor to `/login`
|
the [request context](#requestcontext). A failed gate redirects an **anonymous** visitor to `/login`
|
||||||
with the page as `return_to`; a **signed-in** user lacking the permission gets the **403** page.
|
with the page as `return_to`; a **signed-in** user lacking the permission gets the **403** page.
|
||||||
`public: true` means no gate at all (see [Public pages](#public-pages--menu-items)).
|
`public: true` means no gate at all, `session: true` any signed-in user (see
|
||||||
|
[Public pages](#public-pages--menu-items)).
|
||||||
|
|
||||||
`method` is one of `GET HEAD POST PUT PATCH DELETE`. A `GET` route also answers `HEAD`.
|
`method` is one of `GET HEAD POST PUT PATCH DELETE`. A `GET` route also answers `HEAD`.
|
||||||
|
|
||||||
@@ -470,7 +472,7 @@ import { definePlugin } from "@plainpages/plugin-api";
|
|||||||
import { landing, board } from "./pages.ts";
|
import { landing, board } from "./pages.ts";
|
||||||
|
|
||||||
export default definePlugin({
|
export default definePlugin({
|
||||||
apiVersion: "0.2.0",
|
apiVersion: "0.4.0",
|
||||||
home: landing, // owns "/" — the public front page
|
home: landing, // owns "/" — the public front page
|
||||||
dashboard: board, // owns "/dashboard" — the post-login app home
|
dashboard: board, // owns "/dashboard" — the post-login app home
|
||||||
});
|
});
|
||||||
@@ -569,8 +571,8 @@ system plugins you author or vendor. An ordinary domain plugin ignores it.
|
|||||||
|
|
||||||
A plugin's `nav` fragment is merged into the global menu by `composeNav` (`src/ui/nav.ts`), which
|
A plugin's `nav` fragment is merged into the global menu by `composeNav` (`src/ui/nav.ts`), which
|
||||||
applies the central override and then **filters per user** by the permissions in the session JWT: a
|
applies the central override and then **filters per user** by the permissions in the session JWT: a
|
||||||
node shows iff it is `public`, declares no `permission`, or the user holds that name. A node's `icon`
|
node shows iff it is `public`, is `session` and someone is signed in, declares no `permission`, or
|
||||||
is a **Lucide icon** by sprite id (e.g. `i-cal` → lucide `calendar`); the available ids are
|
the user holds that name. A node's `icon` is a **Lucide icon** by sprite id (e.g. `i-cal` → lucide `calendar`); the available ids are
|
||||||
`ICON_NAMES` in `src/ui/icons.ts`, and adding one means registering its lucide name there.
|
`ICON_NAMES` in `src/ui/icons.ts`, and adding one means registering its lucide name there.
|
||||||
|
|
||||||
**Gating a section header.** A `permission` on the header takes the whole subtree with it. When the
|
**Gating a section header.** A `permission` on the header takes the whole subtree with it. When the
|
||||||
@@ -582,7 +584,14 @@ drops a header whose children all filtered out. That only works while the header
|
|||||||
|
|
||||||
A route or nav node marked **`public: true`** is reachable by anyone and shows in everyone's menu.
|
A route or nav node marked **`public: true`** is reachable by anyone and shows in everyone's menu.
|
||||||
That is the same as omitting `permission`, but stated outright so public is a deliberate choice
|
That is the same as omitting `permission`, but stated outright so public is a deliberate choice
|
||||||
rather than a forgotten gate. The two are **mutually exclusive** — declaring both is refused at boot.
|
rather than a forgotten gate.
|
||||||
|
|
||||||
|
**`session: true`** takes any signed-in user, with no grant to hold — for a plugin whose data is the
|
||||||
|
visitor's own. An anonymous visitor is bounced to `/login` with the page as `return_to`, exactly as a
|
||||||
|
permission gate does.
|
||||||
|
|
||||||
|
A declaration names **exactly one** of the three; two of them contradict, and discovery refuses the
|
||||||
|
plugin at boot.
|
||||||
|
|
||||||
A public page still renders in the native shell; for an anonymous visitor `ctx.user` is `null`, the
|
A public page still renders in the native shell; for an anonymous visitor `ctx.user` is `null`, the
|
||||||
shell shows a **Sign in** link in place of the profile block, the gated **Dashboard** link is hidden,
|
shell shows a **Sign in** link in place of the profile block, the gated **Dashboard** link is hidden,
|
||||||
@@ -635,7 +644,7 @@ The host detects collisions across all discovered plugins with `findConflicts` a
|
|||||||
Mount-path uniqueness needs no rule of its own — it follows from the id check. Discovery also
|
Mount-path uniqueness needs no rule of its own — it follows from the id check. Discovery also
|
||||||
rejects **per-manifest shape errors**: a non-array `nav`/`routes`/`permissions`, a non-function
|
rejects **per-manifest shape errors**: a non-array `nav`/`routes`/`permissions`, a non-function
|
||||||
`home`/`dashboard`, a permission name that isn't [`<resource>:<action>`](#naming-a-permission), or a
|
`home`/`dashboard`, a permission name that isn't [`<resource>:<action>`](#naming-a-permission), or a
|
||||||
route/nav node setting both `public` and `permission`.
|
route/nav node naming more than one gate.
|
||||||
|
|
||||||
### Hooks
|
### Hooks
|
||||||
|
|
||||||
@@ -747,7 +756,7 @@ camel humps both becoming underscores — so `upstream` on the `scheduling` plug
|
|||||||
|
|
||||||
```ts
|
```ts
|
||||||
export default definePlugin({
|
export default definePlugin({
|
||||||
apiVersion: "0.2.0",
|
apiVersion: "0.4.0",
|
||||||
settings: [
|
settings: [
|
||||||
{ key: "upstream", type: "url", required: true, description: "Base URL of the backend" },
|
{ key: "upstream", type: "url", required: true, description: "Base URL of the backend" },
|
||||||
{ key: "pageSize", type: "number", default: 25 },
|
{ key: "pageSize", type: "number", default: 25 },
|
||||||
@@ -801,7 +810,7 @@ import { definePlugin } from "@plainpages/plugin-api";
|
|||||||
let sql: ReturnType<typeof postgres>;
|
let sql: ReturnType<typeof postgres>;
|
||||||
|
|
||||||
export default definePlugin({
|
export default definePlugin({
|
||||||
apiVersion: "0.2.0",
|
apiVersion: "0.4.0",
|
||||||
storage: true,
|
storage: true,
|
||||||
hooks: {
|
hooks: {
|
||||||
onBoot: async (boot) => {
|
onBoot: async (boot) => {
|
||||||
@@ -913,7 +922,8 @@ The menu is **driven entirely by config** and assembled from two sources:
|
|||||||
|
|
||||||
Every nav item may carry a `permission`; the rendered tree is **filtered per user** from the session
|
Every nav item may carry a `permission`; the rendered tree is **filtered per user** from the session
|
||||||
JWT (no per-request authz call), so the menu only shows what that person can reach. An item may
|
JWT (no per-request authz call), so the menu only shows what that person can reach. An item may
|
||||||
instead be **`public: true`** to show it to everyone — mutually exclusive with `permission`.
|
instead be **`public: true`** (everyone) or **`session: true`** (anyone signed in) — one gate per
|
||||||
|
item, never two.
|
||||||
Branding (name, logo, default theme) renders in the app shell.
|
Branding (name, logo, default theme) renders in the app shell.
|
||||||
|
|
||||||
**One menu, one shell, everywhere.** A single menu (`src/ui/chrome.ts` `buildPluginChrome`) renders
|
**One menu, one shell, everywhere.** A single menu (`src/ui/chrome.ts` `buildPluginChrome`) renders
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ services:
|
|||||||
# backs it (PLUGIN_SETTING_SCHEDULING_UPSTREAM above points here). Stand-in for the customer's real service —
|
# backs it (PLUGIN_SETTING_SCHEDULING_UPSTREAM above points here). Stand-in for the customer's real service —
|
||||||
# stdlib-only, in-memory, no auth. Prod points PLUGIN_SETTING_SCHEDULING_UPSTREAM at the real backend instead.
|
# stdlib-only, in-memory, no auth. Prod points PLUGIN_SETTING_SCHEDULING_UPSTREAM at the real backend instead.
|
||||||
shifts-upstream:
|
shifts-upstream:
|
||||||
image: node:24.19.0-alpine3.24
|
image: node:24.20.0-alpine3.24
|
||||||
command: node /srv/server.ts
|
command: node /srv/server.ts
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ services:
|
|||||||
|
|
||||||
# The reference plugin's upstream (examples/shifts-upstream) so /scheduling/shifts shows real rows.
|
# The reference plugin's upstream (examples/shifts-upstream) so /scheduling/shifts shows real rows.
|
||||||
shifts-upstream:
|
shifts-upstream:
|
||||||
image: node:24.19.0-alpine3.24
|
image: node:24.20.0-alpine3.24
|
||||||
command: ["node", "/server.ts"]
|
command: ["node", "/server.ts"]
|
||||||
volumes:
|
volumes:
|
||||||
- ./examples/shifts-upstream/server.ts:/server.ts:ro
|
- ./examples/shifts-upstream/server.ts:/server.ts:ro
|
||||||
@@ -66,7 +66,7 @@ services:
|
|||||||
# Mock OIDC provider for the SSO login test — stdlib Node, auto-approves, signs an id_token Kratos
|
# Mock OIDC provider for the SSO login test — stdlib Node, auto-approves, signs an id_token Kratos
|
||||||
# verifies via its jwks. Reachable as the same host (mock-oidc:9000) by both the browser and Kratos.
|
# verifies via its jwks. Reachable as the same host (mock-oidc:9000) by both the browser and Kratos.
|
||||||
mock-oidc:
|
mock-oidc:
|
||||||
image: node:24.19.0-alpine3.24
|
image: node:24.20.0-alpine3.24
|
||||||
command: ["node", "/mock-oidc.ts"]
|
command: ["node", "/mock-oidc.ts"]
|
||||||
environment:
|
environment:
|
||||||
ISSUER: http://mock-oidc:9000
|
ISSUER: http://mock-oidc:9000
|
||||||
@@ -81,7 +81,7 @@ services:
|
|||||||
|
|
||||||
# Same-origin gateway: Kratos-owned paths → kratos, everything else → web (e2e-tests/proxy.ts).
|
# Same-origin gateway: Kratos-owned paths → kratos, everything else → web (e2e-tests/proxy.ts).
|
||||||
proxy:
|
proxy:
|
||||||
image: node:24.19.0-alpine3.24
|
image: node:24.20.0-alpine3.24
|
||||||
command: ["node", "/proxy.ts"]
|
command: ["node", "/proxy.ts"]
|
||||||
depends_on:
|
depends_on:
|
||||||
web:
|
web:
|
||||||
|
|||||||
@@ -193,6 +193,13 @@ test.describe.serial("authenticated admin journey", () => {
|
|||||||
await page.goto("/scheduling/shifts");
|
await page.goto("/scheduling/shifts");
|
||||||
await expect(page.locator("h1")).toHaveText("Shifts");
|
await expect(page.locator("h1")).toHaveText("Shifts");
|
||||||
await expect(page.locator("table")).toContainText("Morning — Front desk"); // seeded by the mock upstream
|
await expect(page.locator("table")).toContainText("Morning — Front desk"); // seeded by the mock upstream
|
||||||
|
|
||||||
|
// The session-gated page asks the upstream for this visitor's rows: the one seeded against the
|
||||||
|
// signed-in admin is there, and another person's shift is not.
|
||||||
|
await page.goto("/scheduling/mine");
|
||||||
|
await expect(page.locator("h1")).toHaveText("My shifts");
|
||||||
|
await expect(page.locator("table")).toContainText("Night — Escalations");
|
||||||
|
await expect(page.locator("table")).not.toContainText("Morning — Front desk");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("plugin settings: the screen names the variable that sets each declared key", async () => {
|
test("plugin settings: the screen names the variable that sets each declared key", async () => {
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ test("a popover menu sits on its trigger and closes on an outside click or Esc
|
|||||||
await expect(panel).toBeVisible();
|
await expect(panel).toBeVisible();
|
||||||
await page.keyboard.press("Escape");
|
await page.keyboard.press("Escape");
|
||||||
await expect(panel).toBeHidden();
|
await expect(panel).toBeHidden();
|
||||||
|
await expect(trigger).toBeFocused(); // the browser returns focus, so no trigger needs a tabindex
|
||||||
});
|
});
|
||||||
|
|
||||||
test("mobile layout hides the sidebar off-canvas behind the hamburger", async ({ page }) => {
|
test("mobile layout hides the sidebar off-canvas behind the hamburger", async ({ page }) => {
|
||||||
@@ -142,11 +143,11 @@ test("unknown routes serve the 404 page (a real user-facing flow, covered end-to
|
|||||||
await expect(page.getByRole("link", { name: "Back home" })).toBeVisible();
|
await expect(page.getByRole("link", { name: "Back home" })).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
// The reference plugin (plugins/scheduling) ships discovered in the image. Its public Overview is
|
// The reference plugin (plugins/scheduling) ships discovered in the image, and shows all three
|
||||||
// reachable by anyone and its menu header shows for everyone; the shifts list stays permission-gated,
|
// gates: the public Overview is reachable by anyone, My shifts takes any session, and the shifts
|
||||||
// so an anonymous visitor is bounced to sign in. The authenticated list/form flow is the full
|
// list needs a permission. The authenticated list/form flow is the full E2E (full-flow.spec).
|
||||||
// E2E (full-flow.spec). Side-effect-free.
|
// Side-effect-free.
|
||||||
test("the reference plugin: public Overview is open to all, the gated Shifts redirects to /login", async ({ page, request }) => {
|
test("the reference plugin: public Overview is open to all, My shifts takes any session, the gated Shifts redirects to /login", async ({ page, request }) => {
|
||||||
// `request` is the isolated API context — it doesn't carry the beforeEach session cookie, so these
|
// `request` is the isolated API context — it doesn't carry the beforeEach session cookie, so these
|
||||||
// probes are genuinely anonymous.
|
// probes are genuinely anonymous.
|
||||||
// The public overview is reachable with no session (200), not bounced to sign in.
|
// The public overview is reachable with no session (200), not bounced to sign in.
|
||||||
@@ -165,10 +166,24 @@ test("the reference plugin: public Overview is open to all, the gated Shifts red
|
|||||||
expect(res.status()).toBe(303);
|
expect(res.status()).toBe(303);
|
||||||
expect(res.headers()["location"]).toBe("/login?return_to=%2Fscheduling%2Fshifts");
|
expect(res.headers()["location"]).toBe("/login?return_to=%2Fscheduling%2Fshifts");
|
||||||
|
|
||||||
|
// A `session: true` route bounces an anonymous visitor the same way — no permission involved.
|
||||||
|
const mine = await request.get("/scheduling/mine", { maxRedirects: 0 });
|
||||||
|
expect(mine.status()).toBe(303);
|
||||||
|
expect(mine.headers()["location"]).toBe("/login?return_to=%2Fscheduling%2Fmine");
|
||||||
|
|
||||||
// The signed-in member (no scheduling permission) sees the public Scheduling → Overview leaf in the nav,
|
// The signed-in member (no scheduling permission) sees the public Scheduling → Overview leaf in the nav,
|
||||||
// but the gated Shifts leaf is filtered out.
|
// but the gated Shifts leaf is filtered out.
|
||||||
await page.goto("/dashboard");
|
await page.goto("/dashboard");
|
||||||
await expect(page.locator('.sidebar a[href="/dashboard"]')).toHaveCount(1); // the one unified menu renders
|
await expect(page.locator('.sidebar a[href="/dashboard"]')).toHaveCount(1); // the one unified menu renders
|
||||||
await expect(page.locator('.sidebar a[href="/scheduling"]')).toHaveCount(1); // public Overview shown
|
await expect(page.locator('.sidebar a[href="/scheduling"]')).toHaveCount(1); // public Overview shown
|
||||||
await expect(page.locator('.sidebar a[href="/scheduling/shifts"]')).toHaveCount(0); // gated leaf filtered out
|
await expect(page.locator('.sidebar a[href="/scheduling/shifts"]')).toHaveCount(0); // gated leaf filtered out
|
||||||
|
await expect(page.locator('.sidebar a[href="/scheduling/mine"]')).toHaveCount(1); // session gate: a session is enough
|
||||||
|
|
||||||
|
// And the page itself renders for that same member, holding no permission at all. This stack runs
|
||||||
|
// no shifts upstream, so it also pins the degraded page: the reason, never a 500 and never a claim
|
||||||
|
// about what is assigned. The working page is asserted against a real upstream in full-flow.spec.
|
||||||
|
await page.goto("/scheduling/mine");
|
||||||
|
await expect(page.getByRole("heading", { name: "My shifts" })).toBeVisible();
|
||||||
|
await expect(page.getByText("Couldn't reach the scheduling service")).toBeVisible();
|
||||||
|
await expect(page.getByText("No shifts are assigned to")).toHaveCount(0);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ const clients = on("oauth2-clients");
|
|||||||
const pluginSettings = on("plugin-settings");
|
const pluginSettings = on("plugin-settings");
|
||||||
|
|
||||||
export default definePlugin({
|
export default definePlugin({
|
||||||
apiVersion: "0.2.0", // the host contract this was built against — a literal, never HOST_API_VERSION
|
apiVersion: "0.4.0", // the host contract this was built against — a literal, never HOST_API_VERSION
|
||||||
|
|
||||||
nav: [ADMIN_NAV],
|
nav: [ADMIN_NAV],
|
||||||
|
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ What it demonstrates:
|
|||||||
`POST /scheduling/shifts` CSRF-verifies it (`ctx.verifyCsrf`) and forwards the create upstream,
|
`POST /scheduling/shifts` CSRF-verifies it (`ctx.verifyCsrf`) and forwards the create upstream,
|
||||||
then POST-redirect-GET. The form body lives in the plugin's own `views/partials/shift-form.ejs`,
|
then POST-redirect-GET. The form body lives in the plugin's own `views/partials/shift-form.ejs`,
|
||||||
reusing the core `field` partial.
|
reusing the core `field` partial.
|
||||||
- **Permission-gated nav** — the "Shifts" nav leaf and routes are gated on `scheduling:read` /
|
- **All three route gates** — the Overview is `public` (anyone), "My shifts" is `session` (any
|
||||||
`scheduling:write`; the whole "Scheduling" section is invisible to anyone without the grant.
|
signed-in visitor, showing only rows assigned to them), and "Shifts" is gated on `scheduling:read` /
|
||||||
|
`scheduling:write`; a leaf whose gate a visitor fails is invisible in the menu.
|
||||||
- **Its own translations** — every string comes from `i18n/en-US.ts` (`sv-SE.ts` beside it), including
|
- **Its own translations** — every string comes from `i18n/en-US.ts` (`sv-SE.ts` beside it), including
|
||||||
the nav labels, which are catalog keys in the manifest. `shifts.count` shows a plural message, and
|
the nav labels, which are catalog keys in the manifest. `shifts.count` shows a plural message, and
|
||||||
the views carry the visitor's language onto their links with `localeHref()`.
|
the views carry the visitor's language onto their links with `localeHref()`.
|
||||||
@@ -38,7 +39,7 @@ Your backend must expose two routes; the plugin treats any non-2xx as a recovera
|
|||||||
|
|
||||||
| Route | Request | Success | Response body |
|
| Route | Request | Success | Response body |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `GET /shifts` | `Accept: application/json` | `200` | JSON array of `{ id, title, assignee, start, end }` (all strings; missing fields coerce to `""`) |
|
| `GET /shifts` | `Accept: application/json`, optional `?assignee=<who>` | `200` | JSON array of `{ id, title, assignee, start, end }` (all strings; missing fields coerce to `""`). With `assignee`, only that person's rows |
|
||||||
| `POST /shifts` | JSON body `{ title, assignee, start, end }` | `2xx` | ignored (the plugin POST-redirect-GETs back to the list) |
|
| `POST /shifts` | JSON body `{ title, assignee, start, end }` | `2xx` | ignored (the plugin POST-redirect-GETs back to the list) |
|
||||||
|
|
||||||
Domain rules (overlap, capacity, time ordering) live in your backend — reject with a 4xx and the
|
Domain rules (overlap, capacity, time ordering) live in your backend — reject with a 4xx and the
|
||||||
@@ -50,6 +51,7 @@ cosmetically) — normalise to your backend's format there if it matters.
|
|||||||
|
|
||||||
## Granting access
|
## Granting access
|
||||||
|
|
||||||
A user sees Scheduling once they hold the `scheduling:read` permission in Keto (and `scheduling:write`
|
A user sees the shift list once they hold the `scheduling:read` permission in Keto (and
|
||||||
to create). The one-command bootstrap grants both to the demo admin, so the seeded
|
`scheduling:write` to create). The one-command bootstrap grants both to the demo admin, so the seeded
|
||||||
`admin@plainpages.local` can use it immediately.
|
`admin@plainpages.local` can use it immediately. "My shifts" needs no grant at all — signing in is
|
||||||
|
its whole gate.
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ const messages = {
|
|||||||
"scheduling.filter.searchLabel": "Search shifts",
|
"scheduling.filter.searchLabel": "Search shifts",
|
||||||
"scheduling.filter.searchPlaceholder": "Search title or assignee…",
|
"scheduling.filter.searchPlaceholder": "Search title or assignee…",
|
||||||
"scheduling.form.submit": "Create shift",
|
"scheduling.form.submit": "Create shift",
|
||||||
|
"scheduling.mine.empty": "No shifts are assigned to {{email}}.",
|
||||||
|
"scheduling.mine.title": "My shifts",
|
||||||
|
"scheduling.nav.mine": "My shifts",
|
||||||
"scheduling.nav.overview": "Overview",
|
"scheduling.nav.overview": "Overview",
|
||||||
"scheduling.nav.section": "Scheduling",
|
"scheduling.nav.section": "Scheduling",
|
||||||
"scheduling.nav.shifts": "Shifts",
|
"scheduling.nav.shifts": "Shifts",
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ const messages: SchedulingMessages = {
|
|||||||
"scheduling.filter.searchLabel": "Sök pass",
|
"scheduling.filter.searchLabel": "Sök pass",
|
||||||
"scheduling.filter.searchPlaceholder": "Sök på namn eller person…",
|
"scheduling.filter.searchPlaceholder": "Sök på namn eller person…",
|
||||||
"scheduling.form.submit": "Skapa pass",
|
"scheduling.form.submit": "Skapa pass",
|
||||||
|
"scheduling.mine.empty": "Inga pass är tilldelade {{email}}.",
|
||||||
|
"scheduling.mine.title": "Mina pass",
|
||||||
|
"scheduling.nav.mine": "Mina pass",
|
||||||
"scheduling.nav.overview": "Översikt",
|
"scheduling.nav.overview": "Översikt",
|
||||||
"scheduling.nav.section": "Schemaläggning",
|
"scheduling.nav.section": "Schemaläggning",
|
||||||
"scheduling.nav.shifts": "Pass",
|
"scheduling.nav.shifts": "Pass",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// folder, rename it, point it at your own backend. Full contract: README.md → Building plugins.
|
// folder, rename it, point it at your own backend. Full contract: README.md → Building plugins.
|
||||||
|
|
||||||
import { definePlugin } from "@plainpages/plugin-api";
|
import { definePlugin } from "@plainpages/plugin-api";
|
||||||
import { createShift, createUpstream, listShifts, newShiftForm, overview, READ, SCHEDULING_PATH, SHIFTS_PATH, WRITE } from "./shifts.ts";
|
import { createShift, createUpstream, listShifts, MINE_PATH, myShifts, newShiftForm, overview, READ, SCHEDULING_PATH, SHIFTS_PATH, WRITE } from "./shifts.ts";
|
||||||
|
|
||||||
// The upstream this plugin reads/writes — a stand-in for your real backend (the plugin is
|
// The upstream this plugin reads/writes — a stand-in for your real backend (the plugin is
|
||||||
// stateless). Its URL is a declared setting, so it is resolved and validated before onBoot hands it
|
// stateless). Its URL is a declared setting, so it is resolved and validated before onBoot hands it
|
||||||
@@ -12,7 +12,7 @@ let upstreamUrl = "";
|
|||||||
const upstream = createUpstream(() => upstreamUrl);
|
const upstream = createUpstream(() => upstreamUrl);
|
||||||
|
|
||||||
export default definePlugin({
|
export default definePlugin({
|
||||||
apiVersion: "0.2.0", // the host contract this was built against — a literal, never HOST_API_VERSION
|
apiVersion: "0.4.0", // the host contract this was built against — a literal, never HOST_API_VERSION
|
||||||
|
|
||||||
// onBoot runs after discovery, before the server listens — where a plugin receives its resolved
|
// onBoot runs after discovery, before the server listens — where a plugin receives its resolved
|
||||||
// settings. A malformed URL already failed the boot by then; the host validated the declared type.
|
// settings. A malformed URL already failed the boot by then; the host validated the declared type.
|
||||||
@@ -25,6 +25,7 @@ export default definePlugin({
|
|||||||
nav: [{
|
nav: [{
|
||||||
children: [
|
children: [
|
||||||
{ href: SCHEDULING_PATH, id: "scheduling:overview", label: "scheduling.nav.overview", public: true },
|
{ href: SCHEDULING_PATH, id: "scheduling:overview", label: "scheduling.nav.overview", public: true },
|
||||||
|
{ href: MINE_PATH, id: "scheduling:mine", label: "scheduling.nav.mine", session: true },
|
||||||
{ href: SHIFTS_PATH, id: "scheduling:shifts", label: "scheduling.nav.shifts", permission: READ },
|
{ href: SHIFTS_PATH, id: "scheduling:shifts", label: "scheduling.nav.shifts", permission: READ },
|
||||||
],
|
],
|
||||||
icon: "i-cal",
|
icon: "i-cal",
|
||||||
@@ -38,10 +39,9 @@ export default definePlugin({
|
|||||||
{ description: "Create and edit shifts", name: WRITE },
|
{ description: "Create and edit shifts", name: WRITE },
|
||||||
],
|
],
|
||||||
|
|
||||||
// Mounted under /scheduling; `permission` gates before the handler runs. The overview is `public`
|
|
||||||
// (anyone may reach /scheduling, signed in or not); the rest need a permission.
|
|
||||||
routes: [
|
routes: [
|
||||||
{ handler: overview(), method: "GET", path: "/", public: true },
|
{ handler: overview(), method: "GET", path: "/", public: true },
|
||||||
|
{ handler: myShifts(upstream), method: "GET", path: "/mine", session: true },
|
||||||
{ handler: listShifts(upstream), method: "GET", path: "/shifts", permission: READ },
|
{ handler: listShifts(upstream), method: "GET", path: "/shifts", permission: READ },
|
||||||
{ handler: newShiftForm(), method: "GET", path: "/shifts/new", permission: WRITE },
|
{ handler: newShiftForm(), method: "GET", path: "/shifts/new", permission: WRITE },
|
||||||
{ handler: createShift(upstream), method: "POST", path: "/shifts", permission: WRITE },
|
{ handler: createShift(upstream), method: "POST", path: "/shifts", permission: WRITE },
|
||||||
|
|||||||
@@ -4,21 +4,21 @@ import { Readable } from "node:stream";
|
|||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
// Import only from the @plainpages/plugin-api barrel — the same contract boundary shifts.ts uses (the host may
|
// Import only from the @plainpages/plugin-api barrel — the same contract boundary shifts.ts uses (the host may
|
||||||
// refactor any deeper src/* freely behind it); the test models the dev/test story the contract preaches.
|
// refactor any deeper src/* freely behind it); the test models the dev/test story the contract preaches.
|
||||||
import { englishTranslator, GuardError, Log, type PageChrome, type RequestContext, type RouteResult } from "@plainpages/plugin-api";
|
import { englishTranslator, GuardError, Log, type PageChrome, type RequestContext, type RouteResult, type User } from "@plainpages/plugin-api";
|
||||||
import enUS from "./i18n/en-US.ts";
|
import enUS from "./i18n/en-US.ts";
|
||||||
import {
|
import {
|
||||||
buildFormModel, createShift, createUpstream, listShifts, newShiftForm, overview, readInput,
|
buildFormModel, createShift, createUpstream, listShifts, myShifts, newShiftForm, overview, readInput,
|
||||||
SHIFTS_PATH, type Shift, type ShiftInput, type ShiftsUpstream, UpstreamError, validate,
|
SHIFTS_PATH, type Shift, type ShiftInput, type ShiftsUpstream, UpstreamError, validate,
|
||||||
} from "./shifts.ts";
|
} from "./shifts.ts";
|
||||||
|
|
||||||
const t = englishTranslator(enUS); // this plugin's catalog then the host's, as the host would chain them
|
const t = englishTranslator(enUS); // this plugin's catalog then the host's, as the host would chain them
|
||||||
const CHROME: PageChrome = { brand: { name: "Test" }, csrfToken: "tok", nav: [], signInHref: "/login", user: { email: "", initials: "T", name: "Tester" } };
|
const CHROME: PageChrome = { brand: { name: "Test" }, csrfToken: "tok", nav: [], signInHref: "/login", user: { email: "", initials: "T", name: "Tester" } };
|
||||||
|
|
||||||
function fakeCtx(opts: { body?: string; permissions?: string[]; url?: string; verifyCsrf?: (s: string | null | undefined) => boolean } = {}): RequestContext {
|
function fakeCtx(opts: { body?: string; permissions?: string[]; url?: string; user?: User; verifyCsrf?: (s: string | null | undefined) => boolean } = {}): RequestContext {
|
||||||
const url = new URL(opts.url ?? "http://localhost/scheduling/shifts");
|
const url = new URL(opts.url ?? "http://localhost/scheduling/shifts");
|
||||||
const req = Readable.from(opts.body != null ? [Buffer.from(opts.body)] : []) as unknown as IncomingMessage;
|
const req = Readable.from(opts.body != null ? [Buffer.from(opts.body)] : []) as unknown as IncomingMessage;
|
||||||
return {
|
return {
|
||||||
chrome: CHROME, declaredPermissions: [], declaredSettings: [], user: null, locale: "en-US", localeHref: (href) => href, locales: ["en-US"], log: new Log("none"), params: {},
|
chrome: CHROME, declaredPermissions: [], declaredSettings: [], user: opts.user ?? null, locale: "en-US", localeHref: (href) => href, locales: ["en-US"], log: new Log("none"), params: {},
|
||||||
query: url.searchParams, req, res: {} as ServerResponse, permissions: opts.permissions ?? [], t, url,
|
query: url.searchParams, req, res: {} as ServerResponse, permissions: opts.permissions ?? [], t, url,
|
||||||
verifyCsrf: opts.verifyCsrf ?? (() => true),
|
verifyCsrf: opts.verifyCsrf ?? (() => true),
|
||||||
};
|
};
|
||||||
@@ -171,3 +171,22 @@ test("buildFormModel marks title/assignee required and attaches field errors", (
|
|||||||
assert.equal(title.error, "needed");
|
assert.equal(title.error, "needed");
|
||||||
assert.equal(fields.find((f) => f.name === "start")!.required, undefined);
|
assert.equal(fields.find((f) => f.name === "start")!.required, undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---- the session-gated page: the visitor's own rows ----
|
||||||
|
|
||||||
|
test("my shifts asks the upstream for the visitor's own rows, and names them in the empty state", async () => {
|
||||||
|
const user: User = { email: "Blair.Mora@example.test", id: "01a06091-baa3-71f4-a068-4879972979ff", permissions: [] };
|
||||||
|
const mine: Shift = { assignee: "blair.mora@example.test", end: "22:00", id: "3", start: "17:00", title: "Evening on-call" };
|
||||||
|
let asked: { assignee?: string } | undefined;
|
||||||
|
|
||||||
|
const upstream = fakeUpstream({ list: async (opts) => { asked = opts; return [mine]; } });
|
||||||
|
const r = asView(await myShifts(upstream)(fakeCtx({ url: "http://localhost/scheduling/mine", user })));
|
||||||
|
assert.equal(r.view, "mine");
|
||||||
|
assert.deepEqual(asked, { assignee: "Blair.Mora@example.test" });
|
||||||
|
const table = r.data["table"] as { emptyText: string; rows: { name: string }[] };
|
||||||
|
assert.deepEqual(table.rows.map((row) => row.name), ["Evening on-call"]);
|
||||||
|
assert.match(table.emptyText, /Blair\.Mora@example\.test/); // an empty page still says whose it is
|
||||||
|
|
||||||
|
// The route carries `session: true`, but the handler asserts the session itself rather than trusting it.
|
||||||
|
await assert.rejects(async () => { await myShifts(fakeUpstream())(fakeCtx()); }, GuardError);
|
||||||
|
});
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
// pure functions against a mock upstream with no network (README.md → Local dev & test story).
|
// pure functions against a mock upstream with no network (README.md → Local dev & test story).
|
||||||
|
|
||||||
// One import from the host's @plainpages/plugin-api barrel — the stable author surface (see README.md → Building plugins).
|
// One import from the host's @plainpages/plugin-api barrel — the stable author surface (see README.md → Building plugins).
|
||||||
import { can, CSRF_FIELD, englishTranslator, GuardError, type PageChrome, parseListQuery, readFormBody, type RouteHandler, type Translate, tracedFetch } from "@plainpages/plugin-api";
|
import { can, CSRF_FIELD, englishTranslator, GuardError, type PageChrome, parseListQuery, readFormBody, requireSession, type RouteHandler, type Translate, tracedFetch } from "@plainpages/plugin-api";
|
||||||
import enUS from "./i18n/en-US.ts";
|
import enUS from "./i18n/en-US.ts";
|
||||||
|
|
||||||
// The plugin's own English (its catalog, then the host's), for a view model built outside a request:
|
// The plugin's own English (its catalog, then the host's), for a view model built outside a request:
|
||||||
@@ -16,6 +16,7 @@ const EN: Translate = englishTranslator(enUS);
|
|||||||
|
|
||||||
export const SCHEDULING_PATH = "/scheduling"; // the plugin's public overview page
|
export const SCHEDULING_PATH = "/scheduling"; // the plugin's public overview page
|
||||||
export const SHIFTS_PATH = "/scheduling/shifts";
|
export const SHIFTS_PATH = "/scheduling/shifts";
|
||||||
|
export const MINE_PATH = "/scheduling/mine"; // the visitor's own shifts — a session is the whole gate
|
||||||
export const READ = "scheduling:read"; // the permission gating the list + nav
|
export const READ = "scheduling:read"; // the permission gating the list + nav
|
||||||
export const WRITE = "scheduling:write"; // the permission gating create
|
export const WRITE = "scheduling:write"; // the permission gating create
|
||||||
|
|
||||||
@@ -46,7 +47,9 @@ export class UpstreamError extends Error {
|
|||||||
|
|
||||||
export interface ShiftsUpstream {
|
export interface ShiftsUpstream {
|
||||||
create(input: ShiftInput): Promise<void>;
|
create(input: ShiftInput): Promise<void>;
|
||||||
list(): Promise<Shift[]>;
|
// `assignee` scopes the read at the source, which is where an ownership rule belongs (README →
|
||||||
|
// Three tiers of "may I?"); without it the caller would hold everyone's rows to render one page.
|
||||||
|
list(opts?: { assignee?: string }): Promise<Shift[]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// REST client over the upstream service (a stand-in for the customer's real backend). `fetch`
|
// REST client over the upstream service (a stand-in for the customer's real backend). `fetch`
|
||||||
@@ -65,8 +68,9 @@ export function createUpstream(baseUrl: () => string, fetchImpl: typeof fetch =
|
|||||||
});
|
});
|
||||||
if (!res.ok) throw new UpstreamError(`create shift failed (${res.status})`, res.status);
|
if (!res.ok) throw new UpstreamError(`create shift failed (${res.status})`, res.status);
|
||||||
},
|
},
|
||||||
async list() {
|
async list(opts = {}) {
|
||||||
const res = await fetchImpl(`${base()}/shifts`, { headers: { accept: "application/json" } });
|
const query = opts.assignee == null ? "" : `?${new URLSearchParams({ assignee: opts.assignee })}`;
|
||||||
|
const res = await fetchImpl(`${base()}/shifts${query}`, { headers: { accept: "application/json" } });
|
||||||
if (!res.ok) throw new UpstreamError(`list shifts failed (${res.status})`, res.status);
|
if (!res.ok) throw new UpstreamError(`list shifts failed (${res.status})`, res.status);
|
||||||
const data: unknown = await res.json();
|
const data: unknown = await res.json();
|
||||||
return Array.isArray(data) ? data.map(toShift) : [];
|
return Array.isArray(data) ? data.map(toShift) : [];
|
||||||
@@ -186,6 +190,39 @@ export function newShiftForm(): RouteHandler {
|
|||||||
return (ctx) => ({ data: buildFormModel({ chrome: ctx.chrome, t: ctx.t }), view: "shift-new" });
|
return (ctx) => ({ data: buildFormModel({ chrome: ctx.chrome, t: ctx.t }), view: "shift-new" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function myShifts(upstream: ShiftsUpstream): RouteHandler {
|
||||||
|
return async (ctx) => {
|
||||||
|
const user = requireSession(ctx);
|
||||||
|
let shifts: Shift[] = [];
|
||||||
|
let error: string | undefined;
|
||||||
|
try {
|
||||||
|
shifts = await upstream.list({ assignee: user.email });
|
||||||
|
} catch (err) {
|
||||||
|
ctx.log.warn("scheduling upstream unreachable", { error: String(err) });
|
||||||
|
error = ctx.t("scheduling.upstream.list");
|
||||||
|
}
|
||||||
|
return { data: buildMineModel({ chrome: ctx.chrome, email: user.email, ...(error ? { error } : {}), shifts, t: ctx.t }), view: "mine" };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildMineModel(opts: { chrome: PageChrome; email: string; error?: string; shifts: Shift[]; t?: Translate }) {
|
||||||
|
const t = opts.t ?? EN;
|
||||||
|
return {
|
||||||
|
breadcrumbs: [{ label: t("scheduling.mine.title") }],
|
||||||
|
chrome: opts.chrome,
|
||||||
|
count: t("scheduling.shifts.count", { count: opts.shifts.length }),
|
||||||
|
...(opts.error ? { error: opts.error } : {}),
|
||||||
|
table: {
|
||||||
|
caption: t("scheduling.mine.title"),
|
||||||
|
columns: [{ label: t("scheduling.table.shift") }, { label: t("scheduling.table.start") }, { label: t("scheduling.table.end") }],
|
||||||
|
// Only when the upstream answered: a failed read knows nothing about what is assigned.
|
||||||
|
...(opts.error === undefined ? { emptyText: t("scheduling.mine.empty", { email: opts.email }) } : {}),
|
||||||
|
rows: opts.shifts.map((s) => ({ cells: [{ rowHeader: { text: s.title } }, s.start, s.end], name: s.title })),
|
||||||
|
},
|
||||||
|
title: t("scheduling.mine.title"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Public overview: a page anyone may reach — its route + nav node are marked `public`, so the
|
// Public overview: a page anyone may reach — its route + nav node are marked `public`, so the
|
||||||
// gate lets an anonymous visitor through and the menu option shows for everyone. The real data
|
// gate lets an anonymous visitor through and the menu option shows for everyone. The real data
|
||||||
// (the shifts list) stays behind `scheduling:read`; a reader gets a link straight to it, anyone
|
// (the shifts list) stays behind `scheduling:read`; a reader gets a link straight to it, anyone
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<%#
|
||||||
|
Scheduling · the visitor's own shifts (reference plugin).
|
||||||
|
Data: chrome, title, breadcrumbs, count, table, error?
|
||||||
|
%><%
|
||||||
|
const navHtml = include("partials/nav-tree", { nodes: chrome.nav });
|
||||||
|
const tableHtml = include("partials/data-table", table);
|
||||||
|
const alertHtml = locals.error ? include("partials/alert", { text: locals.error, tone: "neg" }) : "";
|
||||||
|
-%>
|
||||||
|
<%- include("partials/shell", {
|
||||||
|
body: '<div class="scheduling-page">' + alertHtml + '<p class="shift-count">' + count + '</p>' + tableHtml + '</div>',
|
||||||
|
brand: chrome.brand,
|
||||||
|
breadcrumbs,
|
||||||
|
csrfToken: chrome.csrfToken,
|
||||||
|
nav: navHtml,
|
||||||
|
styles: ["/public/scheduling/scheduling.css"],
|
||||||
|
theme: chrome.theme,
|
||||||
|
title,
|
||||||
|
user: chrome.user,
|
||||||
|
}) %>
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
// of the app: stdlib only, in-memory (state resets on restart), no auth. Point PLUGIN_SETTING_SCHEDULING_UPSTREAM
|
// of the app: stdlib only, in-memory (state resets on restart), no auth. Point PLUGIN_SETTING_SCHEDULING_UPSTREAM
|
||||||
// at your real service in production.
|
// at your real service in production.
|
||||||
//
|
//
|
||||||
// GET /shifts → 200 [ { id, title, assignee, start, end }, … ]
|
// GET /shifts → 200 [ { id, title, assignee, start, end }, … ] (?assignee=<who> → only theirs)
|
||||||
// POST /shifts → 201 { id, … } (body: { title, assignee, start, end })
|
// POST /shifts → 201 { id, … } (body: { title, assignee, start, end })
|
||||||
|
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
@@ -12,9 +12,10 @@ import { createServer } from "node:http";
|
|||||||
const PORT = Number(process.env.PORT ?? 4000);
|
const PORT = Number(process.env.PORT ?? 4000);
|
||||||
|
|
||||||
const shifts = [
|
const shifts = [
|
||||||
{ id: randomUUID(), title: "Morning — Front desk", assignee: "Avery Kline", start: "2026-06-22 08:00", end: "2026-06-22 12:00" },
|
{ id: randomUUID(), title: "Morning — Front desk", assignee: "avery.kline@plainpages.local", start: "2026-06-22 08:00", end: "2026-06-22 12:00" },
|
||||||
{ id: randomUUID(), title: "Afternoon — Support", assignee: "Blair Mora", start: "2026-06-22 12:00", end: "2026-06-22 17:00" },
|
{ id: randomUUID(), title: "Afternoon — Support", assignee: "blair.mora@plainpages.local", start: "2026-06-22 12:00", end: "2026-06-22 17:00" },
|
||||||
{ id: randomUUID(), title: "Evening — On-call", assignee: "Casey Nguyen", start: "2026-06-22 17:00", end: "2026-06-22 22:00" },
|
{ id: randomUUID(), title: "Evening — On-call", assignee: "casey.nguyen@plainpages.local", start: "2026-06-22 17:00", end: "2026-06-22 22:00" },
|
||||||
|
{ id: randomUUID(), title: "Night — Escalations", assignee: "admin@plainpages.local", start: "2026-06-22 22:00", end: "2026-06-23 06:00" },
|
||||||
];
|
];
|
||||||
|
|
||||||
const json = (res, status, body) => {
|
const json = (res, status, body) => {
|
||||||
@@ -33,7 +34,11 @@ const readBody = (req) =>
|
|||||||
|
|
||||||
createServer(async (req, res) => {
|
createServer(async (req, res) => {
|
||||||
const url = new URL(req.url ?? "/", "http://localhost");
|
const url = new URL(req.url ?? "/", "http://localhost");
|
||||||
if (url.pathname === "/shifts" && req.method === "GET") return json(res, 200, shifts);
|
if (url.pathname === "/shifts" && req.method === "GET") {
|
||||||
|
const assignee = url.searchParams.get("assignee");
|
||||||
|
if (assignee === null) return json(res, 200, shifts);
|
||||||
|
return json(res, 200, shifts.filter((s) => s.assignee.toLowerCase() === assignee.toLowerCase()));
|
||||||
|
}
|
||||||
if (url.pathname === "/shifts" && req.method === "POST") {
|
if (url.pathname === "/shifts" && req.method === "POST") {
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
const shift = { id: randomUUID(), assignee: String(b.assignee ?? ""), end: String(b.end ?? ""), start: String(b.start ?? ""), title: String(b.title ?? "") };
|
const shift = { id: randomUUID(), assignee: String(b.assignee ?? ""), end: String(b.end ?? ""), start: String(b.start ?? ""), title: String(b.title ?? "") };
|
||||||
|
|||||||
Generated
+4
-4
@@ -8,7 +8,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@larvit/log": "2.3.0",
|
"@larvit/log": "2.3.0",
|
||||||
"ejs": "6.0.1",
|
"ejs": "6.0.1",
|
||||||
"lucide-static": "1.33.0",
|
"lucide-static": "1.34.0",
|
||||||
"postgres": "3.4.9"
|
"postgres": "3.4.9"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -399,9 +399,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/lucide-static": {
|
"node_modules/lucide-static": {
|
||||||
"version": "1.33.0",
|
"version": "1.34.0",
|
||||||
"resolved": "https://registry.npmjs.org/lucide-static/-/lucide-static-1.33.0.tgz",
|
"resolved": "https://registry.npmjs.org/lucide-static/-/lucide-static-1.34.0.tgz",
|
||||||
"integrity": "sha512-jNGgvTNcLUfVRX4N9PH9pVVTJzoph/BmYmgU838bYBQodkUJL4nAThkuymFz1x3OUYMhJxPndC7rdg1sxOPYKg==",
|
"integrity": "sha512-pSUvFhfhvDnhXN1fXerZEMgKLQQ3DneKwFYlqB5ji8OEAN0iPi/qgwQvCkcL519QgMeR66IpS/pT342VyT/g4g==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/postgres": {
|
"node_modules/postgres": {
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@larvit/log": "2.3.0",
|
"@larvit/log": "2.3.0",
|
||||||
"ejs": "6.0.1",
|
"ejs": "6.0.1",
|
||||||
"lucide-static": "1.33.0",
|
"lucide-static": "1.34.0",
|
||||||
"postgres": "3.4.9"
|
"postgres": "3.4.9"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -316,6 +316,11 @@ span.nav-self { cursor: default; } /* static / non-clickable */
|
|||||||
.btn-primary:hover { filter: brightness(1.06); }
|
.btn-primary:hover { filter: brightness(1.06); }
|
||||||
.btn-ghost { background: transparent; border-color: transparent; }
|
.btn-ghost { background: transparent; border-color: transparent; }
|
||||||
.btn-ghost:hover { background: var(--surface-2); }
|
.btn-ghost:hover { background: var(--surface-2); }
|
||||||
|
.btn-menu::after {
|
||||||
|
content: ""; width: 7px; height: 7px; margin: -2px 1px 0 1px;
|
||||||
|
border-right: 1.5px solid var(--text-faint); border-bottom: 1.5px solid var(--text-faint);
|
||||||
|
transform: rotate(45deg);
|
||||||
|
}
|
||||||
.icon-btn {
|
.icon-btn {
|
||||||
width: 30px; height: 30px; padding: 0; justify-content: center;
|
width: 30px; height: 30px; padding: 0; justify-content: center;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
@@ -494,7 +499,8 @@ span.nav-self { cursor: default; } /* static / non-clickable */
|
|||||||
position-anchor: auto;
|
position-anchor: auto;
|
||||||
position-try-fallbacks: flip-block, flip-inline;
|
position-try-fallbacks: flip-block, flip-inline;
|
||||||
top: anchor(bottom); right: anchor(right);
|
top: anchor(bottom); right: anchor(right);
|
||||||
min-width: 210px; padding: 6px;
|
min-width: 210px; max-width: min(320px, 92vw); padding: 6px;
|
||||||
|
max-height: 60vh; overflow-y: auto; overflow-wrap: anywhere;
|
||||||
background: var(--surface); color: var(--text);
|
background: var(--surface); color: var(--text);
|
||||||
border: 1px solid var(--border-2); border-radius: var(--radius);
|
border: 1px solid var(--border-2); border-radius: var(--radius);
|
||||||
box-shadow: 0 8px 28px rgba(0,0,0,.16);
|
box-shadow: 0 8px 28px rgba(0,0,0,.16);
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ test("readHostApiVersion pulls the constant out of the real source, and returns
|
|||||||
test("bumping HOST_API_VERSION is a deliberate act, so pin the shipped value", () => {
|
test("bumping HOST_API_VERSION is a deliberate act, so pin the shipped value", () => {
|
||||||
// Not a substitute for the release gate — this test cannot see a tag. It is the tripwire that
|
// Not a substitute for the release gate — this test cannot see a tag. It is the tripwire that
|
||||||
// makes an accidental edit fail here rather than at release time.
|
// makes an accidental edit fail here rather than at release time.
|
||||||
assert.equal(readHostApiVersion(readFileSync("src/plugin-host/plugin.ts", "utf8")), "0.2.0");
|
assert.equal(readHostApiVersion(readFileSync("src/plugin-host/plugin.ts", "utf8")), "0.4.0");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("every author-facing apiVersion sample matches the shipped contract", () => {
|
test("every author-facing apiVersion sample matches the shipped contract", () => {
|
||||||
|
|||||||
@@ -182,7 +182,7 @@ into the app. Create `plugins/hello/plugin.ts`:
|
|||||||
import { definePlugin } from "@plainpages/plugin-api";
|
import { definePlugin } from "@plainpages/plugin-api";
|
||||||
|
|
||||||
export default definePlugin({
|
export default definePlugin({
|
||||||
apiVersion: "0.2.0",
|
apiVersion: "0.4.0",
|
||||||
nav: [{ href: "/hello", id: "hello", label: "Hello", public: true }],
|
nav: [{ href: "/hello", id: "hello", label: "Hello", public: true }],
|
||||||
routes: [
|
routes: [
|
||||||
{ method: "GET", path: "/", public: true, handler: () => ({ html: "<h1>Hello from my plugin</h1>" }) },
|
{ method: "GET", path: "/", public: true, handler: () => ({ html: "<h1>Hello from my plugin</h1>" }) },
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import type { User } from "../http/context.ts";
|
||||||
|
import { allows, gatesSet } from "./gate.ts";
|
||||||
|
|
||||||
|
const holder: User = { email: "holder@example.test", id: "01a06091-ba9f-765f-abf4-b5144c314bc7", permissions: ["x:read"] };
|
||||||
|
const stranger: User = { email: "stranger@example.test", id: "01a06091-baa3-7b4d-810a-c9ee7e559d98", permissions: [] };
|
||||||
|
|
||||||
|
test("allows: ungated and public are open to anyone; session needs a user; permission needs the token", () => {
|
||||||
|
assert.equal(allows({}, null), true);
|
||||||
|
assert.equal(allows({ public: true }, null), true);
|
||||||
|
|
||||||
|
assert.equal(allows({ session: true }, null), false);
|
||||||
|
assert.equal(allows({ session: true }, stranger), true); // signed in is the whole gate — no grant
|
||||||
|
|
||||||
|
assert.equal(allows({ permission: "x:read" }, null), false);
|
||||||
|
assert.equal(allows({ permission: "x:read" }, stranger), false);
|
||||||
|
assert.equal(allows({ permission: "x:read" }, holder), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("gatesSet names the gates a declaration sets, so discovery can refuse more than one", () => {
|
||||||
|
assert.deepEqual(gatesSet({}), []);
|
||||||
|
assert.deepEqual(gatesSet({ session: true }), ["session"]);
|
||||||
|
assert.deepEqual(gatesSet({ permission: "x:read", public: true }), ["public", "permission"]);
|
||||||
|
assert.deepEqual(gatesSet({ permission: "x:read", public: true, session: true }), ["public", "session", "permission"]);
|
||||||
|
// `false` is not a gate — only a set one counts, so { session: false } is an ungated route.
|
||||||
|
assert.deepEqual(gatesSet({ public: false, session: false }), []);
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// One home for the gate rule, so the router and the menu can never disagree about what a visitor
|
||||||
|
// may reach. README → Public pages & menu items.
|
||||||
|
import type { User } from "../http/context.ts";
|
||||||
|
|
||||||
|
const GATES = ["public", "session", "permission"] as const;
|
||||||
|
|
||||||
|
export interface Gate {
|
||||||
|
permission?: string; // the Keto Permission the caller must hold, `<resource>:<action>`
|
||||||
|
public?: boolean; // anyone, signed in or not
|
||||||
|
session?: boolean; // any signed-in user, no grant to hold; anonymous is sent to /login
|
||||||
|
}
|
||||||
|
|
||||||
|
export function allows(gate: Gate, user: User | null): boolean {
|
||||||
|
if (gate.public === true) return true;
|
||||||
|
if (gate.session === true) return user !== null;
|
||||||
|
return gate.permission == null || (user?.permissions.includes(gate.permission) ?? false);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function gatesSet(gate: Gate | null | undefined): string[] {
|
||||||
|
if (gate == null) return [];
|
||||||
|
return GATES.filter((name) => (name === "permission" ? gate.permission != null : gate[name] === true));
|
||||||
|
}
|
||||||
+4
-2
@@ -86,8 +86,10 @@ export interface Reminted {
|
|||||||
// anonymous instead of re-hitting Ory on every one.
|
// anonymous instead of re-hitting Ory on every one.
|
||||||
export async function remintSession(deps: LoginDeps, cookie: string | undefined, options: { secure?: boolean } = {}): Promise<Reminted> {
|
export async function remintSession(deps: LoginDeps, cookie: string | undefined, options: { secure?: boolean } = {}): Promise<Reminted> {
|
||||||
const completed = await completeLogin(deps, cookie);
|
const completed = await completeLogin(deps, cookie);
|
||||||
if (!completed) return { setCookie: clearSessionCookie(options), user: null };
|
// No email is no session, exactly as `claimsToUser` reads a token carrying none: a User with an
|
||||||
return { setCookie: sessionCookie(completed.jwt, options), user: { email: completed.email ?? "", id: completed.userId, permissions: completed.permissions } };
|
// empty email reads as anonymous in the shell, and is a blank key to whatever scopes on it.
|
||||||
|
if (!completed?.email) return { setCookie: clearSessionCookie(options), user: null };
|
||||||
|
return { setCookie: sessionCookie(completed.jwt, options), user: { email: completed.email, id: completed.userId, permissions: completed.permissions } };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build the Set-Cookie for our session JWT. HttpOnly + SameSite=Lax by default; `secure` is
|
// Build the Set-Cookie for our session JWT. HttpOnly + SameSite=Lax by default; `secure` is
|
||||||
|
|||||||
@@ -609,6 +609,7 @@ test("guards map to responses: requireSession → /login, a failed can/check →
|
|||||||
{ handler: (ctx) => { if (!can(ctx, "admin")) throw new GuardError(403, "no"); return { html: "ok" }; }, method: "GET", path: "/admin-only" },
|
{ handler: (ctx) => { if (!can(ctx, "admin")) throw new GuardError(403, "no"); return { html: "ok" }; }, method: "GET", path: "/admin-only" },
|
||||||
{ handler: async (ctx) => { if (!(await check(keto, ctx, { namespace: "Resource", object: ctx.params.id ?? "", relation: "view" }))) throw new GuardError(403, "no"); return { html: "seen" }; }, method: "GET", path: "/doc/:id" },
|
{ handler: async (ctx) => { if (!(await check(keto, ctx, { namespace: "Resource", object: ctx.params.id ?? "", relation: "view" }))) throw new GuardError(403, "no"); return { html: "seen" }; }, method: "GET", path: "/doc/:id" },
|
||||||
{ handler: () => ({ html: "gated" }), method: "GET", path: "/gated", permission: "secret:read" }, // declarative route gate
|
{ handler: () => ({ html: "gated" }), method: "GET", path: "/gated", permission: "secret:read" }, // declarative route gate
|
||||||
|
{ handler: () => ({ html: "mine" }), method: "GET", path: "/mine", session: true }, // declarative session gate
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
const app = createApp({ jwks: staticJwks([ecJwk]), plugins: [guarded] });
|
const app = createApp({ jwks: staticJwks([ecJwk]), plugins: [guarded] });
|
||||||
@@ -642,6 +643,12 @@ test("guards map to responses: requireSession → /login, a failed can/check →
|
|||||||
assert.equal(gDenied.status, 403);
|
assert.equal(gDenied.status, 403);
|
||||||
assert.match(await gDenied.text(), /403/); // the rendered 403.ejs over HTTP
|
assert.match(await gDenied.text(), /403/); // the rendered 403.ejs over HTTP
|
||||||
assert.equal((await fetch(url + "/guarded/gated", auth(["secret:read"]))).status, 200);
|
assert.equal((await fetch(url + "/guarded/gated", auth(["secret:read"]))).status, 200);
|
||||||
|
|
||||||
|
// declarative `session` gate: anonymous → sign in, and any signed-in user through, grant or none.
|
||||||
|
const sAnon = await fetch(url + "/guarded/mine", { redirect: "manual" });
|
||||||
|
assert.equal(sAnon.status, 303);
|
||||||
|
assert.equal(sAnon.headers.get("location"), "/login?return_to=%2Fguarded%2Fmine");
|
||||||
|
assert.equal((await fetch(url + "/guarded/mine", auth([]))).status, 200);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("plugin hooks: onRequest can short-circuit a request and onResponse observes the handler result", async (t) => {
|
test("plugin hooks: onRequest can short-circuit a request and onResponse observes the handler result", async (t) => {
|
||||||
|
|||||||
+3
-2
@@ -28,7 +28,8 @@ import { DEFAULT_MENU, type MenuConfig } from "../ui/menu-config.ts";
|
|||||||
import { declaredPermissions, type Plugin, type RouteHandler, type RouteResult } from "../plugin-host/plugin.ts";
|
import { declaredPermissions, type Plugin, type RouteHandler, type RouteResult } from "../plugin-host/plugin.ts";
|
||||||
import type { PluginSettings } from "../plugin-host/settings.ts";
|
import type { PluginSettings } from "../plugin-host/settings.ts";
|
||||||
import type { SystemCapabilities } from "../plugin-host/system.ts";
|
import type { SystemCapabilities } from "../plugin-host/system.ts";
|
||||||
import { allowedMethods, isAuthorized, matchRoute } from "../plugin-host/router.ts";
|
import { allows } from "../auth/gate.ts";
|
||||||
|
import { allowedMethods, matchRoute } from "../plugin-host/router.ts";
|
||||||
import { buildAuthRoutes } from "../auth/routes.ts";
|
import { buildAuthRoutes } from "../auth/routes.ts";
|
||||||
import { securityHeaders } from "./security-headers.ts";
|
import { securityHeaders } from "./security-headers.ts";
|
||||||
import { localPath } from "./safe-url.ts";
|
import { localPath } from "./safe-url.ts";
|
||||||
@@ -281,7 +282,7 @@ export function createApp(options: AppOptions = {}): Server {
|
|||||||
const match = matchRoute(plugins, method, pathname);
|
const match = matchRoute(plugins, method, pathname);
|
||||||
if (match) {
|
if (match) {
|
||||||
const routeCtx = contextFor(match.plugin.id, match.params);
|
const routeCtx = contextFor(match.plugin.id, match.params);
|
||||||
if (!isAuthorized(match.route, routeCtx.permissions)) {
|
if (!allows(match.route, routeCtx.user)) {
|
||||||
// Anonymous → sign in, remembering the page as return_to; a signed-in user who simply
|
// Anonymous → sign in, remembering the page as return_to; a signed-in user who simply
|
||||||
// lacks the permission gets the 403 page.
|
// lacks the permission gets the 403 page.
|
||||||
if (!routeCtx.user) { res.writeHead(303, { location: loginRedirect(routeCtx) }).end(); return; }
|
if (!routeCtx.user) { res.writeHead(303, { location: loginRedirect(routeCtx) }).end(); return; }
|
||||||
|
|||||||
@@ -100,6 +100,7 @@ const messages = {
|
|||||||
"filter.remove": "Remove {{label}} filter",
|
"filter.remove": "Remove {{label}} filter",
|
||||||
"filter.reset": "Reset",
|
"filter.reset": "Reset",
|
||||||
"filter.search": "Search",
|
"filter.search": "Search",
|
||||||
|
"filter.selected": "{{label}}, {{count}} selected",
|
||||||
"filter.to": "To",
|
"filter.to": "To",
|
||||||
"filter.toSeparator": "to",
|
"filter.toSeparator": "to",
|
||||||
|
|
||||||
|
|||||||
@@ -91,6 +91,7 @@ const messages: CoreMessages = {
|
|||||||
"filter.remove": "Ta bort filtret {{label}}",
|
"filter.remove": "Ta bort filtret {{label}}",
|
||||||
"filter.reset": "Återställ",
|
"filter.reset": "Återställ",
|
||||||
"filter.search": "Sök",
|
"filter.search": "Sök",
|
||||||
|
"filter.selected": "{{label}}, {{count}} valda",
|
||||||
"filter.to": "Till",
|
"filter.to": "Till",
|
||||||
"filter.toSeparator": "till",
|
"filter.toSeparator": "till",
|
||||||
|
|
||||||
|
|||||||
@@ -62,6 +62,11 @@ const badCases: Array<{ name: string; files: Record<string, string>; match: RegE
|
|||||||
{ name: "duplicate nav id across plugins", files: { "a/plugin.ts": full("a").replace("a:root", "dup"), "b/plugin.ts": full("b").replace("b:root", "dup") }, match: /nav id "dup"/ },
|
{ name: "duplicate nav id across plugins", files: { "a/plugin.ts": full("a").replace("a:root", "dup"), "b/plugin.ts": full("b").replace("b:root", "dup") }, match: /nav id "dup"/ },
|
||||||
{ name: "a route marked public AND permission is contradictory", files: { "contra/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", routes: [{ method: "GET", path: "/", public: true, permission: "x:read", handler: () => ({ html: "x" }) }] };` }, match: /contra.*public.*permission/s },
|
{ name: "a route marked public AND permission is contradictory", files: { "contra/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", routes: [{ method: "GET", path: "/", public: true, permission: "x:read", handler: () => ({ html: "x" }) }] };` }, match: /contra.*public.*permission/s },
|
||||||
{ name: "a nav node marked public AND permission is contradictory", files: { "contranav/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", nav: [{ id: "n", label: "N", public: true, permission: "x:read" }] };` }, match: /contranav.*public.*permission/s },
|
{ name: "a nav node marked public AND permission is contradictory", files: { "contranav/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", nav: [{ id: "n", label: "N", public: true, permission: "x:read" }] };` }, match: /contranav.*public.*permission/s },
|
||||||
|
{ name: "a route marked session AND permission is contradictory", files: { "contrasess/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", routes: [{ method: "GET", path: "/", session: true, permission: "x:read", handler: () => ({ html: "x" }) }] };` }, match: /contrasess.*session.*permission/s },
|
||||||
|
{ name: "a route marked public AND session is contradictory", files: { "contrapub/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", routes: [{ method: "GET", path: "/", public: true, session: true, handler: () => ({ html: "x" }) }] };` }, match: /contrapub.*public.*session/s },
|
||||||
|
{ name: "a route whose session flag is a truthy non-boolean is refused, not read as ungated", files: { "truthy/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", routes: [{ method: "GET", path: "/", session: "yes", handler: () => ({ html: "x" }) }] };` }, match: /truthy.*session.*true/s },
|
||||||
|
{ name: "a nav node whose public flag is a truthy non-boolean is refused too", files: { "truthynav/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", nav: [{ id: "n", label: "N", public: 1 }] };` }, match: /truthynav.*public.*true/s },
|
||||||
|
{ name: "a nav node marked session AND permission is contradictory", files: { "contrasessnav/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", nav: [{ id: "n", label: "N", session: true, permission: "x:read" }] };` }, match: /contrasessnav.*session.*permission/s },
|
||||||
// A permission name is <resource>:<action> wherever the manifest mentions one. Enforced here, not
|
// A permission name is <resource>:<action> wherever the manifest mentions one. Enforced here, not
|
||||||
// only in the admin GUI, so it holds for a plugin installed without that GUI.
|
// only in the admin GUI, so it holds for a plugin installed without that GUI.
|
||||||
{ name: "a route gating on a bare word", files: { "bare/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", routes: [{ method: "GET", path: "/", permission: "admin", handler: () => ({ html: "x" }) }] };` }, match: /bare.*admin.*<resource>:<action>/s },
|
{ name: "a route gating on a bare word", files: { "bare/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", routes: [{ method: "GET", path: "/", permission: "admin", handler: () => ({ html: "x" }) }] };` }, match: /bare.*admin.*<resource>:<action>/s },
|
||||||
@@ -96,12 +101,19 @@ test("a discovery failure tells the operator their plugins/ copy may just be out
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("a route + nav node may be marked public and load fine", async (t) => {
|
test("a route + nav node may be marked public, or session, and load fine", async (t) => {
|
||||||
const dir = scaffold(t, { "pub/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", nav: [{ href: "/pub", id: "n", label: "N", public: true }], routes: [{ method: "GET", path: "/", public: true, handler: () => ({ html: "x" }) }] };` });
|
const dir = scaffold(t, {
|
||||||
|
"pub/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", nav: [{ href: "/pub", id: "n", label: "N", public: true }], routes: [{ method: "GET", path: "/", public: true, handler: () => ({ html: "x" }) }] };`,
|
||||||
|
"sess/plugin.ts": `export default { apiVersion: "${HOST_API_VERSION}", nav: [{ href: "/sess", id: "s", label: "S", session: true }], routes: [{ method: "GET", path: "/", session: true, handler: () => ({ html: "x" }) }] };`,
|
||||||
|
});
|
||||||
const plugins = await discoverPlugins({ dir });
|
const plugins = await discoverPlugins({ dir });
|
||||||
assert.equal(plugins.length, 1);
|
assert.equal(plugins.length, 2);
|
||||||
assert.equal(plugins[0]?.routes?.[0]?.public, true);
|
const pub = plugins.find((p) => p.id === "pub");
|
||||||
assert.equal(plugins[0]?.nav?.[0]?.public, true);
|
const sess = plugins.find((p) => p.id === "sess");
|
||||||
|
assert.equal(pub?.routes?.[0]?.public, true);
|
||||||
|
assert.equal(pub?.nav?.[0]?.public, true);
|
||||||
|
assert.equal(sess?.routes?.[0]?.session, true);
|
||||||
|
assert.equal(sess?.nav?.[0]?.session, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("`admin` is not reserved — the admin screens ship as a drop-in plugin mounted at /admin", async (t) => {
|
test("`admin` is not reserved — the admin screens ship as a drop-in plugin mounted at /admin", async (t) => {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||||
|
import { type Gate, gatesSet } from "../auth/gate.ts";
|
||||||
import { checkApiVersion, findConflicts, isValidPermissionName, isValidPluginId, RESERVED_PLUGIN_IDS, type Plugin, type PluginManifest } from "./plugin.ts";
|
import { checkApiVersion, findConflicts, isValidPermissionName, isValidPluginId, RESERVED_PLUGIN_IDS, type Plugin, type PluginManifest } from "./plugin.ts";
|
||||||
import { settingsDeclError } from "./settings.ts";
|
import { settingsDeclError } from "./settings.ts";
|
||||||
import { isValidStoragePluginId, MAX_STORAGE_PLUGIN_ID_LENGTH } from "./storage.ts";
|
import { isValidStoragePluginId, MAX_STORAGE_PLUGIN_ID_LENGTH } from "./storage.ts";
|
||||||
@@ -146,12 +147,13 @@ function shapeError(manifest: PluginManifest): string | null {
|
|||||||
const settings = settingsDeclError(manifest.settings);
|
const settings = settingsDeclError(manifest.settings);
|
||||||
if (settings) return settings;
|
if (settings) return settings;
|
||||||
}
|
}
|
||||||
// `public` and `permission` are contradictory on the same route/nav node — "open to all" vs
|
|
||||||
// "needs this permission". Refuse rather than silently pick one, so the author's intent is unambiguous.
|
|
||||||
for (const route of Array.isArray(manifest.routes) ? manifest.routes : []) {
|
for (const route of Array.isArray(manifest.routes) ? manifest.routes : []) {
|
||||||
if (route?.public === true && route.permission != null) return `route "${route.method} ${route.path}" sets both public and permission — they are mutually exclusive`;
|
const flag = gateFlagError(`route "${route?.method} ${route?.path}"`, route);
|
||||||
|
if (flag) return flag;
|
||||||
|
const gates = gatesSet(route);
|
||||||
|
if (gates.length > 1) return `route "${route?.method} ${route?.path}" sets ${gates.join(" and ")}; a route names exactly one gate — public, session or permission`;
|
||||||
}
|
}
|
||||||
const navContradiction = findPublicNavContradiction(manifest.nav);
|
const navContradiction = findNavGateContradiction(manifest.nav);
|
||||||
if (navContradiction) return navContradiction;
|
if (navContradiction) return navContradiction;
|
||||||
// Every permission name the manifest mentions — gated on or declared — must be `<resource>:<action>`.
|
// Every permission name the manifest mentions — gated on or declared — must be `<resource>:<action>`.
|
||||||
// A bare word names a role, and roles are groups here (README → Naming a permission).
|
// A bare word names a role, and roles are groups here (README → Naming a permission).
|
||||||
@@ -170,11 +172,22 @@ function shapeError(manifest: PluginManifest): string | null {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recurse the nav fragment: a node that is both `public` and `permission`-gated is contradictory.
|
// A truthy non-boolean sets no gate at all, so `session: "yes"` would read as an open page.
|
||||||
function findPublicNavContradiction(nodes: PluginManifest["nav"]): string | null {
|
function gateFlagError(what: string, gate: Gate | null | undefined): string | null {
|
||||||
|
for (const flag of ["public", "session"] as const) {
|
||||||
|
const value = gate?.[flag];
|
||||||
|
if (value !== undefined && typeof value !== "boolean") return `${what} sets ${flag} to ${JSON.stringify(value)}; a gate is declared with \`true\``;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findNavGateContradiction(nodes: PluginManifest["nav"]): string | null {
|
||||||
for (const node of Array.isArray(nodes) ? nodes : []) {
|
for (const node of Array.isArray(nodes) ? nodes : []) {
|
||||||
if (node?.public === true && node.permission != null) return `nav node "${node.label ?? node.id ?? "?"}" sets both public and permission — they are mutually exclusive`;
|
const flag = gateFlagError(`nav node "${node?.label ?? node?.id ?? "?"}"`, node);
|
||||||
const inChild = findPublicNavContradiction(node?.children);
|
if (flag) return flag;
|
||||||
|
const gates = gatesSet(node);
|
||||||
|
if (gates.length > 1) return `nav node "${node?.label ?? node?.id ?? "?"}" sets ${gates.join(" and ")}; a node names exactly one gate — public, session or permission`;
|
||||||
|
const inChild = findNavGateContradiction(node?.children);
|
||||||
if (inChild) return inChild;
|
if (inChild) return inChild;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -4,13 +4,14 @@
|
|||||||
// A plugin's identity is its folder under plugins/: folder name = `id` (isValidPluginId), mount =
|
// A plugin's identity is its folder under plugins/: folder name = `id` (isValidPluginId), mount =
|
||||||
// `/<id>`. Neither is in the manifest — the host derives them, so they can't drift or be claimed twice.
|
// `/<id>`. Neither is in the manifest — the host derives them, so they can't drift or be claimed twice.
|
||||||
|
|
||||||
|
import type { Gate } from "../auth/gate.ts";
|
||||||
import type { RequestContext } from "../http/context.ts";
|
import type { RequestContext } from "../http/context.ts";
|
||||||
import type { NavNode } from "../ui/nav.ts";
|
import type { NavNode } from "../ui/nav.ts";
|
||||||
import { envName, type SettingDecl, type SettingsOf } from "./settings.ts";
|
import { envName, type SettingDecl, type SettingsOf } from "./settings.ts";
|
||||||
import type { StorageCredentials } from "./storage.ts";
|
import type { StorageCredentials } from "./storage.ts";
|
||||||
|
|
||||||
// The Plainpages release this contract ships in — see README → Contract versioning.
|
// The Plainpages release this contract ships in — see README → Contract versioning.
|
||||||
export const HOST_API_VERSION = "0.2.0";
|
export const HOST_API_VERSION = "0.4.0";
|
||||||
|
|
||||||
export type HttpMethod = "DELETE" | "GET" | "HEAD" | "PATCH" | "POST" | "PUT";
|
export type HttpMethod = "DELETE" | "GET" | "HEAD" | "PATCH" | "POST" | "PUT";
|
||||||
|
|
||||||
@@ -24,14 +25,11 @@ export type RouteResult =
|
|||||||
|
|
||||||
export type RouteHandler = (ctx: RequestContext) => Promise<RouteResult | void> | RouteResult | void;
|
export type RouteHandler = (ctx: RequestContext) => Promise<RouteResult | void> | RouteResult | void;
|
||||||
|
|
||||||
export interface Route {
|
// `Gate` carries `permission`/`public`/`session`, checked before the handler runs.
|
||||||
|
export interface Route extends Gate {
|
||||||
handler: RouteHandler;
|
handler: RouteHandler;
|
||||||
method: HttpMethod;
|
method: HttpMethod;
|
||||||
path: string; // relative to the plugin's mount path `/<id>`; ":name" segments → ctx.params.name
|
path: string; // relative to the plugin's mount path `/<id>`; ":name" segments → ctx.params.name
|
||||||
permission?: string; // coarse gate — the Keto Permission the caller must hold; checked before the handler runs
|
|
||||||
// Same as omitting `permission`, but stated outright so public is a deliberate choice rather than
|
|
||||||
// a forgotten gate. Mutually exclusive with `permission` (discovery refuses both).
|
|
||||||
public?: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A Keto Permission this plugin gates on — declared for docs/seeding. Names are a shared global
|
// A Keto Permission this plugin gates on — declared for docs/seeding. Names are a shared global
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { test } from "node:test";
|
import { test } from "node:test";
|
||||||
import type { Plugin, Route } from "./plugin.ts";
|
import type { Plugin, Route } from "./plugin.ts";
|
||||||
import { allowedMethods, isAuthorized, matchRoute } from "./router.ts";
|
import { allowedMethods, matchRoute } from "./router.ts";
|
||||||
|
|
||||||
const noop: Route["handler"] = () => ({ html: "x" });
|
const noop: Route["handler"] = () => ({ html: "x" });
|
||||||
|
|
||||||
@@ -54,14 +54,3 @@ test("allowedMethods lists methods at a path (GET implies HEAD); empty when the
|
|||||||
assert.deepEqual(allowedMethods(plugins, "/x/a"), ["GET", "HEAD", "POST"]);
|
assert.deepEqual(allowedMethods(plugins, "/x/a"), ["GET", "HEAD", "POST"]);
|
||||||
assert.deepEqual(allowedMethods(plugins, "/x/missing"), []);
|
assert.deepEqual(allowedMethods(plugins, "/x/missing"), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("isAuthorized: open routes pass; gated routes require the permission token; public is explicitly open", () => {
|
|
||||||
const open: Route = { handler: noop, method: "GET", path: "/" };
|
|
||||||
const gated: Route = { handler: noop, method: "GET", path: "/", permission: "x:read" };
|
|
||||||
const pub: Route = { handler: noop, method: "GET", path: "/", public: true }; // blessed public alias
|
|
||||||
assert.equal(isAuthorized(open, []), true);
|
|
||||||
assert.equal(isAuthorized(gated, []), false);
|
|
||||||
assert.equal(isAuthorized(gated, ["x:read"]), true);
|
|
||||||
assert.equal(isAuthorized(gated, ["other"]), false);
|
|
||||||
assert.equal(isAuthorized(pub, []), true); // open to anonymous, like omitting permission — but stated outright
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -73,10 +73,3 @@ export function allowedMethods(plugins: Plugin[], pathname: string): string[] {
|
|||||||
}
|
}
|
||||||
return [...methods].sort();
|
return [...methods].sort();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Coarse permission gate: a route marked `public` (or one with no `permission`) is open; otherwise
|
|
||||||
// the user's permissions (from the session JWT) must include the token. The same rule composeNav uses
|
|
||||||
// for the menu. `public` and `permission` are mutually exclusive (discovery refuses both).
|
|
||||||
export function isAuthorized(route: Route, permissions: string[]): boolean {
|
|
||||||
return route.public === true || route.permission == null || permissions.includes(route.permission);
|
|
||||||
}
|
|
||||||
|
|||||||
+3
-5
@@ -10,7 +10,7 @@ import { composeNav, type NavNode } from "./nav.ts";
|
|||||||
import type { Plugin } from "../plugin-host/plugin.ts";
|
import type { Plugin } from "../plugin-host/plugin.ts";
|
||||||
import { branding, shellUser, type ShellUser } from "./shell-context.ts";
|
import { branding, shellUser, type ShellUser } from "./shell-context.ts";
|
||||||
|
|
||||||
const DASHBOARD_NAV: NavNode = { href: "/dashboard", icon: "i-grid", id: "dashboard", label: "nav.dashboard" };
|
const DASHBOARD_NAV: NavNode = { href: "/dashboard", icon: "i-grid", id: "dashboard", label: "nav.dashboard", session: true };
|
||||||
|
|
||||||
export interface PageChrome {
|
export interface PageChrome {
|
||||||
brand: { logo?: string; name: string; sub?: string };
|
brand: { logo?: string; name: string; sub?: string };
|
||||||
@@ -35,8 +35,7 @@ export interface ChromeOptions {
|
|||||||
export function buildPluginChrome(opts: ChromeOptions): PageChrome {
|
export function buildPluginChrome(opts: ChromeOptions): PageChrome {
|
||||||
const t = opts.t ?? ENGLISH;
|
const t = opts.t ?? ENGLISH;
|
||||||
const carryLocale = opts.localeHref ?? ((href: string) => href);
|
const carryLocale = opts.localeHref ?? ((href: string) => href);
|
||||||
// Dashboard is gated, so an anonymous click would only dead-end at /login.
|
const fragments: NavNode[][] = [[DASHBOARD_NAV]];
|
||||||
const fragments: NavNode[][] = opts.user ? [[DASHBOARD_NAV]] : [];
|
|
||||||
// A plugin's nav labels are keys in *its* catalog, so translate each fragment with that plugin's
|
// A plugin's nav labels are keys in *its* catalog, so translate each fragment with that plugin's
|
||||||
// translator before merging. composeNav then runs the core one over the result; already-translated
|
// translator before merging. composeNav then runs the core one over the result; already-translated
|
||||||
// text passes through it.
|
// text passes through it.
|
||||||
@@ -44,8 +43,7 @@ export function buildPluginChrome(opts: ChromeOptions): PageChrome {
|
|||||||
if (p.nav?.length) fragments.push(translateNav(p.nav, opts.translatorFor?.(p.id) ?? t));
|
if (p.nav?.length) fragments.push(translateNav(p.nav, opts.translatorFor?.(p.id) ?? t));
|
||||||
}
|
}
|
||||||
|
|
||||||
const permissions = opts.user?.permissions ?? [];
|
const nav = composeNav(fragments, opts.menu.override, opts.user ?? null, t);
|
||||||
const nav = composeNav(fragments, opts.menu.override, permissions, t);
|
|
||||||
if (opts.currentPath) {
|
if (opts.currentPath) {
|
||||||
// Mark by the *best* (longest) href that is the path or a parent of it, so a sub-path like
|
// Mark by the *best* (longest) href that is the path or a parent of it, so a sub-path like
|
||||||
// /admin/users/new marks the Users base leaf (/admin/users) and the dashboard marks Dashboard.
|
// /admin/users/new marks the Users base leaf (/admin/users) and the dashboard marks Dashboard.
|
||||||
|
|||||||
@@ -37,6 +37,15 @@ const config = {
|
|||||||
options: [{ value: "engineering", label: "Engineering" }, { value: "design", label: "Design" }, { value: "oncall", label: "On-call" }],
|
options: [{ value: "engineering", label: "Engineering" }, { value: "design", label: "Design" }, { value: "oncall", label: "On-call" }],
|
||||||
},
|
},
|
||||||
{ type: "daterange", legend: "Joined", from: { name: "joined_from", value: "2026-01-01", label: "Joined from" }, to: { name: "joined_to", value: "2026-06-14", label: "Joined to" } },
|
{ type: "daterange", legend: "Joined", from: { name: "joined_from", value: "2026-01-01", label: "Joined from" }, to: { name: "joined_to", value: "2026-06-14", label: "Joined to" } },
|
||||||
|
{
|
||||||
|
type: "multiselect",
|
||||||
|
name: "owner",
|
||||||
|
legend: "Owner",
|
||||||
|
note: "30 of 45",
|
||||||
|
value: ["ann"],
|
||||||
|
options: [{ value: "ann", label: "Ann Berg" }, { value: "bo", label: "Bo Falk" }],
|
||||||
|
},
|
||||||
|
{ type: "multiselect", name: "room", legend: "Room", options: [{ value: "lab", label: "Lab" }] },
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
pills: [{ label: "Team", value: "Engineering", remove: "?tag=oncall" }],
|
pills: [{ label: "Team", value: "Engineering", remove: "?tag=oncall" }],
|
||||||
@@ -64,6 +73,14 @@ test("filter-bar renders a GET form with every control type, reflecting current
|
|||||||
assert.match(html, /<input type="checkbox" name="tag" value="oncall" checked>On-call/);
|
assert.match(html, /<input type="checkbox" name="tag" value="oncall" checked>On-call/);
|
||||||
assert.match(html, /<input type="checkbox" name="tag" value="design">Design/);
|
assert.match(html, /<input type="checkbox" name="tag" value="design">Design/);
|
||||||
|
|
||||||
|
// multiselect — a disclosure: the trigger names the filter and counts what is chosen, the options
|
||||||
|
// are checkboxes in a fieldset the popover holds, so a long list costs one line of the bar.
|
||||||
|
assert.match(html, /<div class="menu"><button class="btn btn-menu" type="button" popovertarget="f-owner-menu" aria-label="Owner, 1 selected">Owner<span class="badge">1<\/span><\/button><div id="f-owner-menu" class="menu-pop left" popover>/);
|
||||||
|
assert.match(html, /popover><div class="menu-head">30 of 45<\/div><fieldset class="menu-field"><legend class="menu-head">Owner<\/legend><label class="menu-check"><input type="checkbox" name="owner" value="ann" checked>Ann Berg<\/label><label class="menu-check"><input type="checkbox" name="owner" value="bo">Bo Falk<\/label><\/fieldset>/);
|
||||||
|
|
||||||
|
// Nothing chosen — no badge and no count in the accessible name.
|
||||||
|
assert.match(html, /<button class="btn btn-menu" type="button" popovertarget="f-room-menu">Room<\/button>/);
|
||||||
|
|
||||||
// daterange — calendar icon + two date inputs with values.
|
// daterange — calendar icon + two date inputs with values.
|
||||||
assert.match(html, /<div class="daterange"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-cal"\s*\/?><\/svg>.*?<input type="date" id="f-joined_from" name="joined_from" value="2026-01-01">.*?<span class="to" aria-hidden="true">to<\/span>.*?<input type="date" id="f-joined_to" name="joined_to" value="2026-06-14">/);
|
assert.match(html, /<div class="daterange"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-cal"\s*\/?><\/svg>.*?<input type="date" id="f-joined_from" name="joined_from" value="2026-01-01">.*?<span class="to" aria-hidden="true">to<\/span>.*?<input type="date" id="f-joined_to" name="joined_to" value="2026-06-14">/);
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -12,7 +12,7 @@ const flat = (s: string): string => s.replace(/>\s+</g, "><").replace(/\s+/g, "
|
|||||||
test("menu renders trigger, positioning, the item matrix and check groups", async () => {
|
test("menu renders trigger, positioning, the item matrix and check groups", async () => {
|
||||||
const html = flat(await render({
|
const html = flat(await render({
|
||||||
id: "cols-menu",
|
id: "cols-menu",
|
||||||
trigger: { icon: "i-cols", text: "Columns", label: "Column settings" },
|
trigger: { count: 3, icon: "i-cols", text: "Columns", label: "Column settings" },
|
||||||
align: "left", up: true, width: 240,
|
align: "left", up: true, width: 240,
|
||||||
items: [
|
items: [
|
||||||
{ head: "Actions" },
|
{ head: "Actions" },
|
||||||
@@ -30,7 +30,7 @@ test("menu renders trigger, positioning, the item matrix and check groups", asyn
|
|||||||
|
|
||||||
// Trigger: icon + text + aria-label, wired to the panel by id; popover carries align/up + width.
|
// Trigger: icon + text + aria-label, wired to the panel by id; popover carries align/up + width.
|
||||||
// The panel is the trigger's next sibling inside the wrapper — the CSS open state reads that.
|
// The panel is the trigger's next sibling inside the wrapper — the CSS open state reads that.
|
||||||
assert.match(html, /<div class="menu"><button class="btn" type="button" popovertarget="cols-menu" aria-label="Column settings"><svg class="ico ico-sm"><use href="#i-cols"\s*\/?><\/svg>Columns<\/button><div id="cols-menu" class="menu-pop left up" popover style="min-width:240px">/);
|
assert.match(html, /<div class="menu"><button class="btn" type="button" popovertarget="cols-menu" aria-label="Column settings"><svg class="ico ico-sm"><use href="#i-cols"\s*\/?><\/svg>Columns<span class="badge">3<\/span><\/button><div id="cols-menu" class="menu-pop left up" popover style="min-width:240px">/);
|
||||||
|
|
||||||
// Item matrix: head, button-with-icon, link, separator, danger button.
|
// Item matrix: head, button-with-icon, link, separator, danger button.
|
||||||
assert.match(html, /<div class="menu-head">Actions<\/div>/);
|
assert.match(html, /<div class="menu-head">Actions<\/div>/);
|
||||||
|
|||||||
+19
-9
@@ -1,7 +1,12 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { test } from "node:test";
|
import { test } from "node:test";
|
||||||
|
import type { User } from "../http/context.ts";
|
||||||
import { composeNav, type NavNode } from "./nav.ts";
|
import { composeNav, type NavNode } from "./nav.ts";
|
||||||
|
|
||||||
|
function viewer(...permissions: string[]): User {
|
||||||
|
return { email: "viewer@example.test", id: "01a06091-ba9f-765f-abf4-b5144c314bc7", permissions };
|
||||||
|
}
|
||||||
|
|
||||||
// Two plugin fragments; ids let the override target nodes, `permission` gates per permission.
|
// Two plugin fragments; ids let the override target nodes, `permission` gates per permission.
|
||||||
const fragments: NavNode[][] = [
|
const fragments: NavNode[][] = [
|
||||||
[{
|
[{
|
||||||
@@ -15,7 +20,7 @@ const fragments: NavNode[][] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
test("composeNav merges fragments, filters by permission, and emits clean render nodes", () => {
|
test("composeNav merges fragments, filters by permission, and emits clean render nodes", () => {
|
||||||
const tree = composeNav(fragments, {}, ["scheduling:read"]);
|
const tree = composeNav(fragments, {}, viewer("scheduling:read"));
|
||||||
|
|
||||||
// Reports gone (no reports:read), Manage gone (no scheduling:admin), header kept with Shifts.
|
// Reports gone (no reports:read), Manage gone (no scheduling:admin), header kept with Shifts.
|
||||||
// Output carries no `id`/`permission` and omits absent fields — ready for nav-tree.ejs.
|
// Output carries no `id`/`permission` and omits absent fields — ready for nav-tree.ejs.
|
||||||
@@ -30,7 +35,7 @@ test("composeNav drops gated subtrees, empty headers, and (with no permissions)
|
|||||||
{ id: "admin", label: "Admin", permission: "users:read", children: [{ href: "/u", id: "u", label: "Users" }] },
|
{ id: "admin", label: "Admin", permission: "users:read", children: [{ href: "/u", id: "u", label: "Users" }] },
|
||||||
{ id: "free", label: "Free", children: [{ href: "/d", id: "d", label: "Docs" }] },
|
{ id: "free", label: "Free", children: [{ href: "/d", id: "d", label: "Docs" }] },
|
||||||
]];
|
]];
|
||||||
assert.deepEqual(composeNav(gatedHeader, {}, []), [
|
assert.deepEqual(composeNav(gatedHeader, {}, viewer()), [
|
||||||
{ label: "Free", children: [{ href: "/d", label: "Docs" }] },
|
{ label: "Free", children: [{ href: "/d", label: "Docs" }] },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -39,26 +44,31 @@ test("composeNav drops gated subtrees, empty headers, and (with no permissions)
|
|||||||
{ id: "sec", label: "Section", children: [{ href: "/x", id: "x", label: "X", permission: "x:read" }] },
|
{ id: "sec", label: "Section", children: [{ href: "/x", id: "x", label: "X", permission: "x:read" }] },
|
||||||
{ href: "/hub", id: "hub", label: "Hub", children: [{ href: "/y", id: "y", label: "Y", permission: "y:read" }] },
|
{ href: "/hub", id: "hub", label: "Hub", children: [{ href: "/y", id: "y", label: "Y", permission: "y:read" }] },
|
||||||
]];
|
]];
|
||||||
assert.deepEqual(composeNav(emptyHeader, {}, []), [{ href: "/hub", label: "Hub" }]);
|
assert.deepEqual(composeNav(emptyHeader, {}, viewer()), [{ href: "/hub", label: "Hub" }]);
|
||||||
|
|
||||||
// No fragments / no permissions → empty tree, never throws.
|
// No fragments / no permissions → empty tree, never throws.
|
||||||
assert.deepEqual(composeNav(), []);
|
assert.deepEqual(composeNav(), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("composeNav keeps a node marked public for everyone — the blessed public alias", () => {
|
test("composeNav shows a public node to everyone and a session node to any signed-in user", () => {
|
||||||
// A header with one public child + one gated child: with no permissions, the public child keeps the
|
// A header with a public child, a session child and a gated child: the public child keeps the
|
||||||
// header alive (the gated child is filtered out) — so a plugin can show a public menu option to all.
|
// header alive for an anonymous visitor — so a plugin can show a menu option to all.
|
||||||
const frag: NavNode[][] = [[{
|
const frag: NavNode[][] = [[{
|
||||||
icon: "i-cal", id: "sched", label: "Scheduling",
|
icon: "i-cal", id: "sched", label: "Scheduling",
|
||||||
children: [
|
children: [
|
||||||
{ href: "/scheduling", id: "overview", label: "Overview", public: true },
|
{ href: "/scheduling", id: "overview", label: "Overview", public: true },
|
||||||
|
{ href: "/scheduling/mine", id: "mine", label: "Mine", session: true },
|
||||||
{ href: "/scheduling/shifts", id: "shifts", label: "Shifts", permission: "scheduling:read" },
|
{ href: "/scheduling/shifts", id: "shifts", label: "Shifts", permission: "scheduling:read" },
|
||||||
],
|
],
|
||||||
}]];
|
}]];
|
||||||
// `public` is filter-only (like id/permission) — never rendered into the output node.
|
// `public`/`session` are filter-only (like id/permission) — never rendered into the output node.
|
||||||
assert.deepEqual(composeNav(frag, {}, []), [
|
assert.deepEqual(composeNav(frag, {}, null), [
|
||||||
{ icon: "i-cal", label: "Scheduling", children: [{ href: "/scheduling", label: "Overview" }] },
|
{ icon: "i-cal", label: "Scheduling", children: [{ href: "/scheduling", label: "Overview" }] },
|
||||||
]);
|
]);
|
||||||
|
// Signed in with no permission at all: the session node appears, the permission-gated one does not.
|
||||||
|
assert.deepEqual(composeNav(frag, {}, viewer()), [
|
||||||
|
{ icon: "i-cal", label: "Scheduling", children: [{ href: "/scheduling", label: "Overview" }, { href: "/scheduling/mine", label: "Mine" }] },
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("composeNav applies the override: rename, group, order, hide (then filters)", () => {
|
test("composeNav applies the override: rename, group, order, hide (then filters)", () => {
|
||||||
@@ -74,7 +84,7 @@ test("composeNav applies the override: rename, group, order, hide (then filters)
|
|||||||
groups: [{ icon: "i-box", id: "grp", label: "Group", open: true, children: ["b", "c"] }], // wrap b+c
|
groups: [{ icon: "i-box", id: "grp", label: "Group", open: true, children: ["b", "c"] }], // wrap b+c
|
||||||
order: ["grp", "a"], // grp before the lone a
|
order: ["grp", "a"], // grp before the lone a
|
||||||
hide: ["c"], // remove c from inside the group
|
hide: ["c"], // remove c from inside the group
|
||||||
}, ["secrets:read"]);
|
}, viewer("secrets:read"));
|
||||||
|
|
||||||
// grp emitted (b only, c hidden), reordered before a; Secret kept now that permission "secrets:read" is present.
|
// grp emitted (b only, c hidden), reordered before a; Secret kept now that permission "secrets:read" is present.
|
||||||
assert.deepEqual(tree, [
|
assert.deepEqual(tree, [
|
||||||
|
|||||||
+14
-13
@@ -1,12 +1,15 @@
|
|||||||
// composeNav: merge each plugin's nav fragment into one tree, apply the central override, then
|
// composeNav: merge each plugin's nav fragment into one tree, apply the central override, then
|
||||||
// permission-filter per user. Pure and I/O-free — menu gating reads the JWT `permissions` claim,
|
// filter per user. Pure and I/O-free — menu gating reads the JWT `permissions` claim, never Keto.
|
||||||
// never Keto. A node is visible iff it is `public`, declares no `permission`, or the user holds that
|
// A node is visible iff `allows` passes its gate; a gated header hides its whole subtree, and a pure
|
||||||
// name; a gated header hides its whole subtree, and a pure header left with no children is dropped.
|
// header left with no children is dropped.
|
||||||
|
|
||||||
|
import { allows, type Gate } from "../auth/gate.ts";
|
||||||
|
import type { User } from "../http/context.ts";
|
||||||
import { ENGLISH } from "../i18n/english.ts";
|
import { ENGLISH } from "../i18n/english.ts";
|
||||||
import type { Translate } from "../i18n/translate.ts";
|
import type { Translate } from "../i18n/translate.ts";
|
||||||
|
|
||||||
export interface NavNode {
|
// `Gate` carries `permission`/`public`/`session` — consumed by the filter, never rendered.
|
||||||
|
export interface NavNode extends Gate {
|
||||||
id?: string; // stable key for override targeting; stripped from the rendered tree
|
id?: string; // stable key for override targeting; stripped from the rendered tree
|
||||||
children?: NavNode[];
|
children?: NavNode[];
|
||||||
count?: number;
|
count?: number;
|
||||||
@@ -15,12 +18,10 @@ export interface NavNode {
|
|||||||
icon?: string;
|
icon?: string;
|
||||||
label: string;
|
label: string;
|
||||||
open?: boolean;
|
open?: boolean;
|
||||||
permission?: string; // required permission token; consumed by the filter, never rendered
|
|
||||||
public?: boolean; // show to everyone, signed in or not — the blessed alias for "no permission", stated outright; consumed by the filter, never rendered. Mutually exclusive with permission (discovery refuses both).
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Central override (config/menu.ts). Targets nodes by `id`; applied rename → group →
|
// Central override (config/menu.ts). Targets nodes by `id`; applied rename → group →
|
||||||
// order → hide, then the per-user permission filter runs last.
|
// order → hide, then the per-user gate filter runs last.
|
||||||
export interface NavOverride {
|
export interface NavOverride {
|
||||||
groups?: NavGroupSpec[]; // wrap top-level nodes (by id) under a new header
|
groups?: NavGroupSpec[]; // wrap top-level nodes (by id) under a new header
|
||||||
hide?: string[]; // remove nodes by id, at any depth (incl. a group's id)
|
hide?: string[]; // remove nodes by id, at any depth (incl. a group's id)
|
||||||
@@ -39,7 +40,7 @@ export interface NavGroupSpec {
|
|||||||
export function composeNav(
|
export function composeNav(
|
||||||
fragments: NavNode[][] = [],
|
fragments: NavNode[][] = [],
|
||||||
override: NavOverride = {},
|
override: NavOverride = {},
|
||||||
permissions: string[] = [],
|
user: User | null = null,
|
||||||
t: Translate = ENGLISH,
|
t: Translate = ENGLISH,
|
||||||
): NavNode[] {
|
): NavNode[] {
|
||||||
let nodes: NavNode[] = fragments.flat();
|
let nodes: NavNode[] = fragments.flat();
|
||||||
@@ -47,7 +48,7 @@ export function composeNav(
|
|||||||
if (override.groups?.length) nodes = applyGroups(nodes, override.groups);
|
if (override.groups?.length) nodes = applyGroups(nodes, override.groups);
|
||||||
if (override.order?.length) nodes = applyOrder(nodes, override.order);
|
if (override.order?.length) nodes = applyOrder(nodes, override.order);
|
||||||
if (override.hide?.length) nodes = hideTree(nodes, new Set(override.hide));
|
if (override.hide?.length) nodes = hideTree(nodes, new Set(override.hide));
|
||||||
return filterByRoles(nodes, new Set(permissions)).map((node) => toRenderNode(node, t));
|
return filterByGate(nodes, user).map((node) => toRenderNode(node, t));
|
||||||
}
|
}
|
||||||
|
|
||||||
function renameTree(nodes: NavNode[], rename: Record<string, string>): NavNode[] {
|
function renameTree(nodes: NavNode[], rename: Record<string, string>): NavNode[] {
|
||||||
@@ -104,19 +105,19 @@ function hideTree(nodes: NavNode[], hide: Set<string>): NavNode[] {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
function filterByRoles(nodes: NavNode[], permissions: Set<string>): NavNode[] {
|
function filterByGate(nodes: NavNode[], user: User | null): NavNode[] {
|
||||||
const out: NavNode[] = [];
|
const out: NavNode[] = [];
|
||||||
for (const n of nodes) {
|
for (const n of nodes) {
|
||||||
if (n.public !== true && n.permission != null && !permissions.has(n.permission)) continue; // gated → drop node + subtree (public always shows)
|
if (!allows(n, user)) continue; // gated → drop node + subtree
|
||||||
if (!n.children) { out.push(n); continue; }
|
if (!n.children) { out.push(n); continue; }
|
||||||
const children = filterByRoles(n.children, permissions);
|
const children = filterByGate(n.children, user);
|
||||||
if (children.length === 0 && n.href == null) continue; // empty pure header → drop
|
if (children.length === 0 && n.href == null) continue; // empty pure header → drop
|
||||||
out.push({ ...n, children });
|
out.push({ ...n, children });
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strip the helper-only fields (id/permission) and drop absent ones, so the tree is exactly
|
// Strip the helper-only fields (id and the gate) and drop absent ones, so the tree is exactly
|
||||||
// what nav-tree.ejs reads. Labels (a manifest's, or the central override's rename) pass through
|
// what nav-tree.ejs reads. Labels (a manifest's, or the central override's rename) pass through
|
||||||
// `t` on the way out: a label that names a catalog key is translated, any other renders as written.
|
// `t` on the way out: a label that names a catalog key is translated, any other renders as written.
|
||||||
function toRenderNode(n: NavNode, t: Translate): NavNode {
|
function toRenderNode(n: NavNode, t: Translate): NavNode {
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@
|
|||||||
<p>${t("dashboard.starter.intro")}</p>
|
<p>${t("dashboard.starter.intro")}</p>
|
||||||
<p>${t("dashboard.starter.replace")}</p>
|
<p>${t("dashboard.starter.replace")}</p>
|
||||||
<pre class="code-block"><code>export default definePlugin({
|
<pre class="code-block"><code>export default definePlugin({
|
||||||
apiVersion: "0.2.0",
|
apiVersion: "0.4.0",
|
||||||
// view names plugins/<id>/views/<view>.ejs, rendered in this same shell
|
// view names plugins/<id>/views/<view>.ejs, rendered in this same shell
|
||||||
dashboard: (ctx) => ({ view: "dashboard", data: { /* … */ } }),
|
dashboard: (ctx) => ({ view: "dashboard", data: { /* … */ } }),
|
||||||
});</code></pre>
|
});</code></pre>
|
||||||
|
|||||||
@@ -2,12 +2,15 @@
|
|||||||
Filter bar: a real GET form so filtering is server-side and zero-JS. Config:
|
Filter bar: a real GET form so filtering is server-side and zero-JS. Config:
|
||||||
rows: Control[][] rows of controls, laid out left→right
|
rows: Control[][] rows of controls, laid out left→right
|
||||||
pills, clearHref, label, action, applyLabel
|
pills, clearHref, label, action, applyLabel
|
||||||
Control.type ∈ search | segmented | select | chips | daterange | spacer.
|
Control.type ∈ search | segmented | select | chips | multiselect | daterange | spacer.
|
||||||
search { name, placeholder?, value?, label? }
|
search { name, placeholder?, value?, label? }
|
||||||
segmented { name, legend?, value?, options:{value,label,count?}[] } (radios)
|
segmented { name, legend?, value?, options:{value,label,count?}[] } (radios)
|
||||||
select { name, label, value?, options:{value,label}[] }
|
select { name, label, value?, options:{value,label}[] }
|
||||||
chips { name, legend?, value?:string[], options:{value,label}[] } (checkboxes)
|
chips { name, legend?, value?:string[], options:{value,label}[] } (checkboxes)
|
||||||
|
multiselect { name, legend?, note?, value?:string[], options:{value,label}[] } (checkboxes in a popover)
|
||||||
daterange { legend?, from:{name,value?,label?}, to:{name,value?,label?} }
|
daterange { legend?, from:{name,value?,label?}, to:{name,value?,label?} }
|
||||||
|
chips and multiselect are the same checkboxes on the same parameter: on the bar, or behind a
|
||||||
|
button once the list is too long to lay there.
|
||||||
The form is a GET, which replaces the whole query string — so the visitor's chosen language rides
|
The form is a GET, which replaces the whole query string — so the visitor's chosen language rides
|
||||||
along as a hidden input, and every href here (pills, clear) is run through localeHref.
|
along as a hidden input, and every href here (pills, clear) is run through localeHref.
|
||||||
%><%
|
%><%
|
||||||
@@ -34,6 +37,16 @@
|
|||||||
<span class="filter"><label class="sr-only" for="f-<%= c.name %>"><%= c.label %></label><span class="select"><select id="f-<%= c.name %>" name="<%= c.name %>"><% c.options.forEach((o) => { %><option value="<%= o.value %>"<% if (eq(c.value, o.value)) { %> selected<% } %>><%= o.label %></option><% }) %></select></span></span>
|
<span class="filter"><label class="sr-only" for="f-<%= c.name %>"><%= c.label %></label><span class="select"><select id="f-<%= c.name %>" name="<%= c.name %>"><% c.options.forEach((o) => { %><option value="<%= o.value %>"<% if (eq(c.value, o.value)) { %> selected<% } %>><%= o.label %></option><% }) %></select></span></span>
|
||||||
<% } else if (c.type === "chips") { -%>
|
<% } else if (c.type === "chips") { -%>
|
||||||
<fieldset class="filter-field"><legend class="sr-only"><%= c.legend || c.name %></legend><span class="filter-legend" aria-hidden="true"><%= c.legend || c.name %></span><div class="chips"><% (c.options).forEach((o) => { const on = (c.value || []).map(String).includes(String(o.value)); %><label class="chip"><span class="chip-dot" aria-hidden="true"></span><input type="checkbox" name="<%= c.name %>" value="<%= o.value %>"<% if (on) { %> checked<% } %>><%= o.label %></label><% }) %></div></fieldset>
|
<fieldset class="filter-field"><legend class="sr-only"><%= c.legend || c.name %></legend><span class="filter-legend" aria-hidden="true"><%= c.legend || c.name %></span><div class="chips"><% (c.options).forEach((o) => { const on = (c.value || []).map(String).includes(String(o.value)); %><label class="chip"><span class="chip-dot" aria-hidden="true"></span><input type="checkbox" name="<%= c.name %>" value="<%= o.value %>"<% if (on) { %> checked<% } %>><%= o.label %></label><% }) %></div></fieldset>
|
||||||
|
<% } else if (c.type === "multiselect") { const legend = c.legend || c.name; const on = (c.value || []).map(String); -%>
|
||||||
|
<%- include("menu", {
|
||||||
|
id: "f-" + c.name + "-menu",
|
||||||
|
align: "left", kebab: false, up: false, width: null, // explicit: EJS would otherwise inherit the page's own
|
||||||
|
trigger: { class: "btn btn-menu", count: on.length || null, label: on.length ? t("filter.selected", { count: on.length, label: legend }) : null, text: legend },
|
||||||
|
items: [
|
||||||
|
...(c.note ? [{ head: c.note }] : []),
|
||||||
|
{ group: { legend, name: c.name, options: c.options.map((o) => ({ checked: on.includes(String(o.value)), label: o.label, value: o.value })) } },
|
||||||
|
],
|
||||||
|
}) %>
|
||||||
<% } else if (c.type === "daterange") { -%>
|
<% } else if (c.type === "daterange") { -%>
|
||||||
<fieldset class="filter-field"><legend class="sr-only"><%= c.legend || t("filter.dateRange") %></legend><span class="filter-legend" aria-hidden="true"><%= c.legend || t("filter.dateRange") %></span><div class="daterange"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-cal"/></svg><label class="sr-only" for="f-<%= c.from.name %>"><%= c.from.label || t("filter.from") %></label><input type="date" id="f-<%= c.from.name %>" name="<%= c.from.name %>"<% if (c.from.value) { %> value="<%= c.from.value %>"<% } %>><span class="to" aria-hidden="true"><%= t("filter.toSeparator") %></span><label class="sr-only" for="f-<%= c.to.name %>"><%= c.to.label || t("filter.to") %></label><input type="date" id="f-<%= c.to.name %>" name="<%= c.to.name %>"<% if (c.to.value) { %> value="<%= c.to.value %>"<% } %>></div></fieldset>
|
<fieldset class="filter-field"><legend class="sr-only"><%= c.legend || t("filter.dateRange") %></legend><span class="filter-legend" aria-hidden="true"><%= c.legend || t("filter.dateRange") %></span><div class="daterange"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-cal"/></svg><label class="sr-only" for="f-<%= c.from.name %>"><%= c.from.label || t("filter.from") %></label><input type="date" id="f-<%= c.from.name %>" name="<%= c.from.name %>"<% if (c.from.value) { %> value="<%= c.from.value %>"<% } %>><span class="to" aria-hidden="true"><%= t("filter.toSeparator") %></span><label class="sr-only" for="f-<%= c.to.name %>"><%= c.to.label || t("filter.to") %></label><input type="date" id="f-<%= c.to.name %>" name="<%= c.to.name %>"<% if (c.to.value) { %> value="<%= c.to.value %>"<% } %>></div></fieldset>
|
||||||
<% } else if (c.type === "spacer") { -%>
|
<% } else if (c.type === "spacer") { -%>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
Config:
|
Config:
|
||||||
id string REQUIRED — the panel's id and the trigger's popovertarget. Name it for what
|
id string REQUIRED — the panel's id and the trigger's popovertarget. Name it for what
|
||||||
the menu is (`locale-menu`); it must be unique on the page.
|
the menu is (`locale-menu`); it must be unique on the page.
|
||||||
trigger { class?(="btn", "" ⇒ none) · label?(aria-label) · icon? · text? · html?(raw inner, wins) }
|
trigger { class?(="btn", "" ⇒ none) · label?(aria-label) · icon? · text? · count?(badge) · html?(raw inner, wins) }
|
||||||
align? "left" left-align the popover (default right)
|
align? "left" left-align the popover (default right)
|
||||||
up? boolean open upward (footer menus)
|
up? boolean open upward (footer menus)
|
||||||
kebab? boolean bare kebab trigger (adds .kebab)
|
kebab? boolean bare kebab trigger (adds .kebab)
|
||||||
@@ -26,7 +26,7 @@
|
|||||||
const popCls = "menu-pop" + (locals.align === "left" ? " left" : "") + (locals.up ? " up" : "");
|
const popCls = "menu-pop" + (locals.align === "left" ? " left" : "") + (locals.up ? " up" : "");
|
||||||
const width = locals.width;
|
const width = locals.width;
|
||||||
-%>
|
-%>
|
||||||
<div class="menu"><button<% if (btnCls) { %> class="<%= btnCls %>"<% } %> type="button" popovertarget="<%= locals.id %>"<% if (trigger.label) { %> aria-label="<%= trigger.label %>"<% } %>><% if (trigger.html != null) { %><%- trigger.html %><% } else { if (trigger.icon) { %><svg class="ico ico-sm"><use href="#<%= trigger.icon %>"/></svg><% } if (trigger.text) { %><%= trigger.text %><% } } %></button><div id="<%= locals.id %>" class="<%= popCls %>" popover<% if (width != null) { %> style="min-width:<%= typeof width === "number" ? width + "px" : width %>"<% } %>>
|
<div class="menu"><button<% if (btnCls) { %> class="<%= btnCls %>"<% } %> type="button" popovertarget="<%= locals.id %>"<% if (trigger.label) { %> aria-label="<%= trigger.label %>"<% } %>><% if (trigger.html != null) { %><%- trigger.html %><% } else { if (trigger.icon) { %><svg class="ico ico-sm"><use href="#<%= trigger.icon %>"/></svg><% } if (trigger.text) { %><%= trigger.text %><% } if (trigger.count != null) { %><span class="badge"><%= trigger.count %></span><% } } %></button><div id="<%= locals.id %>" class="<%= popCls %>" popover<% if (width != null) { %> style="min-width:<%= typeof width === "number" ? width + "px" : width %>"<% } %>>
|
||||||
<% items.forEach((it) => { -%>
|
<% items.forEach((it) => { -%>
|
||||||
<% if (it.head != null) { -%>
|
<% if (it.head != null) { -%>
|
||||||
<div class="menu-head"><%= it.head %></div>
|
<div class="menu-head"><%= it.head %></div>
|
||||||
|
|||||||
Reference in New Issue
Block a user