4 Commits
Author SHA1 Message Date
Esa Kataja c6a8532569 Tag non-production tabs, and drop the FOODSTER_ prefix
With dev and prod open side by side in the same browser, the tabs were
indistinguishable. ENV is written into the title of every page unless it says
prod, so "dev · Foodster" picks itself out. The value is used verbatim, so
ENV=staging labels itself too, and prod and production both count as unmarked
so a stray capital cannot tag the real instance.

Environment variables lose their prefix: PASSWORD, DB, ENV, ADDR, HOST, REPO,
TAG. The container namespaces them already, and this matches how the other
services here are configured.

PUID/PGID are the exception rather than UID/GID. UID is read-only in bash, so
a value set in .env would be silently replaced by the invoking shell's own and
compose's user: would ignore what was asked for.

Breaking for a running instance: the deployed .env has to be rewritten in the
same deploy, or the app will refuse to start on an unset PASSWORD.
2026-09-05 23:55:25 +03:00
Esa Kataja b8a46cdd30 Patch the day list in place instead of navigating
Kirjaa now works like the catalog: opening a day, picking a dish, saving,
deleting, cancelling and "Näytä lisää" all patch the list where it stands.
Nothing loads a page, so the scroll position never moves.

One builder serves all three paths. buildLog takes what the screen should
show — the day, an open dish, whether the entry is being changed or a delete
confirmed — and the page render, the patch and the post-write response all go
through it. After a save it is called with only the date, so the day comes
back closed rather than reopening the sides step it was just submitted from.

Links stay links and forms stay forms, with data-on:click__prevent and
data-on:submit__prevent layered over them, so it all still works with
JavaScript off. Each response patches a single element, so plain text/html is
enough here; the SSE writer is only needed by the catalog, where the list and
both forms have to move together.

The anchors added in the previous attempt are gone. They could never have
worked: the browser positions an anchor without knowing where the page was
scrolled, so it jumped regardless.
2026-09-05 23:45:53 +03:00
Esa Kataja e5e020457a Patch the catalog in place instead of navigating
Deleting a dish partway down the list sent the browser back to the top. The
first attempt at fixing it used anchors, which cannot work: the browser
positions the element with no knowledge of where the page was scrolled, so it
still jumps. Datastar was already loaded and doing nothing but search.

Every catalog action now patches. The bin, the pencil and Peruuta stay real
links; the forms stay real forms. Datastar intercepts them with
data-on:click__prevent and data-on:submit__prevent, and the same handlers
redirect when the Datastar-Request header is absent, so none of it requires
JavaScript. Posting with {contentType: 'form'} sends the enclosing form as
FormData, which means the handlers keep reading r.FormValue and no input had
to be rewritten as a signal.

The response is one SSE event carrying three elements: the list and both
forms. They have to move together — opening an edit form also has to clear a
delete that was mid-confirmation — and a text/html response can only replace
one element. The writer is twenty lines rather than re-adding the SDK and the
four modules it brings for a generator we would otherwise never call.

Smoke checks assert the wire format: that these answer with an event stream
carrying all three elements, that the deleted dish is absent from the patched
list, and that a header-less post still redirects.
2026-09-05 23:40:22 +03:00
Esa Kataja f8b908b39e Fix catalog redirects pointing at the old /ruoat
Adding, editing or deleting a dish redirected to /ruoat, which stopped
existing when the tab was renamed to Ruuat. Every one of those actions ended
on a 404. Shipped in v20260905-4.

The rename was done with a scripted replace across views.templ, main.go and
the smoke script; handlers.go was not in the list.

The tests did not catch it because they asserted only that the response was a
303. A redirect to a dead URL is still a 303. They now assert the target.
2026-09-05 23:35:45 +03:00
21 changed files with 618 additions and 635 deletions
+3 -8
View File
@@ -5,18 +5,13 @@
REPO=registry.example.com/you/foodster
TAG=latest
# Shared household password. The app will not start without it.
PASSWORD=changeme
# Hostname Traefik routes to. Kept here rather than in compose.yaml so no
# infrastructure detail is committed.
HOST=foodster.example.com
# The Traefik middleware that authenticates the app. The app itself has no
# login, so this is the whole of its access control — an unset or misspelt
# name takes the router out of service, which is the right way to fail.
AUTH=authelia@docker
# Traefik certificate resolver issuing the TLS certificate for HOST.
CERTRESOLVER=letsencrypt
# Anything other than prod is written into the browser tab title, so a dev
# instance open beside the real one can be told apart.
ENV=prod
-22
View File
@@ -1,22 +0,0 @@
name: check
on:
push:
branches: [dev]
# ponytail: only because Traefik still serves its default self-signed cert for
# git.kessinen.com. Remove once the LE-DNS01-cloudflare runbook has been run.
env:
GIT_SSL_NO_VERIFY: "true"
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- run: make check
-58
View File
@@ -1,58 +0,0 @@
name: release
on:
push:
branches: [main]
# ponytail: only because Traefik still serves its default self-signed cert for
# git.kessinen.com. Remove once the LE-DNS01-cloudflare runbook has been run.
env:
GIT_SSL_NO_VERIFY: "true"
REGISTRY: git.kessinen.com
IMAGE: git.kessinen.com/kessinen/foodster
jobs:
image:
runs-on: ubuntu-latest
steps:
# Full history and tags: the release number is derived by counting the
# tags already cut today.
- uses: actions/checkout@v4
with:
fetch-depth: 0
# The job container is node:22-bookworm and has no docker client. The
# static binary is one file; installing docker.io would pull a daemon
# that is never used, since the build runs against the host's.
- name: Install the docker client
run: |
curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-27.3.1.tgz \
| tar xz --strip-components=1 -C /usr/local/bin docker/docker
docker version --format '{{.Client.Version}}'
- name: Work out the release tag
id: rel
run: |
day=$(date +%Y%m%d)
tag="v$day-$(( $(git tag -l "v$day-*" | wc -l) + 1 ))"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
echo "==> $tag"
- name: Tag the commit
run: |
git tag "${{ steps.rel.outputs.tag }}"
git push origin "${{ steps.rel.outputs.tag }}"
- name: Log in to the registry
run: |
echo "${{ secrets.GITEA_TOKEN }}" \
| docker login "$REGISTRY" -u "${{ gitea.actor }}" --password-stdin
- name: Build and push
run: |
tag="${{ steps.rel.outputs.tag }}"
docker build --platform linux/amd64 --build-arg VERSION="$tag" \
-f Containerfile \
-t "$IMAGE:$tag" -t "$IMAGE:latest" .
docker push "$IMAGE:$tag"
docker push "$IMAGE:latest"
echo "pushed $IMAGE:$tag and :latest - pull it in dockge when ready"
+3
View File
@@ -4,6 +4,9 @@
# Build output
/foodster
# The tag `make image` last built, handed to `make push`.
/.release-tag
# Generated by `templ generate` during the container build.
*_templ.go
-104
View File
@@ -1,104 +0,0 @@
# Contributing
A household project, so this is less a set of rules than a note to whoever
picks it up next — including me in six months.
## Getting set up
```sh
cp .env.example .env # then edit it
make run # http://localhost:8080, tab titled "dev · Foodster"
make # every target, with a one-line description
```
`make check` is the gate: `go vet`, gofmt, unit tests, and `scripts/smoke.sh`,
which drives a real server over HTTP. Run it before every commit.
## Branches
`dev` is where work happens. `main` holds released versions only — it is
protected on the remote and takes no direct pushes, so a release arrives as a
pull request from `dev`, squash-merged.
After a squash merge, reset `dev` onto it or the next pull request will offer
the same commits again:
```sh
git switch main && git pull --ff-only
git switch dev && git reset --hard main
git push --force-with-lease origin dev
```
The release workflow only triggers on `main`, and `main` only moves through a
pull request, so a release can never be built from the wrong branch. Nothing
needs to check for it.
## Commit messages
Conventional Commits — a type, an optional scope, then a short subject in the
imperative.
```
feat(kirjaa): expand the selected day in place
fix: redirect the catalog to /ruuat, not /ruoat
chore(deps): bump the vendored Datastar client
```
| Type | For |
|---|---|
| `feat` | new behaviour someone will notice |
| `fix` | a bug, ideally naming what broke |
| `refactor` | same behaviour, different shape |
| `test` | tests only |
| `docs` | documentation only |
| `build` | Makefile, Containerfile, compose, CI |
| `chore` | anything else: dependencies, seeds, tidying |
**The body matters more than the type.** Explain *why*, and what the
alternative was — the diff already says what changed. If a fix was subtle,
say what made it subtle; if a test caught something, say what. Commits here
are the only design record this project has.
### Release pull requests
Because `main` is squash-merged, a pull request title becomes a commit message
on `main`. A release spans a fix, a feature and some chores at once, so none
of the types above fits it honestly. Use `release:` instead:
```
release: repair the catalog 404 and stop the page jumping
```
`main`'s log is then one line per deployment, which is what that branch is
for, and the pull request body serves as the release notes. No version in the
title — CI creates the CalVer tag after the merge, so it is not known yet.
The types above are for `dev`, where a commit really does do one thing.
## Deploying
The server keeps its own `compose.yaml` and `.env`. Neither is pulled from
here, so a release that renames a variable, adds one, or changes a mount
needs both copied across **in the same deploy** — otherwise the container
comes up against the old names and the app refuses to start.
Anything in this repository that reaches the server by hand belongs in the
release notes, flagged as breaking.
## Things that are easy to get wrong
- **The interface is Finnish.** Code, comments, this file and the PRD are
English. There is no i18n layer and no language switcher.
- **No infrastructure detail is committed** — no hostnames, registry paths or
ports. They live in `.env`, which is gitignored, because the PRD leaves the
door open to publishing this repository.
- **Migrations are immutable once shipped.** A released migration has run on a
live database and will not run again. Add a new numbered file instead.
- **Interactions patch, they do not navigate.** Anything that reloads the page
loses the scroll position, which on a long list is maddening. Links stay
links and forms stay forms so it works without JavaScript; Datastar layers
over them with `data-on:click__prevent` and `data-on:submit__prevent`.
- **A `ponytail:` comment marks a deliberate shortcut** and names its ceiling,
so the next reader can tell a decision from an oversight.
- **Assert what a response does, not just that it responded.** A redirect to a
dead URL is still a 303; that one shipped.
+82 -3
View File
@@ -3,8 +3,18 @@
COMPOSE ?= podman compose
BIN := foodster
PKG := ./cmd/foodster
STATIC := cmd/foodster/static
# Registry coordinates, hostname, TZ. Gitignored.
# What `make image` last built. push reads it rather than re-deriving the tag:
# sorting tags by date is ambiguous when two point at the same commit, and
# re-deriving is what let a parallel make push the wrong one.
TAGFILE := .release-tag
# Vendored Datastar client. Bump, run `make vendor`, commit the result.
DATASTAR_VERSION ?= v1.0.3
SEED ?= seeds/testi.json
# Registry coordinates, shared password and TZ live here. Gitignored.
ifneq (,$(wildcard .env))
include .env
export
@@ -14,7 +24,7 @@ endif
GOFILES = $(shell find . -name '*.go' -not -name '*_templ.go' 2>/dev/null)
.DEFAULT_GOAL := help
.PHONY: help generate build run test smoke check lint fix up down logs clean
.PHONY: help generate build run seed test smoke check lint fix icons vendor image push release up down logs clean
help: ## Show this help
@grep -hE '^[a-zA-Z_-]+:.*## ' $(MAKEFILE_LIST) \
@@ -28,7 +38,10 @@ build: generate ## Build ./foodster
-ldflags="-s -w -X main.version=dev" -o $(BIN) $(PKG)
run: generate ## Run locally on :8080 (database in ./data)
ENV=dev go run $(PKG)
PASSWORD=$${PASSWORD:-dev} ENV=dev go run $(PKG)
seed: ## Import a dish bundle (SEED=seeds/testi.json)
go run $(PKG) -import $(SEED)
test: generate ## Run unit tests
go test ./...
@@ -44,6 +57,21 @@ check: ## Everything that must pass before a commit
@$(MAKE) --no-print-directory smoke
@echo "check: all passed"
icons: ## Rasterise home-screen PNGs from assets/icon.svg and optimise them
rsvg-convert -w 180 -h 180 assets/icon.svg -o $(STATIC)/apple-touch-icon.png
rsvg-convert -w 192 -h 192 assets/icon.svg -o $(STATIC)/icon-192.png
rsvg-convert -w 512 -h 512 assets/icon.svg -o $(STATIC)/icon-512.png
# oxipng -o max alone loses to optipng on the 512; --zopfli wins at every
# size. Slow, but these are three tiny files built by hand.
oxipng -o max --zopfli --quiet \
$(STATIC)/apple-touch-icon.png $(STATIC)/icon-192.png $(STATIC)/icon-512.png
@ls -l $(STATIC)/*.png
vendor: ## Re-download the Datastar client (DATASTAR_VERSION=v1.0.3)
curl -sSfL -o $(STATIC)/datastar.js \
"https://cdn.jsdelivr.net/gh/starfederation/datastar@$(DATASTAR_VERSION)/bundles/datastar.js"
@head -1 $(STATIC)/datastar.js
lint: generate ## go vet, gofmt check, golangci-lint when installed
go vet ./...
@bad=$$(gofmt -l $(GOFILES) 2>/dev/null); \
@@ -56,6 +84,57 @@ fix: ## Format Go and templ sources, tidy go.mod
go tool templ fmt .
go mod tidy
image: ## Build and tag an image as vYYYYMMDD-N. Creates a git tag.
@test -n "$(REPO)" || { echo "set REPO in .env"; exit 1; }
@# A release tag must point into main, or the tag records a commit that
@# was never released.
@branch=$$(git symbolic-ref --short HEAD); \
if [ "$$branch" != "main" ]; then \
echo "releases are cut from main, not $$branch:"; \
echo " git switch main && git merge --ff-only dev"; \
exit 1; \
fi
@day=$$(date +%Y%m%d); \
tag="v$$day-$$(( $$(git tag -l "v$$day-*" | wc -l) + 1 ))"; \
echo "==> $$tag"; \
git tag "$$tag"; \
podman build --platform linux/amd64 --build-arg VERSION="$$tag" \
-t "$(REPO):$$tag" -t "$(REPO):latest" . ; \
echo "$$tag" > $(TAGFILE)
# Pushing reported success while uploading the previous release once, because
# nothing compared what was built against what arrived. So afterwards, ask the
# registry what it actually serves for each tag and fail if it is not the
# image we just built.
push: ## Push the newest tag and :latest, then verify the registry
@test -n "$(REPO)" || { echo "set REPO in .env"; exit 1; }
@test -f $(TAGFILE) || { echo "nothing built - run make image"; exit 1; }; \
tag=$$(cat $(TAGFILE)); \
built=$$(podman image inspect "$(REPO):$$tag" --format '{{.Id}}' 2>/dev/null) || \
{ echo "no local image tagged $$tag - run make image"; exit 1; }; \
podman push "$(REPO):$$tag"; \
podman push "$(REPO):latest"; \
echo "==> verifying $$tag"; \
for ref in "$$tag" latest; do \
podman pull -q "$(REPO):$$ref" >/dev/null 2>&1 || \
{ echo " FAIL $$ref is not in the registry"; exit 1; }; \
served=$$(podman image inspect "$(REPO):$$ref" --format '{{.Id}}'); \
if [ "$$served" != "$$built" ]; then \
echo " FAIL $$ref serves $$served"; \
echo " expected $$built"; \
exit 1; \
fi; \
echo " ok $$ref"; \
done
# Sub-makes, not prerequisites. Under `make -j` — and -j16 is the default on
# at least one machine here — these run concurrently, so push resolves the
# newest tag and uploads :latest before image has finished building and
# tagging. That silently ships the previous release a second time.
release: ## Build, tag and push in one go
@$(MAKE) --no-print-directory image
@$(MAKE) --no-print-directory push
up: ## Start the stack
@mkdir -p data # or the engine creates it root-owned and the app cannot write
$(COMPOSE) up -d
+38 -46
View File
@@ -25,12 +25,12 @@ polished, it may be released as FOSS under MIT.
- No grocery list generation (possible future add-on).
- No per-recipe ingredient tracking — meals are just names.
- No calendar/scheduling with times, reminders, or calendar exports.
- No user accounts, per-person profiles, or permissions *in the app*.
Authentication is the reverse proxy's job (§9).
- No user accounts, per-person profiles, or permissions. A single shared
password gates the whole app (§9).
- No nutrition tracking, calorie counting, or dietary-goal optimization.
- No mobile-native apps. Web only (mobile-friendly responsive is enough).
- No per-user accounts or sessions in the app. It *is* reachable from the
internet (§9, §10), behind Authelia at the proxy.
- No per-user accounts or sessions. The app *is* reachable from the internet
(§9, §10), gated by a single shared password over TLS.
## 4. Delivery stages
@@ -72,9 +72,9 @@ weighting to be meaningful (a few weeks of logged meals).
## 5. Users
A single household. One shared instance, no per-person accounts. Everyone who
gets past Authelia sees and edits the same log; the app draws no distinction
between them.
A single household. One shared instance, no per-person accounts. Anyone on the
home network who knows the shared password can open the app and interact with
it.
The interface is written in **Finnish** — every user of this instance is a
Finnish speaker, so there is no i18n layer and no language switcher. Strings
@@ -350,21 +350,21 @@ build and no asset bundler.
to UTC would shift logged dinners to the wrong calendar day. `time/tzdata`
is imported because the runtime image carries no zoneinfo. All date logic
uses that location explicitly and never `time.Local`.
- **Auth**: none in the app. Every route is served unauthenticated, because
the only client that can reach the app is Traefik, which forwards each
request to **Authelia** first. Sessions, brute-force protection and
multi-factor are configured there once for every service on the host.
Deliberately not reimplemented per app: the earlier in-app HTTP Basic layer
meant two prompts for one door, and the weaker of the two was the one
holding a shared password.
- **Exposure**: served on a public hostname behind Traefik, which terminates
TLS. Two invariants carry the whole security model, and both are asserted
in `compose.yaml`. The router names the Authelia middleware through `AUTH`
— unset or misspelt, Traefik takes the router out of service, so a typo
fails shut. And the container publishes no ports, so it is reachable only
over the shared proxy network; publishing `8080` would expose an
unauthenticated plaintext copy on the host. `/healthz` returns only the
version and is safe to bypass in Authelia for monitoring.
- **Auth**: HTTP Basic with one shared household password read from
`PASSWORD`; the username is ignored. Compared using
`subtle.ConstantTimeCompare` over SHA-256 digests so neither the value nor
its length leaks through timing. `/healthz` is the only route outside auth.
- **Exposure**: the app is served on a public hostname behind Traefik, which
terminates TLS, so Basic credentials are encrypted in transit. A shared
password is therefore the only thing between the internet and the app, and
it is guarded by a per-address rate limiter: five wrong guesses, then one
per ten seconds, answered with `429`. Only requests that actually present
a wrong password spend the allowance — a request with no `Authorization`
header is the normal browser handshake that opens every session.
`X-Forwarded-For` is trusted only when the connection arrived from a
private address, so a direct client cannot forge a new identity per
attempt. None of this substitutes for a strong password; it only removes
brute force as a practical route.
- **Containers**: built with Podman in development, run under Docker Compose
in production. Images are OCI, so one image works with both engines.
@@ -372,27 +372,22 @@ Explicitly *not* React.
## 10. Deployment
Images are built by CI, pushed to a private container registry, then pulled on
the server and run with Docker Compose.
Images are built locally, pushed to a private container registry, then pulled
on the server and run with Docker Compose.
- **Branches**: `main` carries released versions only, so its history is the
deployment history and every release tag points into it. Development happens
on `dev`, and `main` is protected on the remote: it accepts no direct
pushes, so a release arrives as a pull request from `dev`. The release
workflow runs only on `main`, so a release cannot be built from anywhere
else and nothing needs to check for it.
pushes, so a release arrives as a pull request from `dev`. `make image`
additionally refuses to run outside `main` — that one has to be local,
because the tag and the image are made before anything reaches the remote.
- **Versioning**: CalVer `vYYYYMMDD-N`, where `N` is the Nth build of that
day. The release workflow derives `N` by counting the day's existing git
tags, creates the new tag, and bakes the version into the binary through
`-ldflags -X main.version`.
- **CI**: Gitea Actions, workflows in `.gitea/workflows/`. `check.yaml` runs
`make check` on every push to `dev`; `release.yaml` builds and pushes the
image when a pull request merges into `main`. Merging is the release —
there is no local build step.
- **Tooling**: a `Makefile` covers development — `make` on its own lists every
target. Build, test, lint, format and compose commands live there rather
than in loose scripts. Commands run a handful of times a year are written
out in the README instead of earning a target.
day. `make image` derives `N` by counting the day's existing git tags,
creates the new tag, and bakes the version into the binary through
`-ldflags -X main.version`. `make release` builds, tags and pushes.
- **Tooling**: a `Makefile` is the single entry point — `make` on its own
lists every target. Build, test, lint, format, image and compose commands
all live there rather than in loose scripts.
- **Image**: a two-stage `Containerfile`. `golang:1.27-alpine` compiles a
static binary; the runtime stage is `FROM scratch` holding only that
binary, running as UID 65534.
@@ -406,10 +401,8 @@ the server and run with Docker Compose.
`.env.example`):
Names carry no application prefix: the container namespaces them already.
- `REPO` and `TAG` — image coordinates.
- `AUTH` — the Traefik middleware that authenticates the app, e.g.
`authelia@docker`. Required; it is the app's only access control.
- `HOST` and `CERTRESOLVER` — the hostname Traefik matches on and the
resolver that issues its certificate.
- `PASSWORD` — the shared password. Required; the app refuses to start
without it.
- `DB` — database file path, default `./data/foodster.db`. The directory is
created on startup if missing.
- `ENV` — anything but `prod` is prefixed to the browser tab title, so a
@@ -424,16 +417,15 @@ the server and run with Docker Compose.
doing so would put an unencrypted copy of the app on the host, bypassing
the proxy. The hostname lives in `.env` rather than `compose.yaml`, so no
infrastructure detail is committed.
- **Health**: `GET /healthz` returns the build version and nothing else, so it
is safe to exempt in Authelia. There is no Docker `HEALTHCHECK` directive,
because a `scratch` image
- **Health**: `GET /healthz` returns the build version and is exempt from
auth. There is no Docker `HEALTHCHECK` directive, because a `scratch` image
has no shell to run one and `restart: unless-stopped` already covers a dead
process. Adding one would mean giving the binary a `-healthcheck` flag that
calls its own endpoint.
- Pending migrations are applied on app start.
- The Datastar client is vendored at `cmd/foodster/static/datastar.js` and
served from the app's own origin — the SDK ships no browser asset, and a
CDN link would break an offline LAN. The README says how to refresh it; the pinned
CDN link would break an offline LAN. `make vendor` refreshes it; the pinned
version lives in the `Makefile` and in the file's first line.
- No internet exposure; the server binds to the LAN.
+66 -99
View File
@@ -11,35 +11,35 @@ See [PRD.md](PRD.md) for the full specification.
## Status
**Stage 1 — eating history: in use.** The meal catalog and the daily log came
first, because the suggester is worthless until there are a few weeks of real
history to weight against.
**Stage 1 — eating history: in development.** The meal catalog and the daily
log come first, because the suggester is worthless until there are a few
weeks of real history to weight against.
Working:
- **Kirjaa** — log a dinner: pick a dish, tick sides, save. Dishes are grouped
by category, then ordered and sized by how often they are eaten, so the
likely answer is the biggest target. The history sits on the same page
underneath: every day back to the first entry, unlogged days shown as
explicit gaps, and every row opening that day's logger in place. Older days
arrive a window at a time.
- **Kirjaa** — log a dinner: pick a dish, tick sides, save. Dishes are ordered
and sized by how often they are eaten, so the likely answer is the biggest
target. The history sits on the same page underneath: every day back to the
first entry, unlogged days shown as explicit gaps, and every row a link that
loads that day into the logger above it.
- **Ruuat** — add, edit and delete mains and sides, or import a whole bundle
by paste or file upload. Grouped by category and alphabetical inside, since
this is a list you manage rather than one you pick from. Edit and delete are
row icons, and a delete asks first. Deletes are soft, so old log entries
keep showing the dish they used.
- **Search as you type** on both tabs, debounced, patching just the list.
- **Category icons**, not colour dots: shape and colour together, so two marks
are told apart by more than hue.
this is a list you manage rather than one you pick from. Deletes are soft,
so old log entries keep showing the dish they used.
- **Light / dark**, remembered per device, dark by default. The button shows
the theme that is on — moon while dark, sun while light — not the one a
click would bring.
Nothing navigates. Every interaction patches the page through Datastar, so
the scroll position survives; links and forms still work with JavaScript off.
Still to build:
- Live search as you type, and paging for the history and catalog lists once
years of entries make them long. Both via Datastar.
- Category icons instead of plain colour dots — colour and shape together, so
a red blob and a yellow blob are told apart by more than hue.
- Edit and delete as icons in the catalog rows, and a confirmation step before
a delete actually happens.
- A background for the header. Something subtle; the palette gets overhauled
later.
- Stage 2: the seven-meal suggester, which starts once there is history to
weight against.
@@ -55,12 +55,9 @@ One static Go binary. No Node.js, no bundler, no separate database server.
| Interactivity | [Datastar](https://data-star.dev) — signals and DOM patching in one ~11 kB script |
| Styling | hand-written CSS, `light-dark()` for themes |
| Database | SQLite via `modernc.org/sqlite` (pure Go) |
| Auth | none in-app — Authelia, via a Traefik forward-auth middleware |
| Auth | HTTP Basic, one shared household password |
| Runtime image | `FROM scratch` |
Working on it: [CONTRIBUTING.md](CONTRIBUTING.md) — branches, commit messages,
and the conventions that are easy to miss.
## Branches
`main` holds released versions only. Every release tag points at a commit on
@@ -74,20 +71,20 @@ no direct pushes, so a release arrives through a pull request.
git switch dev # where the work happens
# ... commits ...
make check # lint, unit tests, smoke
git push origin dev # CI runs make check too
git push origin dev
tea pr create --base main --head dev # or open it in the forge
# squash-merge the pull request — that is the whole release
# merge the pull request, then:
git switch main && git pull --ff-only
make release # builds, tags vYYYYMMDD-N, pushes the image
git push origin --tags
```
Merging is the release. CI builds the image, tags it `vYYYYMMDD-N` and
`latest`, pushes both to the registry, and creates the matching git tag. There
is nothing to run locally afterwards; pull the new image on the server when
you are ready.
A release tag can therefore never point at a commit that was not released:
the workflow only runs on `main`, and `main` only moves through a pull
request.
`make image` additionally refuses to run from any branch but `main`, so a
release tag can never point at a commit that was not released. That check
lives locally because it has to: tags and images are built before anything
reaches the remote, so protection there cannot catch it.
## Quick start
@@ -102,39 +99,15 @@ make run # http://localhost:8080
make fix gofmt, templ fmt, go mod tidy
make lint go vet, gofmt check, golangci-lint when installed
make test go test ./...
make smoke end-to-end check against a scratch server
make check lint + test + smoke — run before every commit
make build ./foodster
make seed import a dish bundle (SEED=seeds/testi.json)
make vendor re-download the Datastar client
make image build and tag vYYYYMMDD-N (creates a git tag)
make push push the newest tag and :latest
make release image + push
make up/down/logs compose
```
Images are built by CI, not here — see [Deployment](#deployment).
### Occasional commands
Rare enough not to earn a `make` target. Both write into
`cmd/foodster/static/`, and the results are committed.
Re-download the vendored Datastar client after bumping the version:
```sh
curl -sSfL -o cmd/foodster/static/datastar.js \
"https://cdn.jsdelivr.net/gh/starfederation/[email protected]/bundles/datastar.js"
```
Re-rasterise the home-screen icons after editing `assets/icon.svg`:
```sh
cd cmd/foodster/static
rsvg-convert -w 180 -h 180 ../../../assets/icon.svg -o apple-touch-icon.png
rsvg-convert -w 192 -h 192 ../../../assets/icon.svg -o icon-192.png
rsvg-convert -w 512 -h 512 ../../../assets/icon.svg -o icon-512.png
oxipng -o max --zopfli --quiet apple-touch-icon.png icon-192.png icon-512.png
```
`oxipng -o max` on its own loses to optipng on the 512; `--zopfli` wins at
every size. Slow, but these are three tiny files built by hand.
## Importing dishes
The **Ruuat** tab takes a bundle of mains and sides: paste the JSON or upload
@@ -165,7 +138,7 @@ The same importer runs from the command line when you just want to repopulate
a scratch database:
```sh
go run ./cmd/foodster -import seeds/testi.json
make seed # or: SEED=seeds/other.json make seed
```
## Icons
@@ -176,8 +149,12 @@ cannot be transparent and must not change with the theme; they are rasterised
from `assets/icon.svg`, which is opaque and keeps the artwork inside the
central 80% so Android can mask it to any shape.
The PNGs are committed so the build needs no rasterizer. The commands to
regenerate them are under [Occasional commands](#occasional-commands).
```sh
make icons # rsvg-convert, then optipng -o7
```
The PNGs are committed so the build needs no rasterizer. Re-run `make icons`
after editing `assets/icon.svg`.
## Migrations
@@ -196,31 +173,31 @@ Everything is environment variables. `.env` is gitignored; start from
| Variable | Default | Purpose |
|---|---|---|
| `PASSWORD` | *required* | Shared password. The app will not start without it. |
| `DB` | `./data/foodster.db` | SQLite file path; the directory is created if missing. |
| `ENV` | `prod` | Anything else is prefixed to the tab title (`dev · Foodster`). |
| `ADDR` | `:8080` | Listen address. Only useful for a second local instance. |
| `PUID` / `PGID` | `1000` | Host owner of `./data`, for the bind mount. |
| `TZ` | `Europe/Helsinki` | Used for every calendar-day calculation. |
| `REPO` | *required to run* | Image repository, no tag. Used by `compose.yaml`. |
| `TAG` | `latest` | Tag to run under compose. |
| `HOST` | *required to run* | Hostname Traefik routes to. |
| `AUTH` | *required to run* | Traefik middleware that authenticates the app, e.g. `authelia@docker`. |
| `CERTRESOLVER` | *required to run* | Traefik certificate resolver for `HOST`. |
Names carry no prefix: the container gives them their own namespace already.
`PUID`/`PGID` are the exception — `UID` is read-only in bash, so a value set
in `.env` would be silently replaced by the invoking shell's own.
| `REPO` | *required to build* | Image repository, no tag. |
| `TAG` | `latest` | Tag to run under compose. |
| `HOST` | *required to run* | Hostname Traefik routes to. |
Set `TZ` in development too. Under UTC the date rolls over three hours late,
which is exactly when dinner gets logged.
## Deployment
Images are built by CI when a pull request merges into `main`, and run under
Docker Compose on a LAN server. They are OCI images, so either engine works.
Images are built with Podman and run under Docker Compose on a LAN server.
They are OCI images, so either engine works.
```sh
# on the server, once CI reports the build finished:
make release # build, tag, push
# on the server:
docker compose pull && docker compose up -d
```
@@ -229,15 +206,8 @@ running version is served at `GET /healthz`, which is the one route outside
authentication.
There is no database container. SQLite lives in `./data`, bind-mounted into
the container, so you can inspect the file with any sqlite client without
going through the engine. Back it up with
```sh
sqlite3 data/foodster.db ".backup data/foodster-$(date +%F).db"
```
rather than copying the directory: the database runs in WAL mode, and a plain
copy of a live database can catch the `.db` and its `-wal` mid-write.
the container, so a backup is `cp -r data` and you can inspect the file with
any sqlite client without going through the engine.
That directory must exist and be owned by the user compose runs as — `make up`
creates it, and `PUID`/`PGID` in `.env` tell the container who
@@ -255,27 +225,24 @@ docker compose restart
## Security
**The app has no authentication of its own.** It trusts every request it
receives, because the only thing that can reach it is Traefik, and Traefik
hands each request to Authelia first. Access control, sessions, brute-force
protection and multi-factor all live there, where they are configured once
for every service on the host instead of reimplemented per app.
Access is a single shared password over HTTP Basic — no accounts, no
sessions. Credentials are compared in constant time over SHA-256 digests, so
neither the password nor its length leaks through timing.
Two things make that safe, and both must hold:
The app is served on a public hostname behind Traefik, which terminates TLS,
so the credentials are encrypted in transit. That leaves the password as the
only thing between the internet and the app, so wrong guesses are rate
limited per client address: five in a burst, then one per ten seconds,
answered with `429`. Requests carrying no `Authorization` header are not
charged — that is the handshake every browser session begins with, and
counting it would lock the household out for simply opening the app.
- **`AUTH` names the Authelia middleware** on the router. It is the whole of
the app's access control. Traefik takes a router out of service when its
middleware does not resolve, so a typo fails shut rather than open.
- **The container publishes no ports.** It is reachable only over the shared
`traefik` network. Publishing `8080` would put an unauthenticated,
unencrypted copy of the app on the host and defeat both of the above.
`X-Forwarded-For` is trusted only when the connection came from a private
address, meaning it arrived through the proxy. A client connecting directly
could otherwise forge a new address per attempt and skip the limiter.
`/healthz` returns nothing but the version, so it is safe to bypass in
Authelia if a monitor needs to poll it from outside.
Earlier versions carried HTTP Basic auth and a per-IP guess limiter. Both
were removed once Authelia was in front: two prompts for one door, and the
weaker of the two was the one holding a shared password.
**None of this replaces a strong `PASSWORD`.** Rate limiting removes
brute force as a practical route; it does not make a guessable password safe.
## Mockups
+1 -1
View File
@@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512"
role="img" aria-label="Foodster">
<!-- Source for the home-screen PNGs; the README says how to rasterise it.
<!-- Source for the home-screen PNGs; `make icons` rasterises it.
Unlike favicon.svg this one is opaque and fixed-colour: a home screen
icon cannot be transparent and must not change with the system theme.
The bowl sits inside the central 80% so Android can mask it to any

Before

Width:  |  Height:  |  Size: 927 B

After

Width:  |  Height:  |  Size: 918 B

+8 -13
View File
@@ -60,19 +60,12 @@ func render(w http.ResponseWriter, r *http.Request, c templ.Component) {
// there is nothing to write down for a dinner that has not happened, and a
// stray entry dated next year would sit at the top of the history forever.
// Every read and write goes through here, so the clamp covers them all.
//
// The past is clamped too, at maxHistoryDays. The day list runs unbroken from
// today down to the selected day, so a picker set to 1994 would ask for eleven
// thousand rows. Same ceiling ?paivat= already has.
func (a *app) date(r *http.Request) time.Time {
now := today(a.loc)
if raw := r.FormValue("pvm"); raw != "" {
if d, err := time.ParseInLocation(dateLayout, raw, a.loc); err == nil {
switch floor := now.AddDate(0, 0, -maxHistoryDays+1); {
case d.After(now):
if d.After(now) {
return now
case d.Before(floor):
return floor
}
return d
}
@@ -212,13 +205,15 @@ func (a *app) buildLog(r *http.Request, o logOptions) logView {
// list underneath the tap.
func (a *app) loadDays(r *http.Request, v *logView) {
v.HistoryDays = historyWindow(r)
v.HistoryMore = v.HistoryDays + historyDays
// The window has to reach the selected day, or it would have nowhere to
// expand. history() takes it as a floor rather than the caller inflating
// the day count, because the window also truncates at the first entry ever
// logged — and a day older than that still has to be loggable.
page, err := history(a.db, a.loc, v.Today, v.HistoryDays, v.Date)
// expand.
if reach := int(v.Today.Sub(v.Date).Hours()/24) + 1; reach > v.HistoryDays {
v.HistoryDays = min(reach, maxHistoryDays)
}
v.HistoryMore = v.HistoryDays + historyDays
page, err := history(a.db, a.loc, v.Today, v.HistoryDays)
if err != nil {
log.Printf("history: %v", err)
}
+54 -18
View File
@@ -7,6 +7,8 @@ package main
import (
"cmp"
"context"
"crypto/sha256"
"crypto/subtle"
"database/sql"
"embed"
"errors"
@@ -30,7 +32,7 @@ import (
//go:embed static
var staticFS embed.FS
// version is replaced at build time with the CalVer tag by the release workflow.
// version is replaced at build time with the CalVer tag (see `make image`).
var version = "dev"
// envTag marks the browser tab of anything that is not production, so a dev
@@ -74,11 +76,16 @@ func run() error {
}
defer db.Close()
// Importing is an offline chore: no server started, nothing to serve.
// Importing is an offline chore: no password needed, no server started.
if *importPath != "" {
return runImport(db, *importPath)
}
password := os.Getenv("PASSWORD")
if password == "" {
return errors.New("PASSWORD is not set")
}
// Fail rather than fall back to UTC: a silently wrong zone shifts logged
// dinners onto the wrong calendar day, which is invisible until the
// history is already corrupt.
@@ -93,15 +100,10 @@ func run() error {
// local instance can pick another port.
addr := cmp.Or(os.Getenv("ADDR"), listenAddr)
// WriteTimeout and IdleTimeout matter more than they look: the pool holds
// exactly one database connection, so a reader stalling on a long history
// response blocks every other request behind it.
srv := &http.Server{
Addr: addr,
Handler: routes(db, loc),
Handler: routes(db, loc, password),
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
@@ -161,11 +163,7 @@ func openDB(path string) (*sql.DB, error) {
return db, nil
}
// routes serves the app unauthenticated. Access control is the reverse proxy's
// job: Traefik forwards every request to Authelia before it reaches here, so a
// second password in front of it only ever meant two prompts for one door. The
// container publishes no ports, so nothing but the proxy can reach it.
func routes(db *sql.DB, loc *time.Location) http.Handler {
func routes(db *sql.DB, loc *time.Location, password string) http.Handler {
// Go's mime table has no entry for .webmanifest, and a manifest served as
// octet-stream is ignored by the browser.
_ = mime.AddExtensionType(".webmanifest", "application/manifest+json")
@@ -188,13 +186,51 @@ func routes(db *sql.DB, loc *time.Location) http.Handler {
mux.HandleFunc("POST /ruuat/poista", a.deleteDish)
mux.HandleFunc("POST /ruuat/tuonti", a.importDishes)
// /healthz is an ordinary route now that the app has no auth of its own.
// It reveals only the version, so an Authelia bypass rule for it is safe if
// a monitor needs to poll from outside the container network.
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
// /healthz stays outside auth so a monitor or reverse proxy can reach it.
root := http.NewServeMux()
root.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, version)
})
return mux
root.Handle("/", auth(password, mux))
return root
}
// auth gates everything behind one shared household password. There are no
// accounts, so the username is ignored (PRD §9).
func auth(password string, next http.Handler) http.Handler {
want := sha256.Sum256([]byte(password))
guesses := newThrottle()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, given, ok := r.BasicAuth()
// A request with no Authorization header is the normal browser
// handshake, not a guess: every session opens with one. Challenge it
// without spending the address's allowance.
if !ok {
challenge(w)
return
}
// Hashing first keeps the comparison a fixed length, so neither the
// password nor its length leaks through timing.
got := sha256.Sum256([]byte(given))
if subtle.ConstantTimeCompare(got[:], want[:]) != 1 {
if !guesses.allow(clientIP(r)) {
http.Error(w, "Liikaa yrityksiä.", http.StatusTooManyRequests)
return
}
challenge(w)
return
}
next.ServeHTTP(w, r)
})
}
func challenge(w http.ResponseWriter) {
w.Header().Set("WWW-Authenticate", `Basic realm="Foodster", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
// today is the current calendar day in the configured location, truncated to
+48 -8
View File
@@ -306,23 +306,63 @@ func TestDuplicateNamesAreCaseInsensitive(t *testing.T) {
}
}
// The app carries no authentication of its own — Authelia in front of Traefik
// does that — so the only thing left to assert is that every route answers
// without credentials. A 401 from here would mean auth crept back in.
func TestRoutesNeedNoCredentials(t *testing.T) {
func TestAuth(t *testing.T) {
handler := auth("hunter2", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot) // proves we reached the wrapped handler
}))
cases := []struct {
name string
user string
pass string
withAuth bool
want int
}{
{"correct password", "", "hunter2", true, http.StatusTeapot},
{"username is ignored", "anyone", "hunter2", true, http.StatusTeapot},
{"wrong password", "", "wrong", true, http.StatusUnauthorized},
{"empty password", "", "", true, http.StatusUnauthorized},
{"no credentials", "", "", false, http.StatusUnauthorized},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
if c.withAuth {
r.SetBasicAuth(c.user, c.pass)
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != c.want {
t.Errorf("status = %d, want %d", w.Code, c.want)
}
if c.want == http.StatusUnauthorized && w.Header().Get("WWW-Authenticate") == "" {
t.Error("401 without a WWW-Authenticate header; the browser will not prompt")
}
})
}
}
func TestHealthzSkipsAuth(t *testing.T) {
db, err := openDB(t.TempDir() + "/test.db")
if err != nil {
t.Fatalf("openDB: %v", err)
}
defer db.Close()
h := routes(db, time.UTC)
h := routes(db, time.UTC, "hunter2")
for _, path := range []string{"/healthz", "/", "/ruuat"} {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/healthz", nil))
if w.Code != http.StatusOK {
t.Errorf("GET %s = %d, want 200", path, w.Code)
t.Errorf("/healthz without credentials = %d, want 200", w.Code)
}
// Everything else must still be gated.
w = httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/", nil))
if w.Code != http.StatusUnauthorized {
t.Errorf("/ without credentials = %d, want 401", w.Code)
}
}
+6 -95
View File
@@ -305,8 +305,7 @@ func updateMain(db *sql.DB, id int64, name string, categories []string, hasSides
defer tx.Rollback()
if _, err := tx.Exec(
`UPDATE main_dishes SET name = ?, has_sides = ?
WHERE id = ? AND deleted_at IS NULL AND special = 0`,
`UPDATE main_dishes SET name = ?, has_sides = ? WHERE id = ? AND deleted_at IS NULL`,
name, hasSides, id,
); err != nil {
return taken(err)
@@ -346,14 +345,9 @@ func updateSide(db *sql.DB, id int64, name string) error {
// Soft delete: the row stays so historical log entries keep resolving their
// names, but it disappears from the catalog and every picker (PRD §6).
//
// `special = 0` here and in updateMain: the catalog never lists Tähteet, so
// the UI cannot reach it, but a stale tab or a hand-made POST could — and
// removing it would take away the row migration 0002 guarantees.
func softDeleteMain(db *sql.DB, id int64) error {
_, err := db.Exec(
`UPDATE main_dishes SET deleted_at = datetime('now')
WHERE id = ? AND special = 0`, id)
`UPDATE main_dishes SET deleted_at = datetime('now') WHERE id = ?`, id)
return err
}
@@ -438,12 +432,7 @@ type HistoryPage struct {
// history walks back day by day from a given day, so a day nobody wrote down
// shows up as an explicit gap rather than silently missing. It stops at the
// first entry ever recorded — before that there is no history to be missing.
//
// reach names a day that must appear whatever the window says. The log board
// opens inside the selected day's row, so a date picked from before the first
// entry ever logged used to render nothing at all: no row, no board, no way to
// log it. Pass the zero time to ask for the plain window.
func history(db *sql.DB, loc *time.Location, from time.Time, days int, reach time.Time) (HistoryPage, error) {
func history(db *sql.DB, loc *time.Location, from time.Time, days int) (HistoryPage, error) {
var first sql.NullString
if err := db.QueryRow(`SELECT min(date) FROM meal_log`).Scan(&first); err != nil {
if err == sql.ErrNoRows {
@@ -468,92 +457,14 @@ func history(db *sql.DB, loc *time.Location, from time.Time, days int, reach tim
oldest = firstDate
page.More = false
}
if !reach.IsZero() && reach.Before(oldest) {
oldest = reach
page.More = firstDate.Before(oldest)
}
page.Next = oldest.AddDate(0, 0, -1)
entries, err := entriesBetween(db, oldest, from)
for d := from; !d.Before(oldest); d = d.AddDate(0, 0, -1) {
entry, err := entryFor(db, d)
if err != nil {
return HistoryPage{}, err
}
for d := from; !d.Before(oldest); d = d.AddDate(0, 0, -1) {
row := HistoryRow{Date: d}
if e := entries[d.Format(dateLayout)]; e != nil {
e.Date = d
row.Entry = e
}
page.Rows = append(page.Rows, row)
page.Rows = append(page.Rows, HistoryRow{Date: d, Entry: entry})
}
return page, nil
}
// entriesBetween loads every logged day in the inclusive range, keyed by
// stored date string, in two queries rather than two per day. The widest
// window a URL can ask for is five years, which day-at-a-time made 3,600 round
// trips through a pool of exactly one connection.
func entriesBetween(db *sql.DB, from, to time.Time) (map[string]*Entry, error) {
lo, hi := from.Format(dateLayout), to.Format(dateLayout)
rows, err := db.Query(`
SELECT l.id, l.date, m.id, m.name, m.has_sides,
coalesce((SELECT group_concat(c.category)
FROM main_dish_categories c
WHERE c.main_dish_id = m.id), '')
FROM meal_log l
JOIN main_dishes m ON m.id = l.main_dish_id
WHERE l.date BETWEEN ? AND ?`, lo, hi)
if err != nil {
return nil, err
}
defer rows.Close()
byDate := map[string]*Entry{}
byLog := map[int64]*Entry{}
for rows.Next() {
var logID int64
var date, cats string
var e Entry
if err := rows.Scan(
&logID, &date, &e.Main.ID, &e.Main.Name, &e.Main.HasSides, &cats,
); err != nil {
return nil, err
}
if cats != "" {
e.Main.Categories = strings.Split(cats, ",")
}
byDate[date] = &e
byLog[logID] = &e
}
if err := rows.Err(); err != nil {
return nil, err
}
if len(byLog) == 0 {
return byDate, nil
}
sides, err := db.Query(`
SELECT ls.meal_log_id, s.id, s.name
FROM meal_log_sides ls
JOIN side_dishes s ON s.id = ls.side_dish_id
JOIN meal_log l ON l.id = ls.meal_log_id
WHERE l.date BETWEEN ? AND ?
ORDER BY s.name`, lo, hi)
if err != nil {
return nil, err
}
defer sides.Close()
for sides.Next() {
var logID int64
var s Side
if err := sides.Scan(&logID, &s.ID, &s.Name); err != nil {
return nil, err
}
if e := byLog[logID]; e != nil {
e.Sides = append(e.Sides, s)
}
}
return byDate, sides.Err()
}
+4 -65
View File
@@ -235,7 +235,7 @@ func TestHistoryMarksUnloggedDaysAsGaps(t *testing.T) {
t.Fatalf("save -3: %v", err)
}
page, err := history(h.db, loc, now, 60, time.Time{})
page, err := history(h.db, loc, now, 60)
if err != nil {
t.Fatalf("history: %v", err)
}
@@ -271,7 +271,7 @@ func TestHistoryPagesInWindows(t *testing.T) {
t.Fatalf("save -9: %v", err)
}
first, err := history(h.db, loc, now, 5, time.Time{})
first, err := history(h.db, loc, now, 5)
if err != nil {
t.Fatalf("first window: %v", err)
}
@@ -286,7 +286,7 @@ func TestHistoryPagesInWindows(t *testing.T) {
}
// The windows must meet exactly: no day repeated, none skipped.
second, err := history(h.db, loc, first.Next, 5, time.Time{})
second, err := history(h.db, loc, first.Next, 5)
if err != nil {
t.Fatalf("second window: %v", err)
}
@@ -305,7 +305,7 @@ func TestHistoryPagesInWindows(t *testing.T) {
func TestHistoryEmptyWithoutEntries(t *testing.T) {
h := seeded(t)
page, err := history(h.db, time.UTC, today(time.UTC), 60, time.Time{})
page, err := history(h.db, time.UTC, today(time.UTC), 60)
if err != nil {
t.Fatalf("history: %v", err)
}
@@ -316,64 +316,3 @@ func TestHistoryEmptyWithoutEntries(t *testing.T) {
t.Error("More is set although there is no history at all")
}
}
// A date picked from before the first entry ever logged used to fall outside
// the window entirely: no row, so the log board had nothing to open in and the
// day could not be filled in at all.
func TestHistoryReachesDaysOlderThanTheFirstEntry(t *testing.T) {
h := seeded(t)
loc := time.UTC
now := today(loc)
if err := saveEntry(h.db, now, h.mainNamed(t, "Lohikeitto"), nil); err != nil {
t.Fatalf("save today: %v", err)
}
want := now.AddDate(0, 0, -100)
page, err := history(h.db, loc, now, 30, want)
if err != nil {
t.Fatalf("history: %v", err)
}
if len(page.Rows) != 101 {
t.Fatalf("%d rows, want 101 (today back to the selected day)", len(page.Rows))
}
last := page.Rows[len(page.Rows)-1]
if !last.Date.Equal(want) {
t.Errorf("last row is %s, want the selected %s",
last.Date.Format(dateLayout), want.Format(dateLayout))
}
if page.More {
t.Error("More is set although the window reached past the oldest entry")
}
}
// The sides of every day come back in one query now; each still has to land on
// its own day.
func TestHistoryKeepsSidesWithTheirOwnDay(t *testing.T) {
h := seeded(t)
loc := time.UTC
now := today(loc)
muusi := h.sideNamed(t, "Perunamuusi")
riisi := h.sideNamed(t, "Riisi")
if err := saveEntry(h.db, now, h.mainNamed(t, "Lohikeitto"), []int64{muusi}); err != nil {
t.Fatalf("save today: %v", err)
}
if err := saveEntry(h.db, now.AddDate(0, 0, -1), h.mainNamed(t, "Lihapullat"), []int64{riisi}); err != nil {
t.Fatalf("save -1: %v", err)
}
page, err := history(h.db, loc, now, 30, time.Time{})
if err != nil {
t.Fatalf("history: %v", err)
}
if len(page.Rows) != 2 {
t.Fatalf("%d rows, want 2", len(page.Rows))
}
for i, want := range []string{"Perunamuusi", "Riisi"} {
got := page.Rows[i].Entry
if got == nil || len(got.Sides) != 1 || got.Sides[0].Name != want {
t.Errorf("row %d sides = %+v, want just %s", i, got.Sides, want)
}
}
}
+111
View File
@@ -0,0 +1,111 @@
package main
import (
"net"
"net/http"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
)
// The app is reachable from the internet, so a shared password needs more
// than a sleep in front of it. These allow a family fumbling the password a
// handful of quick retries, then roughly six a minute — useless for guessing,
// unnoticeable to anyone who knows it.
//
// This buys time; it is not the defence. A strong password is.
const (
guessBurst = 5
guessInterval = 10 * time.Second
// Bounds on the per-IP table, so a spray across many addresses cannot
// grow it without limit.
throttleMaxEntries = 4096
throttleIdle = 15 * time.Minute
)
type visitor struct {
limiter *rate.Limiter
seen time.Time
}
// throttle rate-limits failed password attempts per client address.
//
// ponytail: one mutex over one map. At household traffic this will never be
// contended; shard it if that ever stops being true.
type throttle struct {
mu sync.Mutex
visitors map[string]*visitor
}
func newThrottle() *throttle {
return &throttle{visitors: make(map[string]*visitor)}
}
// allow reports whether another wrong guess from this address is permitted.
func (t *throttle) allow(ip string) bool {
now := time.Now()
t.mu.Lock()
defer t.mu.Unlock()
if len(t.visitors) >= throttleMaxEntries {
t.pruneLocked(now)
}
v := t.visitors[ip]
if v == nil {
v = &visitor{limiter: rate.NewLimiter(rate.Every(guessInterval), guessBurst)}
t.visitors[ip] = v
}
v.seen = now
return v.limiter.Allow()
}
func (t *throttle) pruneLocked(now time.Time) {
for ip, v := range t.visitors {
if now.Sub(v.seen) > throttleIdle {
delete(t.visitors, ip)
}
}
// Still full of live entries: a spray is in progress. Drop the lot rather
// than grow without bound. Everyone gets a fresh allowance, which is the
// safe direction to fail — the password is still required.
if len(t.visitors) >= throttleMaxEntries {
clear(t.visitors)
}
}
// clientIP resolves the address to rate-limit against.
//
// X-Forwarded-For is only believed when the connection itself came from a
// private address, meaning it arrived through the reverse proxy on the
// container network. A client connecting directly could otherwise forge a
// fresh address on every attempt and walk straight past the limiter.
func clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
ip := net.ParseIP(host)
if ip == nil || !(ip.IsPrivate() || ip.IsLoopback()) {
return host
}
forwarded := r.Header.Get("X-Forwarded-For")
if forwarded == "" {
return host
}
// The nearest proxy appends the address it saw, so the last entry is the
// trustworthy one; anything before it was supplied by the client.
parts := strings.Split(forwarded, ",")
last := strings.TrimSpace(parts[len(parts)-1])
if net.ParseIP(last) == nil {
return host
}
return last
}
+110
View File
@@ -0,0 +1,110 @@
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestThrottleBlocksRepeatedGuesses(t *testing.T) {
th := newThrottle()
for i := 0; i < guessBurst; i++ {
if !th.allow("198.51.100.7") {
t.Fatalf("guess %d refused inside the burst", i+1)
}
}
if th.allow("198.51.100.7") {
t.Error("guess allowed past the burst")
}
// A different address has its own allowance.
if !th.allow("198.51.100.8") {
t.Error("a second address was blocked by the first one's guesses")
}
}
func TestClientIPIgnoresForwardedHeaderFromDirectClients(t *testing.T) {
// Connecting straight from the internet: X-Forwarded-For is attacker
// input, so a forged value must not create a fresh rate-limit bucket.
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "203.0.113.9:44321"
r.Header.Set("X-Forwarded-For", "1.2.3.4")
if got := clientIP(r); got != "203.0.113.9" {
t.Errorf("clientIP = %q, want the real peer 203.0.113.9", got)
}
}
func TestClientIPTakesLastForwardedEntryBehindProxy(t *testing.T) {
// Arriving through Traefik on the container network. The proxy appends
// the address it saw, so the last entry is the trustworthy one and the
// forged entry in front of it must be ignored.
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "172.18.0.4:53000"
r.Header.Set("X-Forwarded-For", "1.2.3.4, 198.51.100.22")
if got := clientIP(r); got != "198.51.100.22" {
t.Errorf("clientIP = %q, want 198.51.100.22", got)
}
}
func TestClientIPFallsBackWhenNoForwardedHeader(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "172.18.0.4:53000"
if got := clientIP(r); got != "172.18.0.4" {
t.Errorf("clientIP = %q, want 172.18.0.4", got)
}
}
func TestAuthRateLimitsWrongPasswords(t *testing.T) {
handler := auth("hunter2", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot)
}))
send := func(pass string) int {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "203.0.113.5:40000"
r.SetBasicAuth("", pass)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
return w.Code
}
for i := 0; i < guessBurst; i++ {
if code := send("wrong"); code != http.StatusUnauthorized {
t.Fatalf("guess %d returned %d, want 401", i+1, code)
}
}
if code := send("wrong"); code != http.StatusTooManyRequests {
t.Errorf("guess past the burst returned %d, want 429", code)
}
}
func TestAuthDoesNotSpendAllowanceOnTheBrowserHandshake(t *testing.T) {
handler := auth("hunter2", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot)
}))
// Every session opens with a credential-less request. Charging those
// would lock a family out by simply opening the app a few times.
for i := 0; i < guessBurst*4; i++ {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "203.0.113.6:40000"
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != http.StatusUnauthorized {
t.Fatalf("handshake %d returned %d, want 401", i+1, w.Code)
}
}
// The correct password still works afterwards.
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "203.0.113.6:40000"
r.SetBasicAuth("", "hunter2")
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != http.StatusTeapot {
t.Errorf("correct password returned %d, want the wrapped handler", w.Code)
}
}
+2 -3
View File
@@ -143,9 +143,8 @@ templ page(title, current string) {
<title>{ pageTitle(title) }</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml"/>
<link rel="apple-touch-icon" href="/static/apple-touch-icon.png"/>
<!-- use-credentials: the manifest fetch is anonymous by default, so
behind Authelia it would be redirected to the login page and
the manifest quietly ignored. -->
<!-- use-credentials: the manifest is fetched behind Basic auth and
would otherwise come back 401 and be ignored. -->
<link rel="manifest" href="/static/manifest.webmanifest" crossorigin="use-credentials"/>
<link rel="stylesheet" href="/static/app.css"/>
<!-- Not deferred: it applies the stored theme before first paint. -->
+3 -9
View File
@@ -15,25 +15,19 @@ services:
- ./data:/data
environment:
PASSWORD: ${PASSWORD:?set PASSWORD in .env}
DB: /data/foodster.db
ENV: ${ENV:-prod}
TZ: ${TZ:-Europe/Helsinki}
# No published ports: Traefik reaches the container over the shared
# network. Publishing 8080 as well would put an unencrypted copy of the
# app on the host, bypassing TLS — and, now that the app has no login of
# its own, bypassing authentication entirely.
#
# The middleware is the only thing standing in front of the app. If AUTH
# is unset or names a middleware Traefik does not know, Traefik takes the
# router out of service rather than serving it open, so a typo fails shut.
# app on the host, bypassing TLS.
labels:
- traefik.enable=true
- traefik.http.routers.foodster.entrypoints=websecure
- traefik.http.routers.foodster.rule=Host(`${HOST:?set HOST in .env}`)
# Naming a resolver implies tls=true, so this is one label, not two.
- traefik.http.routers.foodster.tls.certresolver=${CERTRESOLVER:?set CERTRESOLVER in .env}
- traefik.http.routers.foodster.middlewares=${AUTH:?set AUTH in .env, e.g. authelia@docker}
- traefik.http.routers.foodster.tls=true
- traefik.http.services.foodster.loadbalancer.server.port=8080
- traefik.docker.network=traefik
networks:
+1
View File
@@ -6,6 +6,7 @@ tool github.com/a-h/templ/cmd/templ
require (
github.com/a-h/templ v0.3.1020
golang.org/x/time v0.15.0
modernc.org/sqlite v1.58.0
)
+2
View File
@@ -50,6 +50,8 @@ golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+72 -79
View File
@@ -1,10 +1,7 @@
#!/bin/sh
# End-to-end check of a running Foodster: static assets, the logger and the
# bundle import flow. Builds its own binary, uses a scratch database and a
# spare port, and cleans up after itself, so it never touches a real instance.
#
# There is nothing to authenticate as: the app is served behind Authelia and
# has no login of its own.
# End-to-end check of a running Foodster: auth, static assets and the bundle
# import flow. Builds its own binary, uses a scratch database and a spare
# port, and cleans up after itself, so it never touches a real instance.
#
# Run it with `make smoke`.
@@ -13,18 +10,13 @@ set -eu
cd "$(dirname "$0")/.."
addr=127.0.0.1:8099
# Dates are relative, never literal. A hardcoded one turns into "some day in
# the past" at the next midnight, and the assertions quietly start meaning
# something else.
d0=$(date +%F)
d1=$(date -d yesterday +%F)
pass=smoke
tmp=$(mktemp -d)
trap 'kill ${srv:-0} 2>/dev/null || true; rm -rf "$tmp"' EXIT
go build -o "$tmp/foodster" ./cmd/foodster
DB="$tmp/smoke.db" ADDR="$addr" \
PASSWORD="$pass" DB="$tmp/smoke.db" ADDR="$addr" \
"$tmp/foodster" >"$tmp/server.log" 2>&1 &
srv=$!
@@ -63,19 +55,22 @@ refute() {
echo "smoke: http://$addr"
check "healthz answers" \
check "unauthenticated request is refused" \
"$(curl -s -o /dev/null -w '%{http_code}' "http://$addr/")" "401"
check "healthz needs no password" \
"$(curl -s -o /dev/null -w '%{http_code}' "http://$addr/healthz")" "200"
check "datastar client is served" \
"$(curl -s -o /dev/null -w '%{http_code}' "http://$addr/static/datastar.js")" "200"
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" "http://$addr/static/datastar.js")" "200"
check "favicon is served" \
"$(curl -s -o /dev/null -w '%{http_code}' "http://$addr/static/favicon.svg")" "200"
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" "http://$addr/static/favicon.svg")" "200"
check "theme script is served" \
"$(curl -s -o /dev/null -w '%{http_code}' "http://$addr/static/theme.js")" "200"
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" "http://$addr/static/theme.js")" "200"
home=$(curl -s "http://$addr/")
home=$(curl -s -u ":$pass" "http://$addr/")
check "the header carries the brand" "$home" "Foodster"
# ENV is unset here, so this instance is production and unmarked.
check "production tabs are not tagged" "$home" "<title>Foodster</title>"
@@ -84,47 +79,47 @@ check "the theme toggle is present" "$home" "data-theme-toggle"
check "both theme icons ship so CSS can pick one" "$home" 'class="i-moon"'
check "apple touch icon is served" \
"$(curl -s -o /dev/null -w '%{http_code}' "http://$addr/static/apple-touch-icon.png")" "200"
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" "http://$addr/static/apple-touch-icon.png")" "200"
# A manifest served as octet-stream is silently ignored by the browser.
check "manifest has the right content type" \
"$(curl -s -o /dev/null -w '%{content_type}' "http://$addr/static/manifest.webmanifest")" \
"$(curl -s -o /dev/null -w '%{content_type}' -u ":$pass" "http://$addr/static/manifest.webmanifest")" \
"application/manifest+json"
check "catalog starts empty" \
"$(curl -s "http://$addr/ruuat")" "0 pääruokaa"
"$(curl -s -u ":$pass" "http://$addr/ruuat")" "0 pääruokaa"
out=$(curl -s -F "tiedosto=@seeds/testi.json" "http://$addr/ruuat/tuonti")
out=$(curl -s -u ":$pass" -F "tiedosto=@seeds/testi.json" "http://$addr/ruuat/tuonti")
check "file upload imports the seed bundle" "$out" "Lisätty 22, ohitettu 0"
check "counts update after import" "$out" "16 pääruokaa, 6 lisuketta"
check "re-import refuses duplicates" \
"$(curl -s -F "tiedosto=@seeds/testi.json" "http://$addr/ruuat/tuonti")" \
"$(curl -s -u ":$pass" -F "tiedosto=@seeds/testi.json" "http://$addr/ruuat/tuonti")" \
"jo listalla"
check "pasted JSON imports" \
"$(curl -s -F 'json={"mains":[],"sides":[{"name":"Perunasalaatti"}]}' \
"$(curl -s -u ":$pass" -F 'json={"mains":[],"sides":[{"name":"Perunasalaatti"}]}' \
"http://$addr/ruuat/tuonti")" "Lisätty 1"
check "unknown category is reported" \
"$(curl -s -F 'json={"mains":[{"name":"Rikki","categories":["kana"]}],"sides":[]}' \
"$(curl -s -u ":$pass" -F 'json={"mains":[{"name":"Rikki","categories":["kana"]}],"sides":[]}' \
"http://$addr/ruuat/tuonti")" "tuntematon kategoria"
check "empty submit is explained" \
"$(curl -s -F 'json=' "http://$addr/ruuat/tuonti")" "Ei tuotavaa"
"$(curl -s -u ":$pass" -F 'json=' "http://$addr/ruuat/tuonti")" "Ei tuotavaa"
check "malformed JSON is explained" \
"$(curl -s -F 'json={nope' "http://$addr/ruuat/tuonti")" "JSON ei kelpaa"
"$(curl -s -u ":$pass" -F 'json={nope' "http://$addr/ruuat/tuonti")" "JSON ei kelpaa"
# ---- the log flow, against the dishes imported above --------------------
board=$(curl -s "http://$addr/")
board=$(curl -s -u ":$pass" "http://$addr/")
check "board lists imported dishes" "$board" "Lihapullat"
# Tähteet is loggable but is not food: on the board, never in the catalog.
check "leftovers are on the board" "$board" "Tähteet"
refute "leftovers are not in the catalog" \
"$(curl -s "http://$addr/ruuat")" "Tähteet"
"$(curl -s -u ":$pass" "http://$addr/ruuat")" "Tähteet"
# Pull a real dish id out of the board rather than assuming one.
ruoka=$(printf '%s' "$board" | grep -o 'ruoka=[0-9]*' | head -n1 | cut -d= -f2)
@@ -135,147 +130,145 @@ if [ -z "$ruoka" ]; then
fi
check "picking a dish opens the sides step" \
"$(curl -s "http://$addr/?ruoka=$ruoka")" "Tallenna"
"$(curl -s -u ":$pass" "http://$addr/?ruoka=$ruoka")" "Tallenna"
check "saving redirects back to the day" \
"$(curl -s -o /dev/null -w '%{http_code}' \
-d "pvm=$d0&ruoka=$ruoka" "http://$addr/kirjaa")" "303"
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \
-d "pvm=2026-09-05&ruoka=$ruoka" "http://$addr/kirjaa")" "303"
check "the saved day shows what was eaten" \
"$(curl -s "http://$addr/?pvm=$d0")" "kirjattu"
"$(curl -s -u ":$pass" "http://$addr/?pvm=2026-09-05")" "kirjattu"
# The selected day expands inside the list rather than in a panel above it,
# so the rows below do not shift when one is tapped.
day=$(curl -s "http://$addr/?pvm=$d0")
day=$(curl -s -u ":$pass" "http://$addr/?pvm=2026-09-05")
check "the selected day expands in place" "$day" 'class="open"'
check "and stays in the list rather than being lifted out" "$day" "kirjattu"
# ---- the day list patches in place instead of navigating ----------------
dayp=$(curl -s -H 'Datastar-Request: true' "http://$addr/paiva?pvm=$d0")
dayp=$(curl -s -u ":$pass" -H 'Datastar-Request: true' "http://$addr/paiva?pvm=2026-09-05")
check "opening a day patches the list" "$dayp" 'id="paivat"'
refute "and returns a fragment, not a page" "$dayp" "<html"
check "picking a dish patches to the sides step" \
"$(curl -s -H 'Datastar-Request: true' \
"http://$addr/paiva?pvm=$d0&ruoka=$ruoka")" "Tallenna"
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
"http://$addr/paiva?pvm=2026-09-05&ruoka=$ruoka")" "Tallenna"
check "saving from Datastar patches back" \
"$(curl -s -H 'Datastar-Request: true' \
-d "pvm=$d1&ruoka=$ruoka" "http://$addr/kirjaa")" 'id="paivat"'
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
-d "pvm=2026-09-04&ruoka=$ruoka" "http://$addr/kirjaa")" 'id="paivat"'
check "deleting from Datastar patches back" \
"$(curl -s -H 'Datastar-Request: true' \
-d "pvm=$d1" "http://$addr/poista")" 'id="paivat"'
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
-d "pvm=2026-09-04" "http://$addr/poista")" 'id="paivat"'
# Without the header it must still redirect, for no JavaScript.
check "a plain save still redirects to the day" \
"$(curl -s -o /dev/null -w '%{redirect_url}' \
-d "pvm=$d1&ruoka=$ruoka" "http://$addr/kirjaa")" "pvm=$d1"
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d "pvm=2026-09-04&ruoka=$ruoka" "http://$addr/kirjaa")" "pvm=2026-09-04"
# Deleting a logged meal drops the row outright, so it asks first.
saved=$(curl -s "http://$addr/?pvm=$d0&poista=1")
saved=$(curl -s -u ":$pass" "http://$addr/?pvm=2026-09-05&poista=1")
check "deleting a meal asks first" "$saved" "Poistetaanko merkintä?"
# Assert the entry is still shown, rather than that no gap row exists anywhere
# on the page: other days are legitimately unlogged and render their own.
check "and the entry is still there while asking" "$saved" "kirjattu"
refute "and does not delete while asking" "$saved" "Ei merkintää"
check "deleting redirects back" \
"$(curl -s -o /dev/null -w '%{http_code}' \
-d "pvm=$d0" "http://$addr/poista")" "303"
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \
-d "pvm=2026-09-05" "http://$addr/poista")" "303"
check "the day is empty again" \
"$(curl -s "http://$addr/?pvm=$d0")" "Etsi"
"$(curl -s -u ":$pass" "http://$addr/?pvm=2026-09-05")" "Etsi"
check "search filters the board" \
"$(curl -s "http://$addr/?haku=keitto")" "keitto"
"$(curl -s -u ":$pass" "http://$addr/?haku=keitto")" "keitto"
# ---- live search: Datastar sends signals as JSON in ?datastar= -----------
live=$(curl -s --get --data-urlencode 'datastar={"haku":"keitto"}' "http://$addr/etsi")
live=$(curl -s -u ":$pass" --get --data-urlencode 'datastar={"haku":"keitto"}' "http://$addr/etsi")
check "live search returns the board fragment" "$live" 'id="lauta"'
check "live search applies the term" "$live" "keitto"
refute "live search excludes non-matches" "$live" "Lihapullat"
refute "the fragment is not a whole page" "$live" "<html"
check "live search is served as html for Datastar to patch" \
"$(curl -s -o /dev/null -w '%{content_type}' \
"$(curl -s -o /dev/null -w '%{content_type}' -u ":$pass" \
--get --data-urlencode 'datastar={"haku":"keitto"}' "http://$addr/etsi")" \
"text/html"
cat_live=$(curl -s --get --data-urlencode 'datastar={"haku":"riisi"}' "http://$addr/ruuat/etsi")
cat_live=$(curl -s -u ":$pass" --get --data-urlencode 'datastar={"haku":"riisi"}' "http://$addr/ruuat/etsi")
check "catalog live search returns its fragment" "$cat_live" 'id="ruokalista"'
check "catalog live search matches sides too" "$cat_live" "Riisi"
refute "catalog live search excludes non-matches" "$cat_live" "Lihapullat"
# The plain form still works without JavaScript.
check "catalog search works as a plain form too" \
"$(curl -s "http://$addr/ruuat?haku=riisi")" "Riisi"
"$(curl -s -u ":$pass" "http://$addr/ruuat?haku=riisi")" "Riisi"
# Nothing was eaten tomorrow. A future date is clamped rather than logged.
future=$(date -d '+30 days' +%Y-%m-%d)
check "a future date falls back to today" \
"$(curl -s "http://$addr/?pvm=$future")" "$(date +%-d.%-m.%Y)"
"$(curl -s -u ":$pass" "http://$addr/?pvm=$future")" "$(date +%-d.%-m.%Y)"
check "saving a future date is clamped too" \
"$(curl -s -o /dev/null -w '%{redirect_url}' \
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d "pvm=$future&ruoka=$ruoka" "http://$addr/kirjaa")" "/"
check "tomorrow was not written to the log" \
"$(curl -s "http://$addr/?pvm=$future")" "$(date +%-d.%-m.%Y)"
"$(curl -s -u ":$pass" "http://$addr/?pvm=$future")" "$(date +%-d.%-m.%Y)"
# Clean up the entry that clamped onto today.
curl -s -o /dev/null -d "pvm=$(date +%Y-%m-%d)" "http://$addr/poista"
curl -s -o /dev/null -u ":$pass" -d "pvm=$(date +%Y-%m-%d)" "http://$addr/poista"
# ---- adding a dish without leaving Kirjaa --------------------------------
miss=$(curl -s "http://$addr/?haku=Poronkariste")
miss=$(curl -s -u ":$pass" "http://$addr/?haku=Poronkariste")
check "a search with no hits offers to add it" "$miss" "Ei osumia. Lisätäänkö?"
check "the add form is prefilled with the search" "$miss" 'value="Poronkariste"'
check "quick add goes straight to the sides step" \
"$(curl -s -o /dev/null -w '%{redirect_url}' \
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d 'nimi=Poronkariste&kategoria=meat&lisukkeita=1' "http://$addr/lisaa")" \
"ruoka="
check "quick add rejects a dish with no category" \
"$(curl -s -d 'nimi=Kategoriaton' "http://$addr/lisaa")" \
"$(curl -s -u ":$pass" -d 'nimi=Kategoriaton' "http://$addr/lisaa")" \
"Valitse vähintään yksi kategoria."
check "the quick-added dish is on the board" \
"$(curl -s "http://$addr/")" "Poronkariste"
"$(curl -s -u ":$pass" "http://$addr/")" "Poronkariste"
# ---- catalog CRUD from the UI -------------------------------------------
# Assert where it redirects, not just that it does: these pointed at the old
# /ruoat spelling for a while and every 303-only check was happy.
check "adding a main redirects back to the catalog" \
"$(curl -s -o /dev/null -w '%{redirect_url}' \
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d 'nimi=uunikala&kategoria=fish&lisukkeita=1' "http://$addr/ruuat/paaruoka")" \
"/ruuat"
catalog=$(curl -s "http://$addr/ruuat")
catalog=$(curl -s -u ":$pass" "http://$addr/ruuat")
check "the new main is listed, sentence-cased" "$catalog" "Uunikala"
check "a duplicate name is refused" \
"$(curl -s -d 'nimi=UUNIKALA&kategoria=fish' "http://$addr/ruuat/paaruoka")" \
"$(curl -s -u ":$pass" -d 'nimi=UUNIKALA&kategoria=fish' "http://$addr/ruuat/paaruoka")" \
"Nimi on jo listalla."
check "a main with no category is refused" \
"$(curl -s -d 'nimi=Kategoriaton' "http://$addr/ruuat/paaruoka")" \
"$(curl -s -u ":$pass" -d 'nimi=Kategoriaton' "http://$addr/ruuat/paaruoka")" \
"Valitse vähintään yksi kategoria."
check "a nameless dish is refused" \
"$(curl -s -d 'nimi=+++&kategoria=fish' "http://$addr/ruuat/paaruoka")" \
"$(curl -s -u ":$pass" -d 'nimi=+++&kategoria=fish' "http://$addr/ruuat/paaruoka")" \
"Anna nimi."
check "adding a side redirects back to the catalog" \
"$(curl -s -o /dev/null -w '%{redirect_url}' \
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d 'nimi=lohkoperunat' "http://$addr/ruuat/lisuke")" \
"/ruuat"
check "the new side is listed" \
"$(curl -s "http://$addr/ruuat")" "Lohkoperunat"
"$(curl -s -u ":$pass" "http://$addr/ruuat")" "Lohkoperunat"
# The id of Uunikala specifically: the catalog is grouped and alphabetical, so
# the first id on the page belongs to some other dish entirely.
@@ -286,20 +279,20 @@ if [ -z "$uusi" ]; then
uusi=0
fi
check "the edit form is prefilled" \
"$(curl -s "http://$addr/ruuat?muokkaa=$uusi")" "Muokkaa pääruokaa"
"$(curl -s -u ":$pass" "http://$addr/ruuat?muokkaa=$uusi")" "Muokkaa pääruokaa"
# A bin icon is easy to hit by accident, so the row asks before anything goes.
check "the bin asks before deleting" \
"$(curl -s "http://$addr/ruuat?poista=$uusi&tyyppi=paa")" "Poista?"
"$(curl -s -u ":$pass" "http://$addr/ruuat?poista=$uusi&tyyppi=paa")" "Poista?"
check "the dish is still there while it asks" \
"$(curl -s "http://$addr/ruuat?poista=$uusi&tyyppi=paa")" "Uunikala"
"$(curl -s -u ":$pass" "http://$addr/ruuat?poista=$uusi&tyyppi=paa")" "Uunikala"
# ---- the catalog patches in place instead of navigating -----------------
# A delete confirmation halfway down a long list must not send the browser
# back to the top, so these answer with a Datastar patch rather than a page.
patch=$(curl -s -H 'Datastar-Request: true' \
patch=$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
"http://$addr/ruuat/nayta?poista=$uusi&tyyppi=paa")
check "asking to delete patches rather than navigates" "$patch" "event: datastar-patch-elements"
check "the patch carries the list" "$patch" 'id="ruokalista"'
@@ -307,26 +300,26 @@ check "and both forms, so an open one closes" "$patch" 'id="paaruoka"'
check "the row it patches in is asking" "$patch" "Poista?"
check "patches are served as an event stream" \
"$(curl -s -o /dev/null -w '%{content_type}' -H 'Datastar-Request: true' \
"$(curl -s -o /dev/null -w '%{content_type}' -u ":$pass" -H 'Datastar-Request: true' \
"http://$addr/ruuat/nayta")" "text/event-stream"
check "deleting from Datastar patches too" \
"$(curl -s -H 'Datastar-Request: true' \
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
-d "id=$uusi&tyyppi=paa" "http://$addr/ruuat/poista")" \
"event: datastar-patch-elements"
refute "and the dish is gone from the patched list" \
"$(curl -s -H 'Datastar-Request: true' "http://$addr/ruuat/nayta")" \
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' "http://$addr/ruuat/nayta")" \
"Uunikala"
# Without the header it must still be an ordinary redirect, for no JavaScript.
check "a plain form post still redirects" \
"$(curl -s -o /dev/null -w '%{redirect_url}' \
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d 'nimi=Testiruoka&kategoria=fish' "http://$addr/ruuat/paaruoka")" \
"/ruuat"
refute "the dish is gone once confirmed" \
"$(curl -s "http://$addr/ruuat")" "Uunikala"
"$(curl -s -u ":$pass" "http://$addr/ruuat")" "Uunikala"
if [ "$fail" -ne 0 ]; then
echo "smoke: FAILED"