Calendar: roster team mode on home/teammode
Home team-members.md Part B; teammode-package.md §7.3. teammode, roster
and connect pinned at Home main 67c12e3 (nothing at 6b23c73). Reference
ports: Sheets 35dd773 (#52-#54), Slides 951373f (#33), Memoria
team-mode (#32).
With the five CALENDAR_TEAM_* variables set (all or none, only beside
CALENDAR_HOME_*), Home's roster decides standing on every request, and
CALENDAR_ALLOWED_ADDRESSES becomes optional and only admits local
sign-in. The marker (calendar_team) is read before anything migrates,
with a foreign-issuer census over home_identity_links and
calendar_team_home_people. GET /api/team is teammode.Probe.
Calendar has no shares: every grant is made by EnsurePersonSetup for the
person themselves, so every grant is the team rung and counts only while
Member (team_reach.go, read once before each scoped read). NotMember is
signed out to /signin?err=removed (Memoria's shape); an unlinked local
account is sent to link. Under Unknown the views are the empty partial
list with a notice (the empty state and the day's sentence withheld);
items, forms, writes and the native API are a retryable no-store 503,
and a 404 or 500 a lapse causes part-way is that 503 too.
teammode.Guard runs inside every person's write transaction.
Things that read on someone else's standing: a subscription feed on its
minter's (Unknown is a 503, never a short calendar; NotMember is the
revoked-token 404), a public booking page, hold, confirm and reschedule
on the host's, and a reminder or a booking's host mail on its
recipient's, decided by the drain as it is about to go (NotMember or no
address: settled unsent; Unknown: deferred five minutes). The dashboard
pull is unavailable under Unknown.
Home-only members come in through connect's Unlinked/HomeOnly hooks as
people whose address column holds a random home-only: placeholder that
triggers keep addressless, undeletable and unlinked. No address is
stored for them: no email reminders, no published booking page (the
reminders question is in the spec, §7, for Paul).
Team mode off is byte-identical except /api/team answering
{"team_mode":false} (64 responses dumped at origin/main and here).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
77 files changed,
+4,316
−463
AGENTS.md+43 −0Makefile+1 −1cmd/calendar/main.go+6 −1docs/superpowers/specs/2026-09-02-calendar-design.md+171 −0go.mod+3 −1go.sum+6 −2internal/calendar/app.go+38 −1internal/calendar/auth.go+11 −2internal/calendar/booking_mail.go+16 −0internal/calendar/config.go+18 −1internal/calendar/credits_inventory_test.go+1 −1internal/calendar/dashboard.go+17 −1internal/calendar/handlers.go+7 −0internal/calendar/handlers_booking_manage.go+12 −0internal/calendar/handlers_booking_public.go+13 −0internal/calendar/handlers_booking_settings.go+22 −5internal/calendar/handlers_events.go+1 −0internal/calendar/handlers_jobs.go+10 −0internal/calendar/handlers_misc.go+33 −4internal/calendar/handlers_settings.go+2 −0internal/calendar/handlers_views.go+11 −0internal/calendar/home.go+19 −4internal/calendar/models.go+6 −0internal/calendar/native.go+31 −5internal/calendar/native_quick.go+1 −1internal/calendar/person.go+6 −0internal/calendar/render.go+6 −0internal/calendar/routes.go+74 −56internal/calendar/signin.go+7 −0internal/calendar/store.go+7 −0internal/calendar/store_attendee.go+1 −1internal/calendar/store_booking_cancel.go+18 −16internal/calendar/store_booking_confirm.go+97 −93internal/calendar/store_booking_flow.go+76 −74internal/calendar/store_booking_handle.go+8 −4internal/calendar/store_booking_page.go+64 −45internal/calendar/store_calendar.go+16 −8internal/calendar/store_drain.go+6 −8internal/calendar/store_event.go+2 −1internal/calendar/store_event_read.go+1 −1internal/calendar/store_event_write.go+26 −21internal/calendar/store_feed.go+23 −19internal/calendar/store_feed_rows.go+4 −2internal/calendar/store_override.go+48 −41internal/calendar/store_range.go+9 −6internal/calendar/store_reminder.go+45 −23internal/calendar/team_access.go+244 −0internal/calendar/team_access_test.go+257 −0internal/calendar/team_answers.go+114 −0internal/calendar/team_booking.go+58 −0internal/calendar/team_booking_test.go+103 −0internal/calendar/team_config.go+109 −0internal/calendar/team_config_test.go+278 −0internal/calendar/team_feed.go+71 −0internal/calendar/team_feeds_test.go+223 −0internal/calendar/team_fixture_test.go+247 −0internal/calendar/team_guard.go+80 −0internal/calendar/team_guard_test.go+252 −0internal/calendar/team_home_only.go+114 −0internal/calendar/team_identity_test.go+223 −0internal/calendar/team_jobs.go+130 −0internal/calendar/team_jobs_test.go+268 −0internal/calendar/team_reach.go+51 −0internal/calendar/team_standing.go+105 −0internal/calendar/team_world_test.go+134 −0internal/calendar/teamstate/migrations/0001_home_people.sql+13 −0internal/calendar/teamstate/store.go+180 −0internal/calendar/templates/agenda.html+2 −2internal/calendar/templates/booking_pages.html+1 −1internal/calendar/templates/calendars.html+1 −1internal/calendar/templates/day.html+4 −4internal/calendar/templates/event.html+2 −2internal/calendar/templates/layout.html+5 −0internal/calendar/templates/month.html+1 −1internal/calendar/templates/settings.html+1 −1internal/calendar/templates/week.html+1 −1internal/calendar/viewer.go+1 −1
CI passed — run details
Intent
diff --git a/AGENTS.md b/AGENTS.md| index e5dafe7..091ad72 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -64,6 +64,7 @@ pass by reading a file the data has not reached. |
| | 7a | Local sign-in uses Keymail for an address whose domain runs Keymail, and the magic link for every other address — chosen by the domain alone, never by the allowlist (an oracle otherwise). The Keymail hop is a continuation page, never a 303 out of the form POST (Safari applies form-action to it) | Forcing every address to a magic link | Paul, 2026-10-06 ("I do want it to use keymail") | |
| | 8 | A new event defaults to the person's PERSONAL calendar | Defaulting to the team calendar — the cost of forgetting to change a dropdown should fall on the side of privacy | This session, 2026-09-02 | |
| | H1 | **Optional Home sign-in connects to an existing person after fresh local proof and explicit confirmation; local sign-in remains available** | Treating the Home subject as an email or allocating a new person | User-approved suite connection, 2026-09-10 | |
| +| T1 | **Team mode (`CALENDAR_TEAM_*`): Home's roster decides standing on every request**; a roster Member with no account here gets an addressless Home-only person through connect's `Unlinked` hook (H1 holds outside team mode) | The allowlist deciding a team instance; storing an address for a Home-only member (a new address column: its own privacy review, Fable on oficina/home #98) | Home team-members.md Part B (Fable #92), Paul's port order 2026-10-27; spec §7 "Roster team mode" | |
| | B1 | A booking is confirmed by a BUTTON on the page the mailed link opens — a same-origin POST — never on submit and never on GET | Instant confirmation; confirming on the GET, which every link-scanning mail gateway would press | Booking spec §1, 2026-09-07 | |
| | B2 | Everything the host can see is busy — every calendar they hold a grant on | Personal only | Booking spec §1, 2026-09-07 | |
| | B4 | The public identifier is a chosen plaintext `handle` plus a GENERATED page code | A chosen slug — prose joined to events | Booking spec §1, 2026-09-07 | |
| @@ -283,6 +284,48 @@ relying on remembering one, make it a test instead. |
| moving an instance between `stable` and `edge`. This app runs on |
| `edge`, like docs. Create an instance on the channel you want. |
| +## Team mode (roster, `CALENDAR_TEAM_*`) |
| + |
| +Spec §7 "Roster team mode" is the whole of it; Home |
| +`implementation/teammode-package.md` §7.3 and `team-members.md` Part B are |
| +its design. With the five `CALENDAR_TEAM_*` variables set (all or none, |
| +only beside `CALENDAR_HOME_*`), Home's roster decides standing on every |
| +request and `CALENDAR_ALLOWED_ADDRESSES` only admits local sign-in (empty |
| +admits nobody, in every Env). Without them nothing in `team_*.go` runs and |
| +every rule above stands; the one difference is `GET /api/team` answering |
| +`{"team_mode":false}`. |
| + |
| +- **Configuration, marker, runtime and probe are `home/teammode`'s** |
| + (`team_config.go`). The marker is read before anything migrates; a team |
| + database stays a team database. Do not "fix" a refused boot by deleting |
| + the marker (its triggers refuse that anyway). |
| +- **Every grant is the team rung** (`team_reach.go`): Calendar has no |
| + shares, so a scoped read joins through a grant only while the context's |
| + standing is Member, decided once, before the query. A new scoped read |
| + uses `grantJoin` with `s.reaches(ctx)`; a raw `JOIN grants` is a leak. |
| +- **Standing per request** (`team_access.go`, `team_standing.go`): |
| + NotMember is signed out to `/signin?err=removed`; an unlinked local |
| + account is sent to `/account/home`; under Unknown the views are the empty |
| + partial list with the notice and everything else is a retryable no-store |
| + 503 — including a 404 or 500 a lapse caused part-way |
| + (`errorPage`, `fail`). New routes in the session group go under |
| + `memberRoutes` unless they are a view. |
| +- **Every person's write is guarded inside its transaction** |
| + (`team_guard.go`: `s.guarded`, or `s.guard` inside an existing |
| + `Transaction`). `TestTeamEveryWriteRouteRefusesALapseBeforeCommit` lists |
| + every write route and reads the database back; add yours to it. |
| +- **Things that read on somebody else's standing**: a feed on its minter's |
| + (`team_feed.go`: Unknown is a 503, never a short calendar), a booking |
| + page on its host's (`team_booking.go`), a reminder or host mail on its |
| + recipient's (`team_jobs.go`). The drain itself is the system's and |
| + unguarded; what it delivers is decided on the person's standing. |
| +- **Home-only people have no address** (`team_home_only.go`, |
| + `teamstate/`): their `people.address` is a `home-only:` placeholder the |
| + triggers keep that way. Never mail it, show it, or treat it as an |
| + address: `teamstate.Addressless`, `Person.shownAddress`. They get no |
| + reminders and publish no booking page until Paul rules on the reminders |
| + question in the spec. |
| + |
| --- |
| ## Shipping cadence |
diff --git a/Makefile b/Makefile| index be9dd80..fea8f2f 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -160,6 +160,6 @@ credits: |
| go build -o "$$notices_tmp/notices" amadan.net/oficina/estilo.git/cmd/oficina-notices; \ |
| GOOS=linux GOARCH=arm64 CGO_ENABLED=0 "$$notices_tmp/notices" \ |
| -package ./cmd/calendar -lucide -onest \ |
| - -exclude amadan.net/oficina/home/dashboard,amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/rastrillo/native/server \ |
| + -exclude amadan.net/oficina/home/dashboard,amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode,amadan.net/rastrillo/native/server \ |
| > "$$notices_tmp/notices.json"; \ |
| mv "$$notices_tmp/notices.json" internal/calendar/credits/notices.json |
diff --git a/cmd/calendar/main.go b/cmd/calendar/main.go| index 9a9493c..05a2840 100644 |
| --- a/cmd/calendar/main.go |
| +++ b/cmd/calendar/main.go |
| @@ -14,6 +14,7 @@ package main |
| import ( |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| "log/slog" |
| "os" |
| "strings" |
| @@ -58,7 +59,11 @@ func main() { |
| } |
| app, err := calendar.New(calendar.Config{ |
| - Home: connect.CredentialsFromEnv("CALENDAR"), |
| + Home: connect.CredentialsFromEnv("CALENDAR"), |
| + // Roster team mode: the five CALENDAR_TEAM_* variables, all or |
| + // none (nil when all are empty), verified against the Home |
| + // credentials above before anything migrates (team_config.go). |
| + Team: teammode.ConfigFromEnv("CALENDAR"), |
| DBPath: opts.DBPath, |
| Env: chooseEnv(envFlag, os.Getenv("CALENDAR_ENV")), |
| Origin: origin, |
diff --git a/docs/superpowers/specs/2026-09-02-calendar-design.md b/docs/superpowers/specs/2026-09-02-calendar-design.md| index 46df778..04287e3 100644 |
| --- a/docs/superpowers/specs/2026-09-02-calendar-design.md |
| +++ b/docs/superpowers/specs/2026-09-02-calendar-design.md |
| @@ -307,3 +307,174 @@ value is a dedicated 32-byte connection key, separate from event encryption. |
| Partial configuration refuses startup. Without these values, local sign-in keeps |
| its existing routes and behavior. The shared Home connection package supplies the |
| proof flow and account screens; Calendar keeps its own page shell and grants. |
| + |
| +### Roster team mode — 2026-10-30 |
| + |
| +🤖 Claude Opus 5.5, for Paul. Home `implementation/team-members.md` Part B |
| +and `implementation/teammode-package.md` §7.3, on Home's shared |
| +`home/teammode` package (pinned with `roster` and `connect` at Home main |
| +`67c12e3`). Reference ports: Sheets (`35dd773`, #52–#54), Slides |
| +(`951373f`, #33), Memoria (branch `team-mode`, #32). Not deployed. |
| + |
| +**Configuration.** The five `CALENDAR_TEAM_*` variables (`_ID`, |
| +`_DIRECTORY_ORIGIN`, `_PROVISIONING_BASE64`, `_OPERATOR_KEYS_BASE64`, |
| +`_ROSTER_TOKEN`), all or none, and only beside `CALENDAR_HOME_*`; the |
| +provisioning record is verified against the Home issuer and consumer ID, |
| +app `calendar` and `CALENDAR_ORIGIN` before the database is opened. The |
| +marker (`calendar_team_required`, migration set `calendar_team`) is read |
| +before anything migrates, and an activated database refuses to boot without |
| +the same binding. Activation refuses a census that finds another issuer in |
| +`home_identity_links` or `calendar_team_home_people`. `GET /api/team` is |
| +`teammode.Probe`; with team mode off it answers `{"team_mode":false}`, the |
| +one difference team mode off makes (a 64-response dump at `origin/main` and |
| +at the branch differs only there and in per-run random values). |
| + |
| +**Standing, and what the team rung is in Calendar.** Calendar has no |
| +shares. Every grant is made by `EnsurePersonSetup` for the person |
| +themselves — editor on the one team calendar, owner of their own personal |
| +calendar — so in team mode **every grant is the team rung** and counts only |
| +while the roster says Member (Docs' owner rule; Sheets' "self-grants count |
| +only while Member"). Attendees are recorded addresses, not grants, and |
| +reach nothing. So: |
| + |
| +- **Member**: everything they reached before. |
| +- **NotMember**: nothing, so they are **signed out and told so** |
| + (`/signin?err=removed`), existing sessions included, within the lease — |
| + Memoria's shape, not Slides' guest session, because a guest here would |
| + reach nothing and an empty calendar reads as a free week. A local account |
| + with no Oficina link has no standing until it links and is sent to |
| + `/account/home`. |
| +- **Unknown**: the views (day, week, month, agenda, the calendar list) are |
| + the **partial list with its notice**, always empty, the day's sentence and |
| + every empty state withheld so it never reads as a free day; every item |
| + page, form, write and the native API is a **retryable 503** (`no-store`, |
| + `Retry-After`), and a 404 or 500 that a lapse caused part-way through a |
| + request is answered as that 503 too. |
| + |
| +Standing is read from the request's `teammode.Access` once, before each |
| +scoped read (`team_reach.go`: the grant join matches nothing without |
| +Member), so reach is never decided before standing; a view asks again as |
| +the page is drawn. The roster's role is not consulted: owners and members |
| +reach the same calendars, and Calendar has no owner-only power. |
| + |
| +**Orphans.** Paul's rule (share/retitle only, no delete or narrowing, |
| +team-visible only) has nothing to apply to: the team calendar is everyone's |
| +editor grant and has no owner role, and a departed member's personal |
| +calendar is private, nobody's orphan. No orphan rule is built. |
| + |
| +**Writes.** `teammode.Guard` runs inside every person's write transaction |
| +(`team_guard.go`): events (create, quick add, import, edit, this occurrence, |
| +split, delete, delete one occurrence), reminders, attendees, feeds (mint, |
| +revoke), settings and handle, booking pages (create, edit, publish), the |
| +native API's saves, and the public booking writes, which stand on the |
| +host's standing (hold, confirm, reschedule). Unguarded on purpose: identity |
| +(`EnsurePerson*`, the Home-only allocation), the drain's queue bookkeeping |
| +and hold expiry, a feed's poll counter, and a booker's own cancellation by |
| +its token. `TestTeamEveryWriteRouteRefusesALapseBeforeCommit` lapses the |
| +lease between write and commit on 22 routes and reads the database back |
| +unchanged, then runs each as a member and requires a change. |
| + |
| +**Feeds (`/feed/{token}.ics`) — the ICS decision.** A feed URL stays a |
| +capability (§7.3), but what it reads it reads on its **minter's** standing, |
| +asked on every poll, as a Slides presentation stands on its presenter: |
| +Member, the calendar; NotMember, the same 404 as a revoked token, so a |
| +member taken off the team stops receiving the team calendar in every |
| +account they pasted the URL into, without anybody finding and revoking it |
| +(re-added, it works again); **Unknown, a 503** (`no-store`, |
| +`Retry-After`), and a lapse while it is built is a 503 too, never a short |
| +calendar. Not "keep the last good feed" on the server: that would mean |
| +either rendering under Unknown (deciding reach without standing) or storing |
| +a plaintext copy of the calendar to replay, which the one rule forbids. |
| +Google, Apple and Outlook keep the copy they last fetched when a poll |
| +fails, so the subscriber's calendar does not go blank; it goes stale until |
| +Home answers. **Flagged for Paul.** The roster-owner revoke §7.3 asked for |
| +is not built: tying the feed to its minter's standing does what that revoke |
| +was for (a departed member's URLs die by themselves); a roster owner |
| +revoking a *current* member's feeds is a new power, his to rule on. |
| + |
| +**The dashboard pull** (`/api/oficina/dashboard`, another origin) is |
| +unavailable under Unknown, never short; empty for NotMember. The calendar |
| +download (`/calendars/{id}.ics`) is whole or a 503. |
| + |
| +**Booking pages.** A published page is a free/busy oracle over every |
| +calendar its host can see, the team calendar included (AGENTS.md "does NOT |
| +cover" 5). In team mode the page, its picker, the hold, the confirmation |
| +and a reschedule stand on the **host's** standing: NotMember, the page is |
| +gone (404) within the lease; Unknown, a 503, and the picker asks again |
| +after it is built so a lapse can never offer busy time as free (B23). A |
| +booker's own booking — its manage page, its `.ics`, cancelling it — stays |
| +theirs by its token. A hold whose host was removed cannot be confirmed and |
| +lapses on its own. |
| + |
| +**Scheduled work** (the tick on `CARLOS_CONTROL_SOCKET`/`CARLOS_ADMIN_TOKEN` |
| +and the drain a page view runs) acts as the system, under nobody's lease, |
| +as Memoria's connector runs do. What it **delivers** to a person is decided |
| +on that person's own standing as it is about to go (`team_jobs.go`): a |
| +reminder only to a Member who still reaches the event and has an address |
| +(NotMember, out of reach or addressless: that occurrence is settled unsent |
| +and the next is decided on its own day; Unknown: deferred, unsent and |
| +unattempted, by five minutes, so a Home outage does not keep the instance |
| +awake). A booking's host mail goes only to a Member host with an address |
| +(otherwise retired unsent; Unknown deferred); the booker's mail is |
| +unchanged (B5). A removed member is sent nothing about the team's events. |
| + |
| +**Home-only members.** connect's `Unlinked`/`HomeOnly` hooks, set only in |
| +team mode, give a roster Member with no account here a people row whose |
| +`address` column holds a random `home-only:` placeholder — the column is |
| +NOT NULL and UNIQUE and migrations are additive-only — and |
| +`calendar_team_home_people` says whose. Triggers keep it addressless (no |
| +`@`, never updated), undeletable (with foreign keys off too), and disjoint |
| +from account links in both directions. Nothing mails, shows or signs in |
| +with the placeholder; the account menu says "Oficina account …xxxx". |
| + |
| +**What a Home-only member loses — the reminders question, for Paul.** |
| +Home's design keeps no address at rest for them, and Fable's note on |
| +oficina/home #98 is that Calendar storing one would be a **new address |
| +column in an app, needing its own privacy review**. This branch adds none. |
| +So a Home-only member gets: |
| + |
| +1. **No email reminders.** No default reminder is made for their events, |
| + adding one is refused (the event page says why), and the drain never |
| + mails one. Their colleagues' reminders are unaffected. |
| +2. **No published booking page.** A page may be drafted, not published: |
| + the booker's invitation names the host by address (`ORGANIZER`), and the |
| + host's booking mail has nowhere to go. |
| +3. **No local sign-in.** They sign in through Oficina only. |
| + |
| +Options, none built: |
| + |
| +- **(a) In-app reminders**: an unread-reminder list on the calendar (and |
| + later a push to the native apps). No address anywhere; only seen when the |
| + app is open; the drain marks them due instead of mailing. |
| +- **(b) A member opts in by typing an address**, stored **sealed** (as a |
| + booker's is) with a keyed fingerprint, used only for their reminders and |
| + their booking mail, and removable. This is the new address column Fable |
| + flagged: it needs its own privacy review first, and an answer for what |
| + happens to it when they leave the team. |
| +- **(c) Reminders only for linked local accounts**: a member who wants |
| + email reminders links a local account (an allowlisted address) to their |
| + Oficina identity. No new storage; but Alta's recipe no longer writes the |
| + allowlist, so today nobody on a team instance can. |
| +- A cheap partial measure under any of them: feeds can carry alarms |
| + (`?alarms=1`), so a Home-only member could get reminders from their own |
| + calendar app — but only for reminder rules they cannot currently make. |
| + |
| +**Allowlist.** `CALENDAR_ALLOWED_ADDRESSES` becomes optional in team mode |
| +(every Env; empty admits nobody locally, never the development default). It |
| +admits the local door and nothing more: a linked person stands on the |
| +roster whether or not they are on it, and an unlinked local account is a |
| +person with no standing. Unlike Slides (deviation 4 on #33), a local |
| +**session** is still re-checked against the list on every request, as |
| +Calendar has always done and Memoria does: taking an address off the list |
| +ends that local session's identity (404), though the same person's Home |
| +sign-in still stands on the roster. |
| + |
| +**Alta.** `provision/apps.go` needs, for Calendar: `Roster: true`; |
| +`keys = append(keys, teamKeys(p, in)...)` in `case "calendar"` (exactly |
| +`teammode.EnvNames("CALENDAR")`); and **drop** |
| +`owner("CALENDAR_ALLOWED_ADDRESSES")` (left set, it only admits the owner's |
| +local sign-in). Keep `CALENDAR_DEK` and the `CALENDAR_HOME_*` and |
| +`HOME_DIRECTORY_ORIGIN` names, which match `cmd/calendar`. The step-11 |
| +probe is Calendar's `/api/team`; the fake console, `TestRosterRecipes` and |
| +the homecompat runs need Calendar moved from "pending" to activated, as |
| +`d59778f` did for Slides. |
diff --git a/go.mod b/go.mod| index 24977c7..f9ce6e4 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -5,7 +5,7 @@ go 1.25.0 |
| toolchain go1.26.5 |
| require ( |
| - amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d |
| + amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 |
| github.com/carlosframework/rastrillo v0.23.0 |
| @@ -44,6 +44,8 @@ require ( |
| require ( |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 |
| + amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 |
| + amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 |
| ) |
diff --git a/go.sum b/go.sum| index cb6bab9..70b1253 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,11 +1,15 @@ |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw= |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| -amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d h1:9sVZBph2xUuejZt73DYaoCfoyvrvZCnuPHcyMsg562E= |
| -amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| +amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 h1:MPO8MRkk+tT2k+95fZPJ0JStnmAKUCKiVoPbfBVTk6E= |
| +amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I= |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0= |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d h1:8RTZkLQnyxvH2g0RMovhN/m2LN9D8qb+kBfqdBeqq+s= |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| +amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 h1:yKUTS0nOiVw7ktHpTin0bCcUDLFjmMjpW6CsHIZzZKk= |
| +amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| +amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 h1:0PQiRUkC+9cbTHE67Y4/SmW1sPH1NNWNwTceNFyMjTY= |
| +amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3/go.mod h1:ZaaxeE278dJltdrLwmwpxUjQ5wuKzqDAVSNRet+WupY= |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKfm+AYrqgH1ea6cNsFs4sN7MKLvq+uBY11NZE= |
diff --git a/internal/calendar/app.go b/internal/calendar/app.go| index 505105a..8604663 100644 |
| --- a/internal/calendar/app.go |
| +++ b/internal/calendar/app.go |
| @@ -4,6 +4,7 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/teammode" |
| nativeauth "amadan.net/rastrillo/native/server" |
| "context" |
| "fmt" |
| @@ -51,6 +52,13 @@ type App struct { |
| // h is held for the test harness; requests reach it through mux. |
| h *handlers |
| scheduled *scheduledWork |
| + |
| + // teamOn is the verified team configuration, nil with team mode off; |
| + // team is the roster runtime built from it once the schema is applied |
| + // and Home is wired (team_config.go). Every team-mode branch keys on |
| + // one of the two, so with team mode off none of them runs. |
| + teamOn *teammode.Settings |
| + team *teamRuntime |
| closeOnce sync.Once |
| closeErr error |
| } |
| @@ -73,6 +81,13 @@ func New(cfg Config) (*App, error) { |
| if err != nil { |
| return nil, fmt.Errorf("calendar: Home configuration: %w", err) |
| } |
| + // Team mode (team_config.go): the configuration is verified against |
| + // the Home credentials just decoded, before the database is opened. |
| + // Off, this is nil and nothing below changes. |
| + team, err := teamSettings(cfg.Team, homeSettings, origin) |
| + if err != nil { |
| + return nil, fmt.Errorf("calendar: team configuration: %w", err) |
| + } |
| instanceKey, err := resolveInstanceKey(cfg) |
| if err != nil { |
| @@ -111,6 +126,14 @@ func New(cfg Config) (*App, error) { |
| if homeSettings != nil { |
| boot = migrate.Merge(BootSchema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace)) |
| } |
| + // The marker is read before anything migrates. Off, this is one |
| + // sqlite_master read and boot is unchanged; an activated database |
| + // without the same binding refuses here. |
| + boot, err = teamBootSchema(context.Background(), d.Writer(), team, boot) |
| + if err != nil { |
| + d.Close() |
| + return nil, fmt.Errorf("calendar: team mode: %w", err) |
| + } |
| migrated, err := migrate.Apply(context.Background(), d, boot) |
| if err != nil { |
| d.Close() |
| @@ -151,6 +174,7 @@ func New(cfg Config) (*App, error) { |
| // handlers before auth: auth's Refused and RenderConfirm are pages |
| // the handlers draw. viewerFrom is auth's, so it is set just after. |
| store := NewStore(d.G, sealer, logger) |
| + store.team = team != nil |
| h := &handlers{store: store, logger: logger, origin: origin, mailer: mailer, gate: newGate()} |
| authPlugin, err := newAuthPlugin(origin, writer, instanceKey, signinMail, list, logger, homeSettings != nil, h) |
| if err != nil { |
| @@ -168,6 +192,7 @@ func New(cfg Config) (*App, error) { |
| mailRecorder: recorder, |
| signinMail: signinMail, |
| auth: authPlugin, |
| + teamOn: team, |
| } |
| a.h = h |
| if homeSettings != nil { |
| @@ -182,6 +207,15 @@ func New(cfg Config) (*App, error) { |
| d.Close() |
| return nil, err |
| } |
| + if err = a.configureTeam(team, homeSettings); err != nil { |
| + signinMail.close() |
| + d.Close() |
| + return nil, fmt.Errorf("calendar: team mode: %w", err) |
| + } |
| + h.team = a.team |
| + if a.team != nil { |
| + h.standingOf = a.standingOf |
| + } |
| h.homeEnabled = true |
| h.directory = homeSettings.Directory |
| h.homeLinked = a.home.bridge.Linked |
| @@ -190,11 +224,14 @@ func New(cfg Config) (*App, error) { |
| // behind it; resolve again only where it has not run (public |
| // pages, errors raised before it). |
| if p, ok := CurrentPerson(r); ok { |
| - return rauth.Identity{Address: p.Address}, true |
| + return rauth.Identity{Address: p.shownAddress()}, true |
| } |
| if a.home == nil { |
| return viewer(r) |
| } |
| + if a.team != nil { |
| + return a.teamViewer(r) |
| + } |
| if s, ok := sessions.Current(r); !ok || s.Method != connect.HomeMethod { |
| return viewer(r) |
| } |
diff --git a/internal/calendar/auth.go b/internal/calendar/auth.go| index 03b1bbb..92bf346 100644 |
| --- a/internal/calendar/auth.go |
| +++ b/internal/calendar/auth.go |
| @@ -119,8 +119,10 @@ func normalizeAddress(address string) string { |
| // addrs == nil means "admit every address" — resolveAllowlist's |
| // development-only default, spelled out rather than left as an |
| // accidental nil. addrs != nil means "admit nothing but exactly this |
| -// set". resolveAllowlist never returns a non-nil-but-empty map outside |
| -// development, since an empty parse there is a startup refusal. |
| +// set". resolveAllowlist returns a non-nil-but-empty map only in team |
| +// mode (admit nobody locally: the roster decides, and Home signs people |
| +// in), since an empty parse outside development is otherwise a startup |
| +// refusal. |
| type allowlist struct { |
| addrs map[string]struct{} |
| } |
| @@ -176,6 +178,13 @@ func resolveAllowlist(cfg Config) (allowlist, error) { |
| if len(addrs) > 0 { |
| return allowlist{addrs: addrs}, nil |
| } |
| + if cfg.Team != nil { |
| + // Team mode: the roster decides standing, and the list is only |
| + // local sign-in's admission. Empty admits nobody locally, in |
| + // every Env: a team instance never takes the development |
| + // default that admits everyone. |
| + return allowlist{addrs: addrs}, nil |
| + } |
| if cfg.Env == "development" { |
| return allowlist{}, nil // addrs stays nil: admit everyone |
| } |
diff --git a/internal/calendar/booking_mail.go b/internal/calendar/booking_mail.go| index 8b48f9f..eb19ebb 100644 |
| --- a/internal/calendar/booking_mail.go |
| +++ b/internal/calendar/booking_mail.go |
| @@ -88,6 +88,22 @@ func (h *handlers) sendBookingMail(ctx context.Context, row BookingMail, now tim |
| } |
| return errMailRetired |
| } |
| + // Team mode: the host's mail goes only to a host the roster says is |
| + // on the team, and who has an address (team_jobs.go). |
| + if row.Recipient == ToHost { |
| + switch h.hostMail(ctx, v.Host) { |
| + case deliverLater: |
| + if _, err := h.store.DeferBookingMail(keep(ctx), row.ID, row.ClaimID, now.Unix()); err != nil { |
| + return err |
| + } |
| + return errMailDeferred |
| + case deliverNever: |
| + if _, err := h.store.MarkBookingMailSent(keep(ctx), row.ID, row.ClaimID, now.Unix()); err != nil { |
| + return err |
| + } |
| + return errMailRetired |
| + } |
| + } |
| to, subject, body, err := h.renderBookingMail(row, v, now) |
| if err != nil { |
| return err |
diff --git a/internal/calendar/config.go b/internal/calendar/config.go| index a124a26..ed82de6 100644 |
| --- a/internal/calendar/config.go |
| +++ b/internal/calendar/config.go |
| @@ -5,10 +5,13 @@ import ( |
| "encoding/base64" |
| "fmt" |
| "log/slog" |
| + "net/http" |
| "net/url" |
| "strings" |
| "time" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/mail" |
| ) |
| @@ -24,6 +27,18 @@ const DefaultOrigin = "http://localhost:8080" |
| // quietly does the wrong thing. |
| type Config struct { |
| Home *connect.Credentials |
| + |
| + // Team is roster team mode's configuration (teammode.ConfigFromEnv |
| + // with prefix CALENDAR: the five CALENDAR_TEAM_* variables, all or |
| + // none), nil with team mode off. It exists only beside Home, and in |
| + // team mode AllowedAddresses is optional: if set it only admits local |
| + // sign-in, and gives nobody team standing (team_config.go). |
| + Team *teammode.Config |
| + // teamTransport and teamClock are for tests: a directory that answers |
| + // in memory and a clock a test can step (teammodetest). Production |
| + // leaves both nil. |
| + teamTransport http.RoundTripper |
| + teamClock roster.Clock |
| // DBPath is the SQLite file this instance owns. The platform hands |
| // it in as activation argv; a developer passes -db. |
| DBPath string |
| @@ -68,7 +83,9 @@ type Config struct { |
| // ($CALENDAR_ALLOWED_ADDRESSES). Empty is refused outside |
| // development rather than defaulting to "admit nobody": an |
| // instance that silently admitted nobody would look identical from |
| - // the outside to one working correctly. See resolveAllowlist. |
| + // the outside to one working correctly. See resolveAllowlist. In team |
| + // mode it is optional and only admits local sign-in: empty admits |
| + // nobody locally, in every Env. |
| AllowedAddresses string |
| Logger *slog.Logger |
diff --git a/internal/calendar/credits_inventory_test.go b/internal/calendar/credits_inventory_test.go| index 806bd87..90bb271 100644 |
| --- a/internal/calendar/credits_inventory_test.go |
| +++ b/internal/calendar/credits_inventory_test.go |
| @@ -36,7 +36,7 @@ func TestCreditsMatchProductionDependencies(t *testing.T) { |
| if err != nil { |
| t.Fatalf("production dependency graph unavailable: %v\n%s", err, stderr.String()) |
| } |
| - inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/home/dashboard": true, "amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/rastrillo/native/server": true}) |
| + inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/home/dashboard": true, "amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true, "amadan.net/rastrillo/native/server": true}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/calendar/dashboard.go b/internal/calendar/dashboard.go| index 8f75b5c..1f16ab9 100644 |
| --- a/internal/calendar/dashboard.go |
| +++ b/internal/calendar/dashboard.go |
| @@ -11,6 +11,7 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/oficina/home/dashboard" |
| + "amadan.net/oficina/home/teammode" |
| ) |
| func (a *App) configureDashboard(c *connect.DecodedCredentials) error { |
| @@ -31,7 +32,15 @@ func (a *App) configureDashboard(c *connect.DecodedCredentials) error { |
| a.dashboard = h |
| return nil |
| } |
| -func (a *App) dashboardEvents(ctx context.Context, id int64, _ string, now time.Time) (dashboard.Response, error) { |
| +func (a *App) dashboardEvents(ctx context.Context, id int64, subject string, now time.Time) (dashboard.Response, error) { |
| + var standing *teammode.Access |
| + if a.team != nil { |
| + // The roster's standing for the verified subject that asked |
| + // (Resolve found a link or a Home-only person for it; identity |
| + // only), never anything stored (team_access.go). |
| + standing = a.team.Access(ctx, subject) |
| + ctx = teammode.WithAccess(ctx, standing) |
| + } |
| var person Person |
| if e := a.db.G.WithContext(ctx).First(&person, id).Error; e != nil { |
| return dashboard.Response{}, e |
| @@ -51,6 +60,13 @@ func (a *App) dashboardEvents(ctx context.Context, id int64, _ string, now time. |
| if e != nil { |
| return dashboard.Response{}, e |
| } |
| + // Unknown standing is unavailable, not a short list: the feed is read |
| + // on another origin, by a reader who never sees a view's partial |
| + // notice (teammode-package.md §4, condition 3). Asked after reading, |
| + // of the same Access, because a lease can lapse during it. |
| + if standing != nil && standing.Partial() { |
| + return dashboard.Response{}, dashboard.ErrUnavailable |
| + } |
| out := dashboard.Response{Timezone: zone} |
| for _, event := range rows { |
| if event.Status == "cancelled" || (!event.AllDay && (event.OccEndUTC <= now.Unix() || event.OccStartUTC >= until.Unix())) { |
diff --git a/internal/calendar/handlers.go b/internal/calendar/handlers.go| index f29f383..c4e676c 100644 |
| --- a/internal/calendar/handlers.go |
| +++ b/internal/calendar/handlers.go |
| @@ -5,6 +5,7 @@ import ( |
| "log/slog" |
| "net/http" |
| + "amadan.net/oficina/home/teammode" |
| rauth "amadan.net/rastrillo/rastrillo/auth" |
| "amadan.net/rastrillo/rastrillo/mail" |
| ) |
| @@ -31,6 +32,12 @@ type handlers struct { |
| gate *gate |
| viewerFrom func(*http.Request) (rauth.Identity, bool) |
| + // team is the roster runtime in team mode, nil otherwise (App.team); |
| + // standingOf asks it about somebody other than the request's own |
| + // person (App.standingOf), nil outside team mode. |
| + team *teamRuntime |
| + standingOf func(context.Context, int64) *teammode.Access |
| + |
| // homeLinked is Bridge.Linked with Home configured, nil without it: |
| // whether a person already has a stored link (offerHomeConnect). |
| homeLinked func(context.Context, int64) (bool, error) |
diff --git a/internal/calendar/handlers_booking_manage.go b/internal/calendar/handlers_booking_manage.go| index af1b9c9..7c5c6f7 100644 |
| --- a/internal/calendar/handlers_booking_manage.go |
| +++ b/internal/calendar/handlers_booking_manage.go |
| @@ -75,6 +75,7 @@ func (h *handlers) bookManage(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + r = h.bookersOwn(r) |
| h.renderState(w, r, v, token) |
| } |
| @@ -84,6 +85,9 @@ func (h *handlers) bookConfirm(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if r, ok = h.hostStanding(w, r, v.Host); !ok { |
| + return |
| + } |
| now := time.Now() |
| changed, err := h.store.ConfirmBooking(r.Context(), v.ID, now) |
| if err != nil { |
| @@ -108,6 +112,7 @@ func (h *handlers) bookICS(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + r = h.bookersOwn(r) |
| if v.State != BookingConfirmed && v.State != BookingCancelled { |
| notFoundLikeTheRouter(w, r) |
| return |
| @@ -128,6 +133,9 @@ func (h *handlers) bookReschedulePicker(w http.ResponseWriter, r *http.Request) |
| if !ok { |
| return |
| } |
| + if r, ok = h.hostStanding(w, r, v.Host); !ok { |
| + return |
| + } |
| if !v.Live() { |
| h.renderState(w, r, v, token) |
| return |
| @@ -165,6 +173,9 @@ func (h *handlers) bookReschedule(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if r, ok = h.hostStanding(w, r, v.Host); !ok { |
| + return |
| + } |
| r.Body = http.MaxBytesReader(w, r.Body, 16<<10) |
| if err := r.ParseForm(); err != nil { |
| http.Error(w, "That form was too large.", http.StatusUnprocessableEntity) |
| @@ -218,6 +229,7 @@ func (h *handlers) bookCancel(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + r = h.bookersOwn(r) |
| now := time.Now() |
| changed, err := h.store.CancelBooking(r.Context(), v.ID, CancelledByBooker, now) |
| if err != nil { |
diff --git a/internal/calendar/handlers_booking_public.go b/internal/calendar/handlers_booking_public.go| index d7a8d40..337b665 100644 |
| --- a/internal/calendar/handlers_booking_public.go |
| +++ b/internal/calendar/handlers_booking_public.go |
| @@ -132,6 +132,13 @@ func (h *handlers) picker(w http.ResponseWriter, r *http.Request, page BookingPa |
| t, _ := time.ParseInLocation(LayoutDate, date, bookerLoc) |
| d.Days = append(d.Days, bookDay{Date: date, Label: t.Format("Monday 2 January"), Count: counts[date]}) |
| } |
| + if standingLapsed(r.Context()) { |
| + // Team mode: the host's lease ran out while free time was being |
| + // worked out, so busy may have been read short. Never offer it |
| + // (B23's fail-closed, team_booking.go). |
| + teamUnavailablePlain(w) |
| + return d, false |
| + } |
| return d, true |
| } |
| @@ -141,6 +148,9 @@ func (h *handlers) bookPage(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if r, ok = h.hostStanding(w, r, host); !ok { |
| + return |
| + } |
| zone, chosen := pickZone(r, host) |
| d, ok := h.picker(w, r, page, host, zone, strings.TrimSpace(r.URL.Query().Get("day")), 0, 0) |
| if !ok { |
| @@ -157,6 +167,9 @@ func (h *handlers) bookPost(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if r, ok = h.hostStanding(w, r, host); !ok { |
| + return |
| + } |
| r.Body = http.MaxBytesReader(w, r.Body, 16<<10) |
| if err := r.ParseForm(); err != nil { |
| http.Error(w, "That form was too large.", http.StatusUnprocessableEntity) |
diff --git a/internal/calendar/handlers_booking_settings.go b/internal/calendar/handlers_booking_settings.go| index 05c029e..4fcaaa2 100644 |
| --- a/internal/calendar/handlers_booking_settings.go |
| +++ b/internal/calendar/handlers_booking_settings.go |
| @@ -1,6 +1,7 @@ |
| package calendar |
| import ( |
| + "errors" |
| "net/http" |
| "strconv" |
| "strings" |
| @@ -20,6 +21,12 @@ type bookingPageRow struct { |
| } |
| func (h *handlers) bookingPages(w http.ResponseWriter, r *http.Request) { |
| + h.renderBookingPages(w, r, http.StatusOK) |
| +} |
| + |
| +// renderBookingPages draws the list in status: 200, or 422 for a publish a |
| +// Home-only host may not make (team_home_only.go). |
| +func (h *handlers) renderBookingPages(w http.ResponseWriter, r *http.Request, status int) { |
| p, _ := CurrentPerson(r) |
| pages, err := h.store.BookingPages(r.Context(), p.ID) |
| if err != nil { |
| @@ -38,11 +45,17 @@ func (h *handlers) bookingPages(w http.ResponseWriter, r *http.Request) { |
| } |
| rows = append(rows, row) |
| } |
| - render(w, "booking_pages", h.page(r, "Booking pages", map[string]any{ |
| - "Pages": rows, |
| - "Handle": handle, |
| - "Saved": r.URL.Query().Get("saved") == "1", |
| - })) |
| + data := h.page(r, "Booking pages", map[string]any{ |
| + "Pages": rows, |
| + "Handle": handle, |
| + "Saved": r.URL.Query().Get("saved") == "1", |
| + "NoAddress": h.noAddress(p), |
| + }) |
| + if status != http.StatusOK { |
| + renderStatus(w, "booking_pages", status, data) |
| + return |
| + } |
| + render(w, "booking_pages", data) |
| } |
| // publishBookingPage flips the switch. Publishing is deliberate: the |
| @@ -53,6 +66,10 @@ func (h *handlers) publishBookingPage(w http.ResponseWriter, r *http.Request) { |
| id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) |
| _ = r.ParseForm() |
| err := h.store.PublishBookingPage(r.Context(), p.ID, id, r.FormValue("publish") == "1") |
| + if errors.Is(err, ErrNoAddress) { |
| + h.renderBookingPages(w, r, http.StatusUnprocessableEntity) |
| + return |
| + } |
| if NotFound(err) { |
| h.errorPage(w, r, http.StatusNotFound, "") |
| return |
diff --git a/internal/calendar/handlers_events.go b/internal/calendar/handlers_events.go| index f773d76..530b271 100644 |
| --- a/internal/calendar/handlers_events.go |
| +++ b/internal/calendar/handlers_events.go |
| @@ -152,6 +152,7 @@ func (h *handlers) showEvent(w http.ResponseWriter, r *http.Request) { |
| "Zone": p.Zone, |
| "RuleText": DescribeRule(e.RRule), |
| "When": spanWords(e.StartUTC, e.EndUTC, p.Zone), |
| + "NoAddress": h.noAddress(p), |
| } |
| render(w, "event", h.page(r, e.Title, data)) |
| } |
diff --git a/internal/calendar/handlers_jobs.go b/internal/calendar/handlers_jobs.go| index 4dd0c33..79a7ac0 100644 |
| --- a/internal/calendar/handlers_jobs.go |
| +++ b/internal/calendar/handlers_jobs.go |
| @@ -121,6 +121,13 @@ func (h *handlers) drainReminderQueue(ctx context.Context, now, deadline time.Ti |
| } |
| seen[due.Queue.OccurrenceKey] = true |
| + // Team mode: only to somebody the roster says is on the team, |
| + // and who still reaches the event (team_jobs.go). |
| + if settled, err := h.settleWithoutSending(ctx, due, now); err != nil { |
| + return sent, err |
| + } else if settled { |
| + continue |
| + } |
| if err := h.sendReminder(ctx, due, now); err != nil { |
| if errors.Is(err, ErrMailBusy) { |
| // Nothing was tried: the sender is full. Back in the |
| @@ -232,6 +239,9 @@ func (h *handlers) DrainOnRequest(ctx context.Context) { |
| } |
| return |
| } |
| + if settled, err := h.settleWithoutSending(ctx, due, now); err != nil || settled { |
| + return |
| + } |
| if err := h.sendReminder(sctx, due, now); err != nil { |
| if errors.Is(err, ErrMailBusy) { |
| _, _ = h.store.DeferReminder(keep(ctx), due.Queue.ID, due.ClaimID, now.Unix()) |
diff --git a/internal/calendar/handlers_misc.go b/internal/calendar/handlers_misc.go| index d0f6d73..8eab4bd 100644 |
| --- a/internal/calendar/handlers_misc.go |
| +++ b/internal/calendar/handlers_misc.go |
| @@ -1,6 +1,7 @@ |
| package calendar |
| import ( |
| + "errors" |
| "fmt" |
| "net/http" |
| "strconv" |
| @@ -94,13 +95,23 @@ func (h *handlers) feed(w http.ResponseWriter, r *http.Request) { |
| http.NotFound(w, r) |
| return |
| } |
| - cal, err := h.store.Calendar(r.Context(), f.PersonID, f.CalendarID) |
| + // Team mode: a feed reads on its minter's standing (team_feed.go). |
| + ctx, ok := h.feedStanding(w, r, f) |
| + if !ok { |
| + return |
| + } |
| + cal, err := h.store.Calendar(ctx, f.PersonID, f.CalendarID) |
| if err != nil { |
| - http.NotFound(w, r) |
| + h.feedNotFound(w, r, ctx) |
| return |
| } |
| from, to := feedWindow() |
| - events, err := h.store.EventsForFeed(r.Context(), f.PersonID, f.CalendarID, from, to) |
| + events, err := h.store.EventsForFeed(ctx, f.PersonID, f.CalendarID, from, to) |
| + if err != nil && standingLapsed(ctx) { |
| + // Team mode: the minter's lease ran out between the two reads. |
| + teamUnavailablePlain(w) |
| + return |
| + } |
| if err != nil { |
| h.logger.Error("calendar: feed events", "err", err) |
| http.Error(w, "unavailable", http.StatusInternalServerError) |
| @@ -112,6 +123,12 @@ func (h *handlers) feed(w http.ResponseWriter, r *http.Request) { |
| h.logger.Error("calendar: feed attendees", "stage", "feed.attendees", |
| "err", scrubErr(err)) |
| } |
| + if standingLapsed(ctx) { |
| + // The minter's lease ran out while this was built: never a short |
| + // calendar to a reader that cannot see why (team_feed.go). |
| + teamUnavailablePlain(w) |
| + return |
| + } |
| body := WriteICS(cal.Name, events, r.URL.Query().Get("alarms") == "1") |
| // An ETag so a subscriber that polls every fifteen minutes usually |
| @@ -153,6 +170,12 @@ func (h *handlers) exportCalendar(w http.ResponseWriter, r *http.Request) { |
| h.fail(w, r, "export attendees", err) |
| return |
| } |
| + if requestUnknown(r) { |
| + // Team mode: a download is the whole calendar or a retry, never |
| + // one some of whose events a lapse withheld. |
| + h.teamUnavailable(w, r) |
| + return |
| + } |
| w.Header().Set("Content-Type", "text/calendar; charset=utf-8") |
| w.Header().Set("Content-Disposition", |
| fmt.Sprintf("attachment; filename=%q", safeFilename(cal.Name)+".ics")) |
| @@ -204,6 +227,12 @@ func (h *handlers) importICS(w http.ResponseWriter, r *http.Request) { |
| for _, in := range inputs { |
| in.CalendarID = calID |
| if _, err := h.store.CreateEvent(r.Context(), p.ID, in); err != nil { |
| + // Team mode: standing that lapsed mid-file stops the import |
| + // with a retry, never a count of "skipped" events that were |
| + // refused for who was importing them (team_guard.go). |
| + if h.guardRefused(w, r, err) { |
| + return |
| + } |
| // One unusable event does not fail the file. It is counted |
| // and the page says how many. |
| res.Skipped++ |
| @@ -229,7 +258,7 @@ func (h *handlers) addReminder(w http.ResponseWriter, r *http.Request) { |
| id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) |
| _ = r.ParseForm() |
| offset, _ := strconv.ParseInt(r.FormValue("offset_min"), 10, 64) |
| - if err := h.store.AddReminder(r.Context(), p.ID, id, offset); err != nil && !NotFound(err) { |
| + if err := h.store.AddReminder(r.Context(), p.ID, id, offset); err != nil && !NotFound(err) && !errors.Is(err, ErrNoAddress) { |
| h.fail(w, r, "add reminder", err) |
| return |
| } |
diff --git a/internal/calendar/handlers_settings.go b/internal/calendar/handlers_settings.go| index 6837f0f..2be3297 100644 |
| --- a/internal/calendar/handlers_settings.go |
| +++ b/internal/calendar/handlers_settings.go |
| @@ -22,6 +22,7 @@ func (h *handlers) settings(w http.ResponseWriter, r *http.Request) { |
| "Saved": r.URL.Query().Get("saved") == "1", |
| "Error": "", |
| "ErrorField": "", |
| + "NoAddress": h.noAddress(p), |
| })) |
| } |
| @@ -48,6 +49,7 @@ func (h *handlers) saveSettings(w http.ResponseWriter, r *http.Request) { |
| render(w, "settings", h.page(r, "Settings", map[string]any{ |
| "Person": p, "Zones": CommonZones, |
| "Undeliverable": undeliverable, "Error": ve.Message, "ErrorField": ve.Field, |
| + "NoAddress": h.noAddress(p), |
| })) |
| return |
| } |
diff --git a/internal/calendar/handlers_views.go b/internal/calendar/handlers_views.go| index 624e71a..f1528f8 100644 |
| --- a/internal/calendar/handlers_views.go |
| +++ b/internal/calendar/handlers_views.go |
| @@ -214,6 +214,17 @@ func (h *handlers) agenda(w http.ResponseWriter, r *http.Request) { |
| // storage we cannot grep afterwards, so nothing that identifies a |
| // person or their content goes into it. |
| func (h *handlers) fail(w http.ResponseWriter, r *http.Request, stage string, err error) { |
| + // Team mode: a write the guard refused, or a read a lapse withheld, |
| + // is a standing answer, not an internal error (team_answers.go). |
| + if h.guardRefused(w, r, err) { |
| + return |
| + } |
| + if requestUnknown(r) { |
| + // A read the lapse emptied part-way (a second lookup that no |
| + // longer finds what the first did): a retry, not our fault. |
| + h.teamUnavailable(w, r) |
| + return |
| + } |
| h.logger.Error("calendar: "+stage, "err", err) |
| h.errorPage(w, r, http.StatusInternalServerError, "") |
| } |
diff --git a/internal/calendar/home.go b/internal/calendar/home.go| index 746da72..d24e15e 100644 |
| --- a/internal/calendar/home.go |
| +++ b/internal/calendar/home.go |
| @@ -22,6 +22,7 @@ type homeConnection struct { |
| } |
| func (a *App) newHome(settings *connect.DecodedCredentials, list allowlist) (*homeConnection, error) { |
| + teamOn := a.teamOn != nil |
| writer := a.db.Writer() |
| sess, err := sessions.New(sessions.Config{DB: writer, Origin: a.cfg.Origin, Logger: a.logger}) |
| if err != nil { |
| @@ -39,7 +40,11 @@ func (a *App) newHome(settings *connect.DecodedCredentials, list allowlist) (*ho |
| if err := q.QueryRowContext(ctx, `SELECT address FROM people WHERE id=?`, id).Scan(&address); err != nil { |
| return "", err |
| } |
| - if !list.allows(address) { |
| + // Team mode: a link names who somebody is, not whether they may |
| + // enter. The roster decides that on every request |
| + // (team_access.go), so a linked person needs no place on |
| + // CALENDAR_ALLOWED_ADDRESSES to resolve. |
| + if !teamOn && !list.allows(address) { |
| return "", sql.ErrNoRows |
| } |
| return address, nil |
| @@ -75,13 +80,19 @@ func (a *App) newHome(settings *connect.DecodedCredentials, list allowlist) (*ho |
| w.WriteHeader(status) |
| _, _ = buf.WriteTo(w) |
| } |
| - b, err := connect.New(connect.Config{DB: writer, Origin: a.cfg.Origin, Issuer: settings.Issuer, ConsumerID: settings.ConsumerID, Keys: settings.Keys, DEK: settings.DEK, Namespace: "oficina/calendar", SessionCookie: sess.CookieName(), ReadSession: read, LookupLocalSession: local, LookupPerson: lookup, Render: page, Now: a.cfg.homeNow, MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| + cfg := connect.Config{DB: writer, Origin: a.cfg.Origin, Issuer: settings.Issuer, ConsumerID: settings.ConsumerID, Keys: settings.Keys, DEK: settings.DEK, Namespace: homeNamespace, SessionCookie: sess.CookieName(), ReadSession: read, LookupLocalSession: local, LookupPerson: lookup, Render: page, Now: a.cfg.homeNow, MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}) |
| - }}) |
| + }} |
| + if teamOn { |
| + // Team mode only: with both hooks nil connect is exactly what it |
| + // was (team_home_only.go). |
| + cfg.HomeOnly, cfg.Unlinked = a.teamHomeOnly(writer), a.teamUnlinked(writer) |
| + } |
| + b, err := connect.New(cfg) |
| if err != nil { |
| return nil, err |
| } |
| - routes, err := connect.NewRoutes(b, connect.RoutesConfig{Namespace: "oficina/calendar", Origin: a.cfg.Origin, Issuer: settings.Issuer, SessionCookie: sess.CookieName(), DEK: settings.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.h.signin, Protect: csrf.Protect(a.cfg.Origin), Render: page}) |
| + routes, err := connect.NewRoutes(b, connect.RoutesConfig{Namespace: homeNamespace, Origin: a.cfg.Origin, Issuer: settings.Issuer, SessionCookie: sess.CookieName(), DEK: settings.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.h.signin, Protect: csrf.Protect(a.cfg.Origin), Render: page}) |
| if err != nil { |
| return nil, err |
| } |
| @@ -137,6 +148,10 @@ func (a *App) homePerson(r *http.Request) (Person, error) { |
| // sheets' homeRequire and docs' admission check do). A storage failure is |
| // a 503, never a sign-out. |
| func (a *App) homeSignin(w http.ResponseWriter, r *http.Request) { |
| + if a.team != nil { |
| + a.teamSignin(w, r) |
| + return |
| + } |
| s, ok := a.home.sessions.From(r) |
| if ok && (s.Method == connect.HomeMethod || s.Method == "magiclink" || s.Method == "keymail") { |
| admitted := false |
diff --git a/internal/calendar/models.go b/internal/calendar/models.go| index 3a15ad9..de71b73 100644 |
| --- a/internal/calendar/models.go |
| +++ b/internal/calendar/models.go |
| @@ -81,6 +81,12 @@ type Person struct { |
| CreatedAt time.Time `gorm:"column:created_at;not null"` |
| UpdatedAt time.Time `gorm:"column:updated_at;not null"` |
| + |
| + // homeOnly is, in team mode, the Home subject of a person who has no |
| + // address here (a Home-only member: team_access.go), and "" for |
| + // everybody else. Never a column: unexported, so gorm and the |
| + // migration check never see it. |
| + homeOnly string |
| } |
| // Calendar is a container of events: one team calendar created with the |
diff --git a/internal/calendar/native.go b/internal/calendar/native.go| index 6d892ef..e268c81 100644 |
| --- a/internal/calendar/native.go |
| +++ b/internal/calendar/native.go |
| @@ -46,6 +46,10 @@ func (h *handlers) nativeSession(w http.ResponseWriter, r *http.Request) { |
| http.Error(w, "Cannot load calendars", 500) |
| return |
| } |
| + if requestUnknown(r) { |
| + h.teamUnavailable(w, r) |
| + return |
| + } |
| type cal struct { |
| ID int64 `json:"id"` |
| Name string `json:"name"` |
| @@ -103,6 +107,13 @@ func (h *handlers) nativeEvents(w http.ResponseWriter, r *http.Request) { |
| http.Error(w, "Cannot load events", 500) |
| return |
| } |
| + // Team mode: JSON has no room for a partial notice, so a list built |
| + // on standing that lapsed while building is a 503, never short |
| + // (Paul's ruling, 2026-10-28). The gate already refused Unknown. |
| + if requestUnknown(r) { |
| + h.teamUnavailable(w, r) |
| + return |
| + } |
| out := make([]nativeEvent, 0, len(events)) |
| for _, ev := range events { |
| // The first editor handles single, non-booked events; series remain intact. |
| @@ -158,7 +169,7 @@ func (h *handlers) nativeSave(w http.ResponseWriter, r *http.Request) { |
| if id != 0 { |
| ev, err := h.store.Event(r.Context(), p.ID, id) |
| if err != nil { |
| - http.NotFound(w, r) |
| + h.nativeNotFound(w, r) |
| return |
| } |
| _, booked := h.store.BookingSummaryFor(r.Context(), id) |
| @@ -170,13 +181,13 @@ func (h *handlers) nativeSave(w http.ResponseWriter, r *http.Request) { |
| value.Kind = ev.Kind |
| value.Status = ev.Status |
| if err = h.store.UpdateEvent(r.Context(), p.ID, id, value); err != nil { |
| - nativeEventError(w, r, err) |
| + h.nativeEventError(w, r, err) |
| return |
| } |
| } else { |
| ev, err := h.store.CreateEvent(r.Context(), p.ID, value) |
| if err != nil { |
| - nativeEventError(w, r, err) |
| + h.nativeEventError(w, r, err) |
| return |
| } |
| id = ev.ID |
| @@ -187,9 +198,13 @@ func (h *handlers) nativeSave(w http.ResponseWriter, r *http.Request) { |
| } |
| nativeJSON(w, map[string]any{"id": id, "saved_at": time.Now().Unix()}) |
| } |
| -func nativeEventError(w http.ResponseWriter, r *http.Request, err error) { |
| +func (h *handlers) nativeEventError(w http.ResponseWriter, r *http.Request, err error) { |
| + if standingRefusal(err) { |
| + h.guardRefused(w, r, err) |
| + return |
| + } |
| if NotFound(err) { |
| - http.NotFound(w, r) |
| + h.nativeNotFound(w, r) |
| return |
| } |
| if err == ErrReadOnly { |
| @@ -202,3 +217,14 @@ func nativeEventError(w http.ResponseWriter, r *http.Request, err error) { |
| } |
| http.Error(w, "Cannot save event", 500) |
| } |
| + |
| +// nativeNotFound is the native API's 404, or in team mode, when the |
| +// request's standing lapsed between the gate and the read, the retryable |
| +// 503 it really is (team_answers.go). |
| +func (h *handlers) nativeNotFound(w http.ResponseWriter, r *http.Request) { |
| + if requestUnknown(r) { |
| + h.teamUnavailable(w, r) |
| + return |
| + } |
| + http.NotFound(w, r) |
| +} |
diff --git a/internal/calendar/native_quick.go b/internal/calendar/native_quick.go| index a174ff6..15b2668 100644 |
| --- a/internal/calendar/native_quick.go |
| +++ b/internal/calendar/native_quick.go |
| @@ -109,7 +109,7 @@ func (h *handlers) nativeQuickSave(w http.ResponseWriter, r *http.Request) { |
| // author identity, status or raw recurrence rule is accepted from the client. |
| ev, err := h.store.CreateEvent(r.Context(), p.ID, EventInput{CalendarID: in.CalendarID, Title: in.Title, Location: in.Location, StartLocal: in.StartLocal, EndLocal: in.EndLocal, TZ: in.TZ, AllDay: in.AllDay, Kind: KindMeeting, Status: StatusConfirmed, RRule: RuleFromRepeat(in.Repeat, "", in.StartLocal, in.TZ, in.AllDay)}) |
| if err != nil { |
| - nativeEventError(w, r, err) |
| + h.nativeEventError(w, r, err) |
| return |
| } |
| warnings := []string{} |
diff --git a/internal/calendar/person.go b/internal/calendar/person.go| index 32d0b19..8ee51ad 100644 |
| --- a/internal/calendar/person.go |
| +++ b/internal/calendar/person.go |
| @@ -28,6 +28,12 @@ type personCtxKey struct{} |
| // empty calendar looks like a new account, not like a bug. |
| func (a *App) requirePerson(next http.Handler) http.Handler { |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if a.team != nil { |
| + // Team mode: the roster's standing replaces the allowlist |
| + // recheck below (team_access.go). |
| + a.teamRequirePerson(w, r, next) |
| + return |
| + } |
| if session, ok := sessions.Current(r); ok && session.Method == connect.HomeMethod { |
| if a.home == nil { |
| a.h.errorPage(w, r, http.StatusNotFound, "") |
diff --git a/internal/calendar/render.go b/internal/calendar/render.go| index 5e2c580..1b30946 100644 |
| --- a/internal/calendar/render.go |
| +++ b/internal/calendar/render.go |
| @@ -130,6 +130,7 @@ type PageData struct { |
| HomeEnabled bool |
| SignedIn bool |
| Address string |
| + Partial bool // team mode's partial view (team_answers.go) |
| // QuickPane is the quick-add box's first paint. It is on the SHELL |
| // rather than on each page's own data because the box is in the |
| @@ -153,6 +154,7 @@ func (h *handlers) page(r *http.Request, title string, data any) PageData { |
| Path: r.URL.Path, |
| QuickPane: emptyPane(), |
| Data: data, |
| + Partial: h.team != nil && requestUnknown(r), |
| } |
| if id, ok := h.viewer(r); ok { |
| pd.SignedIn = true |
| @@ -219,6 +221,10 @@ func ErrorPage(w http.ResponseWriter, r *http.Request, status int, ref string) { |
| // live session whose person cannot be resolved still gets the account |
| // menu, to sign out from, with no identity in it. |
| func (h *handlers) errorPage(w http.ResponseWriter, r *http.Request, status int, ref string) { |
| + if status == http.StatusNotFound && requestUnknown(r) { |
| + h.teamUnavailable(w, r) // team mode: retry, never "not found" |
| + return |
| + } |
| id, ok := h.viewer(r) |
| _, session := sessions.Current(r) |
| if !ok { |
diff --git a/internal/calendar/routes.go b/internal/calendar/routes.go| index 3007079..fbdae4f 100644 |
| --- a/internal/calendar/routes.go |
| +++ b/internal/calendar/routes.go |
| @@ -6,6 +6,7 @@ import ( |
| "amadan.net/oficina/estilo.git/theme" |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/teammode" |
| "net/http" |
| "github.com/go-chi/chi/v5" |
| @@ -41,6 +42,10 @@ func (a *App) routes(h *handlers, authPlugin *rauth.Auth, list allowlist, origin |
| if a.dashboard != nil { |
| r.Handle("/api/oficina/dashboard", a.dashboard) |
| } |
| + // Team mode's readiness probe (team_answers.go), unauthenticated: |
| + // {"team_mode":false} with team mode off, as Docs', Sheets' and |
| + // Slides' are (Paul's ruling on oficina/sheets #52, deviation 5). |
| + r.Get(teammode.ProbePath, a.teamProbe) |
| r.Get("/help/open-source", h.credits) |
| r.NotFound(h.notFound) |
| @@ -118,62 +123,21 @@ func (a *App) routes(h *handlers, authPlugin *rauth.Auth, list allowlist, origin |
| r.Use(a.requirePerson) |
| r.Use(h.drainOpportunistically) |
| - r.Post("/api/native/quick/parse", h.nativeQuickParse) |
| - r.Post("/api/native/quick", h.nativeQuickSave) |
| - r.Get("/api/native/session", h.nativeSession) |
| - r.Get("/api/native/events", h.nativeEvents) |
| - r.Post("/api/native/events", h.nativeSave) |
| - r.Post("/api/native/events/{id}", h.nativeSave) |
| - |
| - r.Get("/", h.today) |
| - r.Get("/today", h.today) |
| - r.Get("/day/{date}", h.day) |
| - r.Get("/week/{date}", h.week) |
| - r.Get("/month/{month}", h.month) |
| - r.Get("/agenda", h.agenda) |
| - |
| - r.Get("/events/new", h.newEvent) |
| - r.Post("/events", h.createEvent) |
| - // Quick add. Both are literal segments and both are declared |
| - // BEFORE /events/{id}, so a sentence can never be mistaken for |
| - // an event id. |
| - r.Post("/events/quick", h.quickAdd) |
| - r.Post("/events/quick/parse", h.quickParse) |
| - r.Get("/events/{id}", h.showEvent) |
| - r.Get("/events/{id}/edit", h.editEvent) |
| - r.Post("/events/{id}", h.updateEvent) |
| - // The destructive action gets its own URL and its own page, |
| - // never a modal: it works with no script, it can be linked to, |
| - // and the browser's back button is a working cancel. |
| - r.Get("/events/{id}/delete", h.confirmDelete) |
| - r.Post("/events/{id}/delete", h.deleteEvent) |
| - r.Post("/events/{id}/reminders", h.addReminder) |
| - r.Post("/events/{id}/reminders/remove", h.removeReminder) |
| - // One occurrence of a series. Last, so it cannot shadow the |
| - // literal segments above. |
| - r.Get("/events/{id}/{occ}", h.showEvent) |
| - |
| - r.Get("/calendars", h.calendars) |
| - r.Get("/calendars/{id}.ics", h.exportCalendar) |
| - r.Get("/calendars/{id}/share", h.share) |
| - r.Post("/calendars/{id}/feeds", h.mintFeed) |
| - r.Post("/calendars/{id}/feeds/revoke", h.revokeFeed) |
| - |
| - r.Get("/import", h.importForm) |
| - r.Post("/import", h.importICS) |
| - |
| - r.Get("/settings", h.settings) |
| - r.Post("/settings", h.saveSettings) |
| - |
| - // Booking pages, the host's side. Person-scoped throughout: a |
| - // page id that is not yours 404s (booking spec §2.6). |
| - r.Get("/settings/booking", h.bookingPages) |
| - r.Get("/settings/booking/new", h.newBookingPage) |
| - r.Post("/settings/booking", h.saveBookingPage) |
| - r.Post("/settings/booking/parse", h.bookingParse) |
| - r.Get("/settings/booking/{id}", h.editBookingPage) |
| - r.Post("/settings/booking/{id}", h.saveBookingPage) |
| - r.Post("/settings/booking/{id}/publish", h.publishBookingPage) |
| + // Team mode: the views render partial under Unknown standing; |
| + // every other route here needs Member (team_access.go). Outside |
| + // team mode both gates are next, unchanged. |
| + r.With(a.standing(needListing)).Get("/", h.today) |
| + r.With(a.standing(needListing)).Get("/today", h.today) |
| + r.With(a.standing(needListing)).Get("/day/{date}", h.day) |
| + r.With(a.standing(needListing)).Get("/week/{date}", h.week) |
| + r.With(a.standing(needListing)).Get("/month/{month}", h.month) |
| + r.With(a.standing(needListing)).Get("/agenda", h.agenda) |
| + r.With(a.standing(needListing)).Get("/calendars", h.calendars) |
| + |
| + r.Group(func(r chi.Router) { |
| + r.Use(a.standing(needMember)) |
| + a.memberRoutes(r, h) |
| + }) |
| }) |
| mux := http.NewServeMux() |
| @@ -215,3 +179,57 @@ func (a *App) routes(h *handlers, authPlugin *rauth.Auth, list allowlist, origin |
| func (a *App) mountTick(mux *http.ServeMux, h *handlers) { |
| mux.Handle("POST /jobs/reminders", http.HandlerFunc(h.drainReminders)) |
| } |
| + |
| +// memberRoutes are the session group's routes that need Member in team |
| +// mode (team_access.go): every form, item page, write and the native API. |
| +// Outside team mode the gate in front of them is next, unchanged. |
| +func (a *App) memberRoutes(r chi.Router, h *handlers) { |
| + r.Post("/api/native/quick/parse", h.nativeQuickParse) |
| + r.Post("/api/native/quick", h.nativeQuickSave) |
| + r.Get("/api/native/session", h.nativeSession) |
| + r.Get("/api/native/events", h.nativeEvents) |
| + r.Post("/api/native/events", h.nativeSave) |
| + r.Post("/api/native/events/{id}", h.nativeSave) |
| + |
| + r.Get("/events/new", h.newEvent) |
| + r.Post("/events", h.createEvent) |
| + // Quick add. Both are literal segments and both are declared |
| + // BEFORE /events/{id}, so a sentence can never be mistaken for |
| + // an event id. |
| + r.Post("/events/quick", h.quickAdd) |
| + r.Post("/events/quick/parse", h.quickParse) |
| + r.Get("/events/{id}", h.showEvent) |
| + r.Get("/events/{id}/edit", h.editEvent) |
| + r.Post("/events/{id}", h.updateEvent) |
| + // The destructive action gets its own URL and its own page, |
| + // never a modal: it works with no script, it can be linked to, |
| + // and the browser's back button is a working cancel. |
| + r.Get("/events/{id}/delete", h.confirmDelete) |
| + r.Post("/events/{id}/delete", h.deleteEvent) |
| + r.Post("/events/{id}/reminders", h.addReminder) |
| + r.Post("/events/{id}/reminders/remove", h.removeReminder) |
| + // One occurrence of a series. Last, so it cannot shadow the |
| + // literal segments above. |
| + r.Get("/events/{id}/{occ}", h.showEvent) |
| + |
| + r.Get("/calendars/{id}.ics", h.exportCalendar) |
| + r.Get("/calendars/{id}/share", h.share) |
| + r.Post("/calendars/{id}/feeds", h.mintFeed) |
| + r.Post("/calendars/{id}/feeds/revoke", h.revokeFeed) |
| + |
| + r.Get("/import", h.importForm) |
| + r.Post("/import", h.importICS) |
| + |
| + r.Get("/settings", h.settings) |
| + r.Post("/settings", h.saveSettings) |
| + |
| + // Booking pages, the host's side. Person-scoped throughout: a |
| + // page id that is not yours 404s (booking spec §2.6). |
| + r.Get("/settings/booking", h.bookingPages) |
| + r.Get("/settings/booking/new", h.newBookingPage) |
| + r.Post("/settings/booking", h.saveBookingPage) |
| + r.Post("/settings/booking/parse", h.bookingParse) |
| + r.Get("/settings/booking/{id}", h.editBookingPage) |
| + r.Post("/settings/booking/{id}", h.saveBookingPage) |
| + r.Post("/settings/booking/{id}/publish", h.publishBookingPage) |
| +} |
diff --git a/internal/calendar/signin.go b/internal/calendar/signin.go| index 36f6518..44dce25 100644 |
| --- a/internal/calendar/signin.go |
| +++ b/internal/calendar/signin.go |
| @@ -105,6 +105,13 @@ func (h *handlers) renderSignin(w http.ResponseWriter, r *http.Request, status i |
| } |
| switch q.Get("err") { |
| case "": |
| + case "removed": |
| + // Team mode's offboard lands here (team_access.go). Outside |
| + // team mode nothing sends it, and it reads as any other err. |
| + form.Error = "That link did not work. Ask for a new one." |
| + if h.team != nil { |
| + form.Error = "You’re no longer on this team, so its calendar is closed to you. If that’s a mistake, ask a team owner." |
| + } |
| case "rate": |
| form.Error = "Too many attempts. Wait a few minutes, then try again." |
| case "address": |
diff --git a/internal/calendar/store.go b/internal/calendar/store.go| index 397fd97..2428629 100644 |
| --- a/internal/calendar/store.go |
| +++ b/internal/calendar/store.go |
| @@ -28,6 +28,13 @@ type Store struct { |
| seal *seal.Sealer |
| logger *slog.Logger |
| + // team is true in roster team mode: every scoped read joins through |
| + // the team rung only while the context's standing is Member |
| + // (team_reach.go), and every person's write is guarded inside its |
| + // transaction (team_guard.go). False, and both are exactly what they |
| + // were. |
| + team bool |
| + |
| // holdMu serialises hold creation and rescheduling (booking spec |
| // B12). SQLite begins deferred, so two transactions can both read |
| // "free" before either takes the write lock; one process per |
diff --git a/internal/calendar/store_attendee.go b/internal/calendar/store_attendee.go| index 877f3df..95781f8 100644 |
| --- a/internal/calendar/store_attendee.go |
| +++ b/internal/calendar/store_attendee.go |
| @@ -16,7 +16,7 @@ import ( |
| // current caller comes straight off Store.Event or Store.CreateEvent, |
| // both of which 404 a row that is not yours. |
| func (s *Store) SetAttendees(ctx context.Context, eventID int64, addresses []string) error { |
| - return s.setAttendeesOn(s.g.WithContext(ctx), eventID, addresses) |
| + return s.guarded(ctx, func(db *gorm.DB) error { return s.setAttendeesOn(db, eventID, addresses) }) |
| } |
| // setAttendeesOn is SetAttendees on a caller's transaction, so a |
diff --git a/internal/calendar/store_booking_cancel.go b/internal/calendar/store_booking_cancel.go| index 7fd9d36..3e84d45 100644 |
| --- a/internal/calendar/store_booking_cancel.go |
| +++ b/internal/calendar/store_booking_cancel.go |
| @@ -16,23 +16,25 @@ import ( |
| // (booking spec §5.6, §5.7). A second press affects zero rows. |
| func (s *Store) CancelBooking(ctx context.Context, bookingID int64, by string, now time.Time) (changed bool, err error) { |
| err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - var b Booking |
| - if err := tx.First(&b, bookingID).Error; err != nil { |
| - return fmt.Errorf("calendar: read booking: %w", err) |
| - } |
| - n, err := cancelBookingOn(tx, b, by, now) |
| - if err != nil { |
| - return err |
| - } |
| - if n == 0 { |
| + return s.guard(ctx, func() error { |
| + var b Booking |
| + if err := tx.First(&b, bookingID).Error; err != nil { |
| + return fmt.Errorf("calendar: read booking: %w", err) |
| + } |
| + n, err := cancelBookingOn(tx, b, by, now) |
| + if err != nil { |
| + return err |
| + } |
| + if n == 0 { |
| + return nil |
| + } |
| + changed = true |
| + if err := tx.Model(&Event{}).Where("id = ? AND deleted_at IS NULL", b.EventID). |
| + Updates(map[string]any{"status": StatusCancelled, "sequence": gorm.Expr("sequence + 1"), "updated_at": now.UTC()}).Error; err != nil { |
| + return fmt.Errorf("calendar: cancel booked event: %w", err) |
| + } |
| return nil |
| - } |
| - changed = true |
| - if err := tx.Model(&Event{}).Where("id = ? AND deleted_at IS NULL", b.EventID). |
| - Updates(map[string]any{"status": StatusCancelled, "sequence": gorm.Expr("sequence + 1"), "updated_at": now.UTC()}).Error; err != nil { |
| - return fmt.Errorf("calendar: cancel booked event: %w", err) |
| - } |
| - return nil |
| + }) |
| }) |
| return changed, err |
| } |
diff --git a/internal/calendar/store_booking_confirm.go b/internal/calendar/store_booking_confirm.go| index 264e99d..106c753 100644 |
| --- a/internal/calendar/store_booking_confirm.go |
| +++ b/internal/calendar/store_booking_confirm.go |
| @@ -25,42 +25,44 @@ func (s *Store) ConfirmBooking(ctx context.Context, bookingID int64, now time.Ti |
| var b Booking |
| var e Event |
| err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - if err := tx.First(&b, bookingID).Error; err != nil { |
| - return fmt.Errorf("calendar: read booking: %w", err) |
| - } |
| - if err := tx.First(&e, b.EventID).Error; err != nil { |
| - return fmt.Errorf("calendar: read booked event: %w", err) |
| - } |
| - res := tx.Model(&Booking{}). |
| - Where("id = ? AND state = ? AND hold_expires_at > ? AND ? < ?", bookingID, BookingHeld, now.Unix(), now.Unix(), e.StartUTC). |
| - Updates(map[string]any{"state": BookingConfirmed, "confirmed_at": now.Unix(), "updated_at": now.UTC()}) |
| - if res.Error != nil { |
| - return fmt.Errorf("calendar: confirm booking: %w", res.Error) |
| - } |
| - if res.RowsAffected == 0 { |
| - return nil |
| - } |
| - changed = true |
| - if err := tx.Model(&Event{}).Where("id = ?", e.ID). |
| - Updates(map[string]any{"status": StatusConfirmed, "sequence": gorm.Expr("sequence + 1"), "updated_at": now.UTC()}).Error; err != nil { |
| - return fmt.Errorf("calendar: confirm booked event: %w", err) |
| - } |
| - if err := tx.First(&e, e.ID).Error; err != nil { |
| - return err |
| - } |
| - addr, err := s.openBookerAddress(b) |
| - if err != nil { |
| - return err |
| - } |
| - if err := s.setAttendeesOn(tx, e.ID, []string{addr}); err != nil { |
| - return err |
| - } |
| - // An owed hold mail is now false: forgotten here, not merely |
| - // skipped later. |
| - if err := deleteUnsentMail(tx, bookingID, MailHold); err != nil { |
| - return err |
| - } |
| - return queueBookingMail(tx, bookingID, MailConfirmed, []string{ToHost}, e.Sequence, now) |
| + return s.guard(ctx, func() error { |
| + if err := tx.First(&b, bookingID).Error; err != nil { |
| + return fmt.Errorf("calendar: read booking: %w", err) |
| + } |
| + if err := tx.First(&e, b.EventID).Error; err != nil { |
| + return fmt.Errorf("calendar: read booked event: %w", err) |
| + } |
| + res := tx.Model(&Booking{}). |
| + Where("id = ? AND state = ? AND hold_expires_at > ? AND ? < ?", bookingID, BookingHeld, now.Unix(), now.Unix(), e.StartUTC). |
| + Updates(map[string]any{"state": BookingConfirmed, "confirmed_at": now.Unix(), "updated_at": now.UTC()}) |
| + if res.Error != nil { |
| + return fmt.Errorf("calendar: confirm booking: %w", res.Error) |
| + } |
| + if res.RowsAffected == 0 { |
| + return nil |
| + } |
| + changed = true |
| + if err := tx.Model(&Event{}).Where("id = ?", e.ID). |
| + Updates(map[string]any{"status": StatusConfirmed, "sequence": gorm.Expr("sequence + 1"), "updated_at": now.UTC()}).Error; err != nil { |
| + return fmt.Errorf("calendar: confirm booked event: %w", err) |
| + } |
| + if err := tx.First(&e, e.ID).Error; err != nil { |
| + return err |
| + } |
| + addr, err := s.openBookerAddress(b) |
| + if err != nil { |
| + return err |
| + } |
| + if err := s.setAttendeesOn(tx, e.ID, []string{addr}); err != nil { |
| + return err |
| + } |
| + // An owed hold mail is now false: forgotten here, not merely |
| + // skipped later. |
| + if err := deleteUnsentMail(tx, bookingID, MailHold); err != nil { |
| + return err |
| + } |
| + return queueBookingMail(tx, bookingID, MailConfirmed, []string{ToHost}, e.Sequence, now) |
| + }) |
| }) |
| if err != nil || !changed { |
| return false, err |
| @@ -120,63 +122,65 @@ func (s *Store) RescheduleBooking(ctx context.Context, bookingID, startUTC, endU |
| } |
| err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - if err := tx.Exec(`UPDATE booking_pages SET updated_at = updated_at WHERE id = ?`, v.PageID).Error; err != nil { |
| - return fmt.Errorf("calendar: take write lock: %w", err) |
| - } |
| - // The page, its windows and the host as they are NOW, behind |
| - // the lock: windows the host has since withdrawn cannot be |
| - // moved into, and tz below is the zone the slot was computed |
| - // in (B21), so compute it there. currentPageOn refuses an |
| - // unpublished page, which is the host's way of closing it. |
| - page, host, err := s.currentPageOn(tx, v.PageID) |
| - if err != nil { |
| - return err |
| - } |
| - v.Page, v.Host = page, host |
| - if loc, err = Zone(v.Host.Zone); err != nil { |
| - return err |
| - } |
| - again, err := s.freeSlotsOn(tx, v.Page, v.Host, now, day, dayEnd, v.EventID, dur) |
| - if err != nil { |
| - return err |
| - } |
| - if !hasSlot(again, startUTC, endUTC) { |
| - return ErrSlotTaken |
| - } |
| - res := tx.Model(&Event{}). |
| - Where("id = ? AND sequence = ? AND deleted_at IS NULL AND status = ?", v.EventID, rev, StatusConfirmed). |
| - Updates(map[string]any{ |
| - "start_local": FormatLocal(time.Unix(startUTC, 0).In(loc), false), |
| - "end_local": FormatLocal(time.Unix(endUTC, 0).In(loc), false), |
| - "tz": v.Host.Zone, |
| - "start_utc": startUTC, |
| - "end_utc": endUTC, |
| - "sequence": gorm.Expr("sequence + 1"), |
| - "updated_at": now.UTC(), |
| - }) |
| - if res.Error != nil { |
| - return fmt.Errorf("calendar: move booked event: %w", res.Error) |
| - } |
| - if res.RowsAffected == 0 { |
| - return nil |
| - } |
| - changed = true |
| - cnt := tx.Model(&Booking{}). |
| - Where("id = ? AND state = ?", bookingID, BookingConfirmed). |
| - Updates(map[string]any{"reschedules": gorm.Expr("reschedules + 1"), "updated_at": now.UTC()}) |
| - if cnt.Error != nil { |
| - return fmt.Errorf("calendar: count reschedule: %w", cnt.Error) |
| - } |
| - if cnt.RowsAffected == 0 { |
| - return errClaimLost // cancelled under us; the event UPDATE above rolls back with this |
| - } |
| - if err := s.rescheduleAllForTx(tx, v.EventID); err != nil { |
| - return err |
| - } |
| - if err := deleteUnsentMail(tx, bookingID, MailRescheduled); err != nil { |
| - return err |
| - } |
| - return queueBookingMail(tx, bookingID, MailRescheduled, []string{ToBooker, ToHost}, rev+1, now) |
| + return s.guard(ctx, func() error { |
| + if err := tx.Exec(`UPDATE booking_pages SET updated_at = updated_at WHERE id = ?`, v.PageID).Error; err != nil { |
| + return fmt.Errorf("calendar: take write lock: %w", err) |
| + } |
| + // The page, its windows and the host as they are NOW, behind |
| + // the lock: windows the host has since withdrawn cannot be |
| + // moved into, and tz below is the zone the slot was computed |
| + // in (B21), so compute it there. currentPageOn refuses an |
| + // unpublished page, which is the host's way of closing it. |
| + page, host, err := s.currentPageOn(tx, v.PageID) |
| + if err != nil { |
| + return err |
| + } |
| + v.Page, v.Host = page, host |
| + if loc, err = Zone(v.Host.Zone); err != nil { |
| + return err |
| + } |
| + again, err := s.freeSlotsOn(tx, v.Page, v.Host, now, day, dayEnd, v.EventID, dur) |
| + if err != nil { |
| + return err |
| + } |
| + if !hasSlot(again, startUTC, endUTC) { |
| + return ErrSlotTaken |
| + } |
| + res := tx.Model(&Event{}). |
| + Where("id = ? AND sequence = ? AND deleted_at IS NULL AND status = ?", v.EventID, rev, StatusConfirmed). |
| + Updates(map[string]any{ |
| + "start_local": FormatLocal(time.Unix(startUTC, 0).In(loc), false), |
| + "end_local": FormatLocal(time.Unix(endUTC, 0).In(loc), false), |
| + "tz": v.Host.Zone, |
| + "start_utc": startUTC, |
| + "end_utc": endUTC, |
| + "sequence": gorm.Expr("sequence + 1"), |
| + "updated_at": now.UTC(), |
| + }) |
| + if res.Error != nil { |
| + return fmt.Errorf("calendar: move booked event: %w", res.Error) |
| + } |
| + if res.RowsAffected == 0 { |
| + return nil |
| + } |
| + changed = true |
| + cnt := tx.Model(&Booking{}). |
| + Where("id = ? AND state = ?", bookingID, BookingConfirmed). |
| + Updates(map[string]any{"reschedules": gorm.Expr("reschedules + 1"), "updated_at": now.UTC()}) |
| + if cnt.Error != nil { |
| + return fmt.Errorf("calendar: count reschedule: %w", cnt.Error) |
| + } |
| + if cnt.RowsAffected == 0 { |
| + return errClaimLost // cancelled under us; the event UPDATE above rolls back with this |
| + } |
| + if err := s.rescheduleAllForTx(tx, v.EventID); err != nil { |
| + return err |
| + } |
| + if err := deleteUnsentMail(tx, bookingID, MailRescheduled); err != nil { |
| + return err |
| + } |
| + return queueBookingMail(tx, bookingID, MailRescheduled, []string{ToBooker, ToHost}, rev+1, now) |
| + }) |
| }) |
| if errors.Is(err, errClaimLost) { |
| return false, nil |
diff --git a/internal/calendar/store_booking_flow.go b/internal/calendar/store_booking_flow.go| index 64307a9..ebde5c5 100644 |
| --- a/internal/calendar/store_booking_flow.go |
| +++ b/internal/calendar/store_booking_flow.go |
| @@ -159,83 +159,85 @@ func (s *Store) holdOnce(ctx context.Context, in HoldInput, addrFP string, day, |
| var b Booking |
| err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - // The write lock, before any read this decision depends on. |
| - if err := tx.Exec(`UPDATE booking_pages SET updated_at = updated_at WHERE id = ?`, in.Page.ID).Error; err != nil { |
| - return fmt.Errorf("calendar: take write lock: %w", err) |
| - } |
| - // The page, its windows and the host as they are NOW, behind |
| - // the lock: a page unpublished or a host who moved zone since |
| - // the request read them must not be booked against. |
| - page, host, err := s.currentPageOn(tx, in.Page.ID) |
| - if err != nil { |
| - return err |
| - } |
| - in.Page, in.Host = page, host |
| - loc, err = Zone(host.Zone) |
| - if err != nil { |
| - return err |
| - } |
| - // The snapshot is sealed from the page AS RE-READ, so the |
| - // booking's title and the event's title come from one version |
| - // of it. |
| - sealed, err := s.sealBooker(in, token) |
| - if err != nil { |
| - return err |
| - } |
| - again, err := s.freeSlotsOn(tx, page, host, now, day, dayEnd, 0, 0) |
| - if err != nil { |
| - return err |
| - } |
| - if !hasSlot(again, in.StartUTC, in.EndUTC) { |
| - return ErrSlotTaken |
| - } |
| + return s.guard(ctx, func() error { |
| + // The write lock, before any read this decision depends on. |
| + if err := tx.Exec(`UPDATE booking_pages SET updated_at = updated_at WHERE id = ?`, in.Page.ID).Error; err != nil { |
| + return fmt.Errorf("calendar: take write lock: %w", err) |
| + } |
| + // The page, its windows and the host as they are NOW, behind |
| + // the lock: a page unpublished or a host who moved zone since |
| + // the request read them must not be booked against. |
| + page, host, err := s.currentPageOn(tx, in.Page.ID) |
| + if err != nil { |
| + return err |
| + } |
| + in.Page, in.Host = page, host |
| + loc, err = Zone(host.Zone) |
| + if err != nil { |
| + return err |
| + } |
| + // The snapshot is sealed from the page AS RE-READ, so the |
| + // booking's title and the event's title come from one version |
| + // of it. |
| + sealed, err := s.sealBooker(in, token) |
| + if err != nil { |
| + return err |
| + } |
| + again, err := s.freeSlotsOn(tx, page, host, now, day, dayEnd, 0, 0) |
| + if err != nil { |
| + return err |
| + } |
| + if !hasSlot(again, in.StartUTC, in.EndUTC) { |
| + return ErrSlotTaken |
| + } |
| - calID, err := s.defaultCalendarOn(tx, in.Host.ID) |
| - if err != nil { |
| - return err |
| - } |
| - e, err := s.buildEvent(in.Host.ID, EventInput{ |
| - CalendarID: calID, |
| - Title: in.Page.Title + " — " + in.Name, |
| - Notes: in.Note, |
| - StartLocal: FormatLocal(time.Unix(in.StartUTC, 0).In(loc), false), |
| - EndLocal: FormatLocal(time.Unix(in.EndUTC, 0).In(loc), false), |
| - TZ: in.Host.Zone, |
| - Kind: KindMeeting, |
| - Status: StatusTentative, |
| - }) |
| - if err != nil { |
| - return err |
| - } |
| - if err := tx.Create(&e).Error; err != nil { |
| - return fmt.Errorf("calendar: create held event: %w", err) |
| - } |
| + calID, err := s.defaultCalendarOn(tx, in.Host.ID) |
| + if err != nil { |
| + return err |
| + } |
| + e, err := s.buildEvent(in.Host.ID, EventInput{ |
| + CalendarID: calID, |
| + Title: in.Page.Title + " — " + in.Name, |
| + Notes: in.Note, |
| + StartLocal: FormatLocal(time.Unix(in.StartUTC, 0).In(loc), false), |
| + EndLocal: FormatLocal(time.Unix(in.EndUTC, 0).In(loc), false), |
| + TZ: in.Host.Zone, |
| + Kind: KindMeeting, |
| + Status: StatusTentative, |
| + }) |
| + if err != nil { |
| + return err |
| + } |
| + if err := tx.Create(&e).Error; err != nil { |
| + return fmt.Errorf("calendar: create held event: %w", err) |
| + } |
| - expires := now.Add(HoldTTL).Unix() |
| - if in.StartUTC < expires { |
| - expires = in.StartUTC // B15: never confirmable after it starts |
| - } |
| - ipfp := in.IPFP |
| - b = Booking{ |
| - PageID: in.Page.ID, EventID: e.ID, |
| - TokenHash: HashFeedToken(token), TokenSealed: sealed.token, |
| - State: BookingHeld, |
| - TitleSealed: sealed.title, |
| - DescriptionSealed: sealed.description, |
| - BookerNameSealed: sealed.name, BookerAddressSealed: sealed.address, |
| - BookerAddressFP: addrFP, NoteSealed: sealed.note, |
| - BookerZone: in.BookerZone, |
| - HoldExpiresAt: expires, |
| - IPFP: &ipfp, IPForgetAt: now.Add(IPForgetAfter).Unix(), |
| - CreatedAt: now.UTC(), UpdatedAt: now.UTC(), |
| - } |
| - if err := tx.Create(&b).Error; err != nil { |
| - if isUniqueViolation(err) { |
| - return errTokenCollision |
| + expires := now.Add(HoldTTL).Unix() |
| + if in.StartUTC < expires { |
| + expires = in.StartUTC // B15: never confirmable after it starts |
| } |
| - return fmt.Errorf("calendar: create booking: %w", err) |
| - } |
| - return queueBookingMail(tx, b.ID, MailHold, []string{ToBooker}, 0, now) |
| + ipfp := in.IPFP |
| + b = Booking{ |
| + PageID: in.Page.ID, EventID: e.ID, |
| + TokenHash: HashFeedToken(token), TokenSealed: sealed.token, |
| + State: BookingHeld, |
| + TitleSealed: sealed.title, |
| + DescriptionSealed: sealed.description, |
| + BookerNameSealed: sealed.name, BookerAddressSealed: sealed.address, |
| + BookerAddressFP: addrFP, NoteSealed: sealed.note, |
| + BookerZone: in.BookerZone, |
| + HoldExpiresAt: expires, |
| + IPFP: &ipfp, IPForgetAt: now.Add(IPForgetAfter).Unix(), |
| + CreatedAt: now.UTC(), UpdatedAt: now.UTC(), |
| + } |
| + if err := tx.Create(&b).Error; err != nil { |
| + if isUniqueViolation(err) { |
| + return errTokenCollision |
| + } |
| + return fmt.Errorf("calendar: create booking: %w", err) |
| + } |
| + return queueBookingMail(tx, b.ID, MailHold, []string{ToBooker}, 0, now) |
| + }) |
| }) |
| if err != nil { |
| return Booking{}, err |
diff --git a/internal/calendar/store_booking_handle.go b/internal/calendar/store_booking_handle.go| index 9c3b621..ab0cffa 100644 |
| --- a/internal/calendar/store_booking_handle.go |
| +++ b/internal/calendar/store_booking_handle.go |
| @@ -59,8 +59,10 @@ func (s *Store) SaveHandle(ctx context.Context, personID int64, handle string) e |
| h := normalizeHandle(handle) |
| now := time.Now().UTC() |
| if h == "" { |
| - err := s.g.WithContext(ctx).Model(&Person{}).Where("id = ?", personID). |
| - Updates(map[string]any{"handle": nil, "updated_at": now}).Error |
| + err := s.guarded(ctx, func(db *gorm.DB) error { |
| + return db.Model(&Person{}).Where("id = ?", personID). |
| + Updates(map[string]any{"handle": nil, "updated_at": now}).Error |
| + }) |
| if err != nil { |
| return fmt.Errorf("calendar: clear handle: %w", err) |
| } |
| @@ -74,8 +76,10 @@ func (s *Store) SaveHandle(ctx context.Context, personID int64, handle string) e |
| } else if err != nil && !NotFound(err) { |
| return err |
| } |
| - err := s.g.WithContext(ctx).Model(&Person{}).Where("id = ?", personID). |
| - Updates(map[string]any{"handle": h, "updated_at": now}).Error |
| + err := s.guarded(ctx, func(db *gorm.DB) error { |
| + return db.Model(&Person{}).Where("id = ?", personID). |
| + Updates(map[string]any{"handle": h, "updated_at": now}).Error |
| + }) |
| if err != nil { |
| if isUniqueViolation(err) { |
| return ErrHandleTaken |
diff --git a/internal/calendar/store_booking_page.go b/internal/calendar/store_booking_page.go| index 93f0df2..f62c69a 100644 |
| --- a/internal/calendar/store_booking_page.go |
| +++ b/internal/calendar/store_booking_page.go |
| @@ -128,21 +128,7 @@ func (s *Store) CreateBookingPage(ctx context.Context, personID int64, in Bookin |
| AvailabilitySealed: avail, CreatedAt: now, UpdatedAt: now, |
| } |
| err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - for attempt := 0; ; attempt++ { |
| - code, err := newPageCode() |
| - if err != nil { |
| - return err |
| - } |
| - page.Code = code |
| - err = tx.Create(&page).Error |
| - if err == nil { |
| - break |
| - } |
| - if !isUniqueViolation(err) || attempt >= 1 { |
| - return fmt.Errorf("calendar: create booking page: %w", err) |
| - } |
| - } |
| - return insertWindows(tx, page.ID, ws) |
| + return s.guard(ctx, func() error { return createPageOn(tx, &page, ws) }) |
| }) |
| if err != nil { |
| return BookingPage{}, err |
| @@ -150,6 +136,25 @@ func (s *Store) CreateBookingPage(ctx context.Context, personID int64, in Bookin |
| return page, nil |
| } |
| +// createPageOn is CreateBookingPage's write, on its transaction. |
| +func createPageOn(tx *gorm.DB, page *BookingPage, ws []Window) error { |
| + for attempt := 0; ; attempt++ { |
| + code, err := newPageCode() |
| + if err != nil { |
| + return err |
| + } |
| + page.Code = code |
| + err = tx.Create(page).Error |
| + if err == nil { |
| + break |
| + } |
| + if !isUniqueViolation(err) || attempt >= 1 { |
| + return fmt.Errorf("calendar: create booking page: %w", err) |
| + } |
| + } |
| + return insertWindows(tx, page.ID, ws) |
| +} |
| + |
| // insertWindows writes a page's windows. The caller has already |
| // deleted the old ones inside the same transaction, if there were any. |
| func insertWindows(tx *gorm.DB, pageID int64, ws []Window) error { |
| @@ -181,30 +186,35 @@ func (s *Store) UpdateBookingPage(ctx context.Context, personID, pageID int64, i |
| return err |
| } |
| return s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - res := tx.Model(&BookingPage{}).Where("id = ? AND person_id = ?", pageID, personID). |
| - Updates(map[string]any{ |
| - "title_sealed": title, |
| - "description_sealed": desc, |
| - "availability_text_sealed": avail, |
| - "duration_min": in.DurationMin, |
| - "buffer_min": in.BufferMin, |
| - "notice_min": in.NoticeMin, |
| - "horizon_days": in.HorizonDays, |
| - "updated_at": time.Now().UTC(), |
| - }) |
| - if res.Error != nil { |
| - return fmt.Errorf("calendar: update booking page: %w", res.Error) |
| - } |
| - if res.RowsAffected == 0 { |
| - return ErrNotFound |
| - } |
| - if err := tx.Where("page_id = ?", pageID).Delete(&BookingWindow{}).Error; err != nil { |
| - return fmt.Errorf("calendar: clear booking windows: %w", err) |
| - } |
| - return insertWindows(tx, pageID, ws) |
| + return s.guard(ctx, func() error { return updatePageOn(tx, personID, pageID, in, title, desc, avail, ws) }) |
| }) |
| } |
| +// updatePageOn is UpdateBookingPage's write, on its transaction. |
| +func updatePageOn(tx *gorm.DB, personID, pageID int64, in BookingPageInput, title, desc, avail []byte, ws []Window) error { |
| + res := tx.Model(&BookingPage{}).Where("id = ? AND person_id = ?", pageID, personID). |
| + Updates(map[string]any{ |
| + "title_sealed": title, |
| + "description_sealed": desc, |
| + "availability_text_sealed": avail, |
| + "duration_min": in.DurationMin, |
| + "buffer_min": in.BufferMin, |
| + "notice_min": in.NoticeMin, |
| + "horizon_days": in.HorizonDays, |
| + "updated_at": time.Now().UTC(), |
| + }) |
| + if res.Error != nil { |
| + return fmt.Errorf("calendar: update booking page: %w", res.Error) |
| + } |
| + if res.RowsAffected == 0 { |
| + return ErrNotFound |
| + } |
| + if err := tx.Where("page_id = ?", pageID).Delete(&BookingWindow{}).Error; err != nil { |
| + return fmt.Errorf("calendar: clear booking windows: %w", err) |
| + } |
| + return insertWindows(tx, pageID, ws) |
| +} |
| + |
| // PublishBookingPage sets or clears published_at. Explicit, with its |
| // own button, because a published page is an oracle for when the host |
| // is free (spec §7.4). |
| @@ -214,14 +224,23 @@ func (s *Store) PublishBookingPage(ctx context.Context, personID, pageID int64, |
| if publish { |
| at = now.Unix() |
| } |
| - res := s.g.WithContext(ctx).Model(&BookingPage{}). |
| - Where("id = ? AND person_id = ?", pageID, personID). |
| - Updates(map[string]any{"published_at": at, "updated_at": now}) |
| - if res.Error != nil { |
| - return fmt.Errorf("calendar: publish booking page: %w", res.Error) |
| - } |
| - if res.RowsAffected == 0 { |
| - return ErrNotFound |
| + if publish { |
| + // Team mode: a Home-only host has no address for the booker's |
| + // invitation or the host's own mail (team_home_only.go). |
| + if err := s.refuseAddressless(ctx, personID); err != nil { |
| + return err |
| + } |
| } |
| - return nil |
| + return s.guarded(ctx, func(db *gorm.DB) error { |
| + res := db.Model(&BookingPage{}). |
| + Where("id = ? AND person_id = ?", pageID, personID). |
| + Updates(map[string]any{"published_at": at, "updated_at": now}) |
| + if res.Error != nil { |
| + return fmt.Errorf("calendar: publish booking page: %w", res.Error) |
| + } |
| + if res.RowsAffected == 0 { |
| + return ErrNotFound |
| + } |
| + return nil |
| + }) |
| } |
diff --git a/internal/calendar/store_calendar.go b/internal/calendar/store_calendar.go| index c9e381b..803eec8 100644 |
| --- a/internal/calendar/store_calendar.go |
| +++ b/internal/calendar/store_calendar.go |
| @@ -51,19 +51,27 @@ func (s *Store) EnsurePersonSetup(ctx context.Context, address string) (Person, |
| if err != nil { |
| return Person{}, err |
| } |
| + if err := s.setupPerson(ctx, p); err != nil { |
| + return Person{}, err |
| + } |
| + return p, nil |
| +} |
| + |
| +// setupPerson is the half of EnsurePersonSetup after the row exists: the |
| +// team calendar, the grant onto it, and a personal calendar. Idempotent. |
| +// In team mode a Home-only person, who has no address to ensure a row by, |
| +// gets the same (team_access.go). |
| +func (s *Store) setupPerson(ctx context.Context, p Person) error { |
| team, err := s.ensureTeamCalendar(ctx, p.ID) |
| if err != nil { |
| - return Person{}, err |
| + return err |
| } |
| // Editor, not owner: the team calendar belongs to the team, and |
| // nobody should be able to delete it out from under the others. |
| if err := s.ensureGrant(ctx, team.ID, p.ID, RoleEditor, p.ID); err != nil { |
| - return Person{}, err |
| + return err |
| } |
| - if err := s.ensurePersonalCalendar(ctx, p); err != nil { |
| - return Person{}, err |
| - } |
| - return p, nil |
| + return s.ensurePersonalCalendar(ctx, p) |
| } |
| func (s *Store) ensureTeamCalendar(ctx context.Context, creator int64) (Calendar, error) { |
| @@ -147,7 +155,7 @@ func (s *Store) Calendars(ctx context.Context, personID int64) ([]CalendarView, |
| err := s.g.WithContext(ctx). |
| Model(&Calendar{}). |
| Select("calendars.*, grants.role as role"). |
| - Joins("JOIN grants ON grants.calendar_id = calendars.id AND grants.person_id = ?", personID). |
| + Joins(grantJoin("calendars.id", s.reaches(ctx)), personID). |
| Where("calendars.archived_at IS NULL"). |
| Order("calendars.id"). |
| Scan(&rows).Error |
| @@ -176,7 +184,7 @@ func (s *Store) Calendar(ctx context.Context, personID, calendarID int64) (Calen |
| err := s.g.WithContext(ctx). |
| Model(&Calendar{}). |
| Select("calendars.*, grants.role as role"). |
| - Joins("JOIN grants ON grants.calendar_id = calendars.id AND grants.person_id = ?", personID). |
| + Joins(grantJoin("calendars.id", s.reaches(ctx)), personID). |
| Where("calendars.id = ?", calendarID). |
| Limit(1). |
| Scan(&r).Error |
diff --git a/internal/calendar/store_drain.go b/internal/calendar/store_drain.go| index 4e09d47..e0e05d2 100644 |
| --- a/internal/calendar/store_drain.go |
| +++ b/internal/calendar/store_drain.go |
| @@ -22,7 +22,10 @@ type DueReminder struct { |
| // completion passes it back and is conditional on it. |
| ClaimID string |
| - EventID int64 |
| + EventID int64 |
| + // PersonID is whose reminder it is: team mode asks the roster about |
| + // them before anything is sent (team_jobs.go). |
| + PersonID int64 |
| Title string |
| Location string |
| Zone string |
| @@ -164,6 +167,7 @@ func (s *Store) ClaimDueReminder(ctx context.Context, now int64) (DueReminder, b |
| Queue: q, |
| ClaimID: claimID, |
| EventID: e.ID, |
| + PersonID: rem.PersonID, |
| Title: title, |
| Location: loc, |
| Zone: zone, |
| @@ -214,13 +218,7 @@ func (s *Store) CompleteReminder(ctx context.Context, due DueReminder, now int64 |
| // was busy and nothing was tried. retry_at, never due_at — due_at IS |
| // the meeting time minus the offset. |
| func (s *Store) DeferReminder(ctx context.Context, queueID int64, claimID string, now int64) (ok bool, err error) { |
| - res := s.g.WithContext(ctx).Model(&ReminderQueue{}). |
| - Where("id = ? AND claim_id = ?", queueID, claimID). |
| - Updates(map[string]any{"retry_at": now + int64(deferFor.Seconds()), "claimed_at": nil, "claim_id": nil}) |
| - if res.Error != nil { |
| - return false, fmt.Errorf("calendar: defer reminder: %w", res.Error) |
| - } |
| - return res.RowsAffected == 1, nil |
| + return s.deferReminderFor(ctx, queueID, claimID, now, deferFor) |
| } |
| // MaxReminderAttempts is when a reminder stops being retried. |
diff --git a/internal/calendar/store_event.go b/internal/calendar/store_event.go| index 9f583f7..099281d 100644 |
| --- a/internal/calendar/store_event.go |
| +++ b/internal/calendar/store_event.go |
| @@ -7,6 +7,7 @@ import ( |
| "encoding/hex" |
| "errors" |
| "fmt" |
| + "gorm.io/gorm" |
| "time" |
| "amadan.net/oficina/calendar/internal/calendar/seal" |
| @@ -92,7 +93,7 @@ func (s *Store) CreateEvent(ctx context.Context, personID int64, in EventInput) |
| if err != nil { |
| return Event{}, err |
| } |
| - if err := s.g.WithContext(ctx).Create(&e).Error; err != nil { |
| + if err := s.guarded(ctx, func(db *gorm.DB) error { return db.Create(&e).Error }); err != nil { |
| return Event{}, fmt.Errorf("calendar: create event: %w", err) |
| } |
| return e, nil |
diff --git a/internal/calendar/store_event_read.go b/internal/calendar/store_event_read.go| index 86c0848..75cc607 100644 |
| --- a/internal/calendar/store_event_read.go |
| +++ b/internal/calendar/store_event_read.go |
| @@ -24,7 +24,7 @@ func (s *Store) Event(ctx context.Context, personID, eventID int64) (EventView, |
| Model(&Event{}). |
| Select("events.*, grants.role as role, calendars.name_sealed as calendar_name, calendars.hue as calendar_hue"). |
| Joins("JOIN calendars ON calendars.id = events.calendar_id"). |
| - Joins("JOIN grants ON grants.calendar_id = events.calendar_id AND grants.person_id = ?", personID). |
| + Joins(grantJoin("events.calendar_id", s.reaches(ctx)), personID). |
| Where("events.id = ? AND events.deleted_at IS NULL", eventID). |
| Limit(1). |
| Scan(&r).Error |
diff --git a/internal/calendar/store_event_write.go b/internal/calendar/store_event_write.go| index b924fec..9b24cb9 100644 |
| --- a/internal/calendar/store_event_write.go |
| +++ b/internal/calendar/store_event_write.go |
| @@ -30,7 +30,7 @@ func (s *Store) UpdateEvent(ctx context.Context, personID, eventID int64, in Eve |
| // spec B18): the comparison against the stored row happens inside |
| // the transaction below, so a stale form cannot slip a time past it. |
| return s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - return s.updateEventOn(tx, existing.Event, in, time.Now().UTC()) |
| + return s.guard(ctx, func() error { return s.updateEventOn(tx, existing.Event, in, time.Now().UTC()) }) |
| }) |
| } |
| @@ -131,26 +131,31 @@ func (s *Store) DeleteEvent(ctx context.Context, personID, eventID int64) error |
| } |
| now := time.Now().UTC() |
| return s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - // A booked event's deletion is a cancellation the booker is |
| - // told about, and its CANCEL ICS must outrank the REQUEST, so |
| - // the soft-deleted row takes one more revision (booking spec |
| - // §5.5). |
| - updates := map[string]any{"deleted_at": now, "updated_at": now, "sequence": gorm.Expr("sequence + 1")} |
| - if _, booked, err := bookingFor(tx, eventID); err != nil { |
| + return s.guard(ctx, func() error { return deleteEventOn(tx, eventID, now) }) |
| + }) |
| +} |
| + |
| +// deleteEventOn is DeleteEvent's write, on its transaction. |
| +func deleteEventOn(tx *gorm.DB, eventID int64, now time.Time) error { |
| + // A booked event's deletion is a cancellation the booker is |
| + // told about, and its CANCEL ICS must outrank the REQUEST, so |
| + // the soft-deleted row takes one more revision (booking spec |
| + // §5.5). |
| + updates := map[string]any{"deleted_at": now, "updated_at": now, "sequence": gorm.Expr("sequence + 1")} |
| + if _, booked, err := bookingFor(tx, eventID); err != nil { |
| + return err |
| + } else if booked { |
| + if err := cancelBookingsForEvent(tx, eventID, now); err != nil { |
| return err |
| - } else if booked { |
| - if err := cancelBookingsForEvent(tx, eventID, now); err != nil { |
| - return err |
| - } |
| - } |
| - if err := tx.Model(&Event{}).Where("id = ?", eventID). |
| - Updates(updates).Error; err != nil { |
| - return fmt.Errorf("calendar: delete event: %w", err) |
| } |
| - if err := tx.Model(&Event{}).Where("series_id = ?", eventID). |
| - Update("deleted_at", now).Error; err != nil { |
| - return fmt.Errorf("calendar: delete overrides: %w", err) |
| - } |
| - return nil |
| - }) |
| + } |
| + if err := tx.Model(&Event{}).Where("id = ?", eventID). |
| + Updates(updates).Error; err != nil { |
| + return fmt.Errorf("calendar: delete event: %w", err) |
| + } |
| + if err := tx.Model(&Event{}).Where("series_id = ?", eventID). |
| + Update("deleted_at", now).Error; err != nil { |
| + return fmt.Errorf("calendar: delete overrides: %w", err) |
| + } |
| + return nil |
| } |
diff --git a/internal/calendar/store_feed.go b/internal/calendar/store_feed.go| index 0b14b84..5c3f5ee 100644 |
| --- a/internal/calendar/store_feed.go |
| +++ b/internal/calendar/store_feed.go |
| @@ -45,7 +45,7 @@ func (s *Store) MintFeed(ctx context.Context, personID, calendarID int64) (strin |
| TokenHash: HashFeedToken(token), |
| CreatedAt: time.Now().UTC(), |
| } |
| - if err := s.g.WithContext(ctx).Create(&f).Error; err != nil { |
| + if err := s.guarded(ctx, func(db *gorm.DB) error { return db.Create(&f).Error }); err != nil { |
| return "", fmt.Errorf("calendar: mint feed: %w", err) |
| } |
| return token, nil |
| @@ -110,16 +110,18 @@ func (s *Store) FeedsFor(ctx context.Context, personID, calendarID int64) ([]Fee |
| // matching a later feed that happened to reuse the row. |
| func (s *Store) RevokeFeed(ctx context.Context, personID, feedID int64) error { |
| now := time.Now().UTC() |
| - res := s.g.WithContext(ctx).Model(&Feed{}). |
| - Where("id = ? AND person_id = ?", feedID, personID). |
| - Update("revoked_at", now) |
| - if res.Error != nil { |
| - return fmt.Errorf("calendar: revoke feed: %w", res.Error) |
| - } |
| - if res.RowsAffected == 0 { |
| - return ErrNotFound |
| - } |
| - return nil |
| + return s.guarded(ctx, func(db *gorm.DB) error { |
| + res := db.Model(&Feed{}). |
| + Where("id = ? AND person_id = ?", feedID, personID). |
| + Update("revoked_at", now) |
| + if res.Error != nil { |
| + return fmt.Errorf("calendar: revoke feed: %w", res.Error) |
| + } |
| + if res.RowsAffected == 0 { |
| + return ErrNotFound |
| + } |
| + return nil |
| + }) |
| } |
| // EventsForFeed reads a calendar's events for export, opening the UID |
| @@ -184,14 +186,16 @@ func (s *Store) SaveSettings(ctx context.Context, personID int64, zone string, w |
| default: |
| weekStart = WeekStartMonday |
| } |
| - err := s.g.WithContext(ctx).Model(&Person{}).Where("id = ?", personID). |
| - Updates(map[string]any{ |
| - "zone": zone, |
| - "week_start": weekStart, |
| - "default_reminder_min": reminderMin, |
| - "default_all_day_min": allDayMin, |
| - "updated_at": time.Now().UTC(), |
| - }).Error |
| + err := s.guarded(ctx, func(db *gorm.DB) error { |
| + return db.Model(&Person{}).Where("id = ?", personID). |
| + Updates(map[string]any{ |
| + "zone": zone, |
| + "week_start": weekStart, |
| + "default_reminder_min": reminderMin, |
| + "default_all_day_min": allDayMin, |
| + "updated_at": time.Now().UTC(), |
| + }).Error |
| + }) |
| if err != nil { |
| return fmt.Errorf("calendar: save settings: %w", err) |
| } |
diff --git a/internal/calendar/store_feed_rows.go b/internal/calendar/store_feed_rows.go| index 24fe683..533ae83 100644 |
| --- a/internal/calendar/store_feed_rows.go |
| +++ b/internal/calendar/store_feed_rows.go |
| @@ -10,7 +10,9 @@ func (s *Store) feedEventRows(ctx context.Context, personID, calendarID, from, t |
| if _, err := s.Calendar(ctx, personID, calendarID); err != nil { |
| return nil, err |
| } |
| - rows, err := s.rangeRows(s.g.WithContext(ctx), personID, from, to) |
| + // Standing is read once, before the reads it decides (team_reach.go). |
| + rung := s.reaches(ctx) |
| + rows, err := s.rangeRows(s.g.WithContext(ctx), personID, from, to, rung) |
| if err != nil { |
| return nil, err |
| } |
| @@ -46,7 +48,7 @@ func (s *Store) feedEventRows(ctx context.Context, personID, calendarID, from, t |
| for id := range masters { |
| ids = append(ids, id) |
| } |
| - overrides, err := s.overridesFor(s.g.WithContext(ctx), personID, ids) |
| + overrides, err := s.overridesFor(s.g.WithContext(ctx), personID, ids, rung) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/calendar/store_override.go b/internal/calendar/store_override.go| index f7133f0..161a74b 100644 |
| --- a/internal/calendar/store_override.go |
| +++ b/internal/calendar/store_override.go |
| @@ -114,11 +114,13 @@ func (s *Store) UpdateOccurrence(ctx context.Context, personID, seriesID int64, |
| CreatedAt: now, |
| UpdatedAt: now, |
| } |
| - if err := s.g.WithContext(ctx).Create(&ov).Error; err != nil { |
| - return fmt.Errorf("calendar: create override: %w", err) |
| - } |
| - // The reminder for this occurrence now points at a different time. |
| - return s.rescheduleAllFor(ctx, seriesID) |
| + return s.guarded(ctx, func(db *gorm.DB) error { |
| + if err := db.Create(&ov).Error; err != nil { |
| + return fmt.Errorf("calendar: create override: %w", err) |
| + } |
| + // The reminder for this occurrence now points at a different time. |
| + return s.rescheduleAllForTx(db, seriesID) |
| + }) |
| } |
| // SplitSeries ends a series the day before originalLocal and starts a |
| @@ -159,44 +161,49 @@ func (s *Store) SplitSeries(ctx context.Context, personID, seriesID int64, origi |
| headRule := withUntil(master.RRule, until) |
| return s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - headUntil, _ := RuleUntilUTC(headRule, master.StartLocal, master.TZ, master.AllDay) |
| - head := splitWritableEvents(tx, personID, master.CalendarID). |
| - Where("id = ? AND deleted_at IS NULL AND sequence = ?", seriesID, master.Sequence). |
| - Select("rrule", "until_utc", "sequence", "updated_at"). |
| - Updates(map[string]any{ |
| - "rrule": headRule, |
| - "until_utc": headUntil, |
| - "sequence": gorm.Expr("sequence + 1"), |
| - "updated_at": time.Now().UTC(), |
| - }) |
| - if head.Error != nil { |
| - return fmt.Errorf("calendar: end the head series: %w", head.Error) |
| - } |
| - if head.RowsAffected != 1 { |
| - return ErrNotFound |
| - } |
| + return s.guard(ctx, func() error { return s.splitOn(tx, personID, seriesID, master, headRule, cut, in) }) |
| + }) |
| +} |
| - // The tail is a new series with the master's rule, starting at |
| - // the edited time. A new UID: to any importer this is a |
| - // different series from here on, and pretending otherwise |
| - // produces two events claiming one identity. |
| - tail := in |
| - tail.CalendarID = master.CalendarID |
| - tail.RRule = master.RRule |
| - tail.Exdates = "" |
| - ev, err := s.buildEvent(personID, tail) |
| - if err != nil { |
| - return err |
| - } |
| - if err := tx.Create(&ev).Error; err != nil { |
| - return fmt.Errorf("calendar: create the tail series: %w", err) |
| - } |
| +// splitOn is SplitSeries' write, on its transaction. |
| +func (s *Store) splitOn(tx *gorm.DB, personID, seriesID int64, master EventView, headRule string, cut time.Time, in EventInput) error { |
| + headUntil, _ := RuleUntilUTC(headRule, master.StartLocal, master.TZ, master.AllDay) |
| + head := splitWritableEvents(tx, personID, master.CalendarID). |
| + Where("id = ? AND deleted_at IS NULL AND sequence = ?", seriesID, master.Sequence). |
| + Select("rrule", "until_utc", "sequence", "updated_at"). |
| + Updates(map[string]any{ |
| + "rrule": headRule, |
| + "until_utc": headUntil, |
| + "sequence": gorm.Expr("sequence + 1"), |
| + "updated_at": time.Now().UTC(), |
| + }) |
| + if head.Error != nil { |
| + return fmt.Errorf("calendar: end the head series: %w", head.Error) |
| + } |
| + if head.RowsAffected != 1 { |
| + return ErrNotFound |
| + } |
| - if err := moveSplitOverrides(tx, personID, master.Event, ev, cut); err != nil { |
| - return err |
| - } |
| - return s.rescheduleAllForTx(tx, seriesID) |
| - }) |
| + // The tail is a new series with the master's rule, starting at |
| + // the edited time. A new UID: to any importer this is a |
| + // different series from here on, and pretending otherwise |
| + // produces two events claiming one identity. |
| + tail := in |
| + tail.CalendarID = master.CalendarID |
| + tail.RRule = master.RRule |
| + tail.Exdates = "" |
| + ev, err := s.buildEvent(personID, tail) |
| + if err != nil { |
| + return err |
| + } |
| + if err := tx.Create(&ev).Error; err != nil { |
| + return fmt.Errorf("calendar: create the tail series: %w", err) |
| + } |
| + |
| + if err := moveSplitOverrides(tx, personID, master.Event, ev, cut); err != nil { |
| + return err |
| + } |
| + return s.rescheduleAllForTx(tx, seriesID) |
| } |
| // findOverride looks one up by its ORIGINAL occurrence. |
diff --git a/internal/calendar/store_range.go b/internal/calendar/store_range.go| index e3d4665..df4f753 100644 |
| --- a/internal/calendar/store_range.go |
| +++ b/internal/calendar/store_range.go |
| @@ -64,7 +64,10 @@ func (s *Store) EventsInRangeStrict(ctx context.Context, personID, from, to int6 |
| // eventsInRange runs on any *gorm.DB — the store's own, or a caller's |
| // transaction — so a hold can re-read busy time behind the write lock. |
| func (s *Store) eventsInRange(db *gorm.DB, personID, from, to int64, strict bool) ([]EventView, error) { |
| - rows, err := s.rangeRows(db, personID, from, to) |
| + // Standing is read once, before either pass, so both passes join |
| + // through the same reach (team_reach.go). |
| + rung := s.reaches(db.Statement.Context) |
| + rows, err := s.rangeRows(db, personID, from, to, rung) |
| if err != nil { |
| return nil, err |
| } |
| @@ -95,7 +98,7 @@ func (s *Store) eventsInRange(db *gorm.DB, personID, from, to int64, strict bool |
| } |
| } |
| } |
| - overrides, err := s.overridesFor(db, personID, masterIDs) |
| + overrides, err := s.overridesFor(db, personID, masterIDs, rung) |
| if err != nil { |
| return nil, err |
| } |
| @@ -192,13 +195,13 @@ func (s *Store) eventsInRange(db *gorm.DB, personID, from, to int64, strict bool |
| // rangeRows reads the candidate events: anything overlapping the window, |
| // plus every series master that could still be producing in it. |
| -func (s *Store) rangeRows(db *gorm.DB, personID, from, to int64) ([]eventRow, error) { |
| +func (s *Store) rangeRows(db *gorm.DB, personID, from, to int64, rung bool) ([]eventRow, error) { |
| var rows []eventRow |
| err := db. |
| Model(&Event{}). |
| Select("events.*, grants.role as role, calendars.name_sealed as calendar_name, calendars.hue as calendar_hue"). |
| Joins("JOIN calendars ON calendars.id = events.calendar_id AND calendars.archived_at IS NULL"). |
| - Joins("JOIN grants ON grants.calendar_id = events.calendar_id AND grants.person_id = ?", personID). |
| + Joins(grantJoin("events.calendar_id", rung), personID). |
| Where("events.deleted_at IS NULL"). |
| Where(` |
| -- a single, or an override, overlapping the window |
| @@ -231,7 +234,7 @@ func (s *Store) rangeRows(db *gorm.DB, personID, from, to int64) ([]eventRow, er |
| // overridesFor reads every override of the given series, keyed by |
| // series and ORIGINAL occurrence. |
| -func (s *Store) overridesFor(db *gorm.DB, personID int64, seriesIDs []int64) (map[string]eventRow, error) { |
| +func (s *Store) overridesFor(db *gorm.DB, personID int64, seriesIDs []int64, rung bool) (map[string]eventRow, error) { |
| out := map[string]eventRow{} |
| if len(seriesIDs) == 0 { |
| return out, nil |
| @@ -241,7 +244,7 @@ func (s *Store) overridesFor(db *gorm.DB, personID int64, seriesIDs []int64) (ma |
| Model(&Event{}). |
| Select("events.*, grants.role as role, calendars.name_sealed as calendar_name, calendars.hue as calendar_hue"). |
| Joins("JOIN calendars ON calendars.id = events.calendar_id"). |
| - Joins("JOIN grants ON grants.calendar_id = events.calendar_id AND grants.person_id = ?", personID). |
| + Joins(grantJoin("events.calendar_id", rung), personID). |
| Where("events.series_id IN ?", seriesIDs). |
| Scan(&rows).Error |
| if err != nil { |
diff --git a/internal/calendar/store_reminder.go b/internal/calendar/store_reminder.go| index 6489979..06e15e9 100644 |
| --- a/internal/calendar/store_reminder.go |
| +++ b/internal/calendar/store_reminder.go |
| @@ -7,6 +7,8 @@ import ( |
| "time" |
| "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/calendar/internal/calendar/teamstate" |
| ) |
| // EnsureDefaultReminder gives a newly created event the person's own |
| @@ -25,6 +27,11 @@ func (s *Store) EnsureDefaultReminder(ctx context.Context, p Person, e Event) er |
| if offset == 0 { |
| return nil |
| } |
| + if s.team && teamstate.Addressless(p.Address) { |
| + // Team mode: a Home-only person has no address to remind, so |
| + // gets no default reminder (team_home_only.go). |
| + return nil |
| + } |
| r := Reminder{ |
| EventID: e.ID, |
| PersonID: p.ID, |
| @@ -32,10 +39,12 @@ func (s *Store) EnsureDefaultReminder(ctx context.Context, p Person, e Event) er |
| Channel: "email", |
| CreatedAt: time.Now().UTC(), |
| } |
| - if err := s.g.WithContext(ctx).Create(&r).Error; err != nil { |
| - return fmt.Errorf("calendar: create reminder: %w", err) |
| - } |
| - return s.RescheduleReminder(ctx, r.ID) |
| + return s.guarded(ctx, func(db *gorm.DB) error { |
| + if err := db.Create(&r).Error; err != nil { |
| + return fmt.Errorf("calendar: create reminder: %w", err) |
| + } |
| + return s.rescheduleAfterTx(db, r.ID, 0) |
| + }) |
| } |
| // RemindersFor lists a person's own reminders on an event. Only their |
| @@ -58,6 +67,10 @@ func (s *Store) AddReminder(ctx context.Context, personID, eventID, offsetMin in |
| if _, err := s.Event(ctx, personID, eventID); err != nil { |
| return err |
| } |
| + // Team mode: a Home-only person has no address to remind. |
| + if err := s.refuseAddressless(ctx, personID); err != nil { |
| + return err |
| + } |
| r := Reminder{ |
| EventID: eventID, |
| PersonID: personID, |
| @@ -65,29 +78,36 @@ func (s *Store) AddReminder(ctx context.Context, personID, eventID, offsetMin in |
| Channel: "email", |
| CreatedAt: time.Now().UTC(), |
| } |
| - if err := s.g.WithContext(ctx).Create(&r).Error; err != nil { |
| - return fmt.Errorf("calendar: add reminder: %w", err) |
| - } |
| - return s.RescheduleReminder(ctx, r.ID) |
| + return s.guarded(ctx, func(db *gorm.DB) error { |
| + if err := db.Create(&r).Error; err != nil { |
| + return fmt.Errorf("calendar: add reminder: %w", err) |
| + } |
| + return s.rescheduleAfterTx(db, r.ID, 0) |
| + }) |
| } |
| // RemoveReminder deletes one of the person's own reminders, and the |
| // queued row with it. |
| func (s *Store) RemoveReminder(ctx context.Context, personID, reminderID int64) error { |
| return s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - res := tx.Where("id = ? AND person_id = ?", reminderID, personID).Delete(&Reminder{}) |
| - if res.Error != nil { |
| - return fmt.Errorf("calendar: remove reminder: %w", res.Error) |
| - } |
| - if res.RowsAffected == 0 { |
| - // Somebody else's reminder, or none. Not found, never |
| - // forbidden. |
| - return ErrNotFound |
| - } |
| - return tx.Where("reminder_id = ?", reminderID).Delete(&ReminderQueue{}).Error |
| + return s.guard(ctx, func() error { return removeReminderOn(tx, personID, reminderID) }) |
| }) |
| } |
| +// removeReminderOn is RemoveReminder's write, on its transaction. |
| +func removeReminderOn(tx *gorm.DB, personID, reminderID int64) error { |
| + res := tx.Where("id = ? AND person_id = ?", reminderID, personID).Delete(&Reminder{}) |
| + if res.Error != nil { |
| + return fmt.Errorf("calendar: remove reminder: %w", res.Error) |
| + } |
| + if res.RowsAffected == 0 { |
| + // Somebody else's reminder, or none. Not found, never |
| + // forbidden. |
| + return ErrNotFound |
| + } |
| + return tx.Where("reminder_id = ?", reminderID).Delete(&ReminderQueue{}).Error |
| +} |
| + |
| // RescheduleReminder recomputes when a rule next fires and writes the |
| // single pending queue row for it. |
| // |
| @@ -192,11 +212,13 @@ func (s *Store) ExcludeOccurrence(ctx context.Context, personID, eventID int64, |
| next += "," |
| } |
| next += local |
| - if err := s.g.WithContext(ctx).Model(&Event{}).Where("id = ?", eventID). |
| - Updates(map[string]any{"exdates": next, "updated_at": time.Now().UTC()}).Error; err != nil { |
| - return fmt.Errorf("calendar: exclude occurrence: %w", err) |
| - } |
| - return s.rescheduleAllFor(ctx, eventID) |
| + return s.guarded(ctx, func(db *gorm.DB) error { |
| + if err := db.Model(&Event{}).Where("id = ?", eventID). |
| + Updates(map[string]any{"exdates": next, "updated_at": time.Now().UTC()}).Error; err != nil { |
| + return fmt.Errorf("calendar: exclude occurrence: %w", err) |
| + } |
| + return s.rescheduleAllForTx(db, eventID) |
| + }) |
| } |
| // rescheduleAllFor recomputes every reminder on an event, after the |
diff --git a/internal/calendar/team_access.go b/internal/calendar/team_access.go| new file mode 100644 |
| index 0000000..c8448bc |
| --- /dev/null |
| +++ b/internal/calendar/team_access.go |
| @@ -0,0 +1,244 @@ |
| +package calendar |
| + |
| +// Team mode's per-request standing. With a.team nil nothing here runs: |
| +// requirePerson, the route gates and every store read are what they have |
| +// always been. |
| +// |
| +// Standing itself is home/teammode's Access. Identity is resolved from the |
| +// actual session (a local address the allowlist admits, an account link, |
| +// or a Home-only person); the roster is asked about the Home subject, if |
| +// there is one; and the answer is one of three: |
| +// |
| +// - Member: the team rung, which in Calendar is every grant a person |
| +// holds. Calendar has no shares: every grant is made by |
| +// EnsurePersonSetup for the person themselves (editor on the team |
| +// calendar, owner of their own), so every grant is the team rung and |
| +// counts only while the roster says Member. The roster's role says |
| +// owner or member, and only the roster's. |
| +// - NotMember: nothing. With no shares a guest reaches nothing, so they |
| +// are signed out and told so (offboard), as Memoria does. The one |
| +// exception is a local account with no Oficina link, which has no |
| +// standing until it links and is sent to /account/home to do that. |
| +// - Unknown: the roster could not be read within its lease. Lists are |
| +// partial with a notice (Paul, 2026-10-28) — and, with no shares, |
| +// empty — and everything else is a retryable 503 rather than a 404 |
| +// that would claim the event is gone. |
| +// |
| +// A Member decision carries a lease. Access.State checks it every time it |
| +// is asked; the store's reads ask it once before they query (team_reach.go) |
| +// and a write checks it again inside its own transaction, before and |
| +// after (team_guard.go); a list asks it again after it is built. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + rauth "amadan.net/rastrillo/rastrillo/auth" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/calendar/internal/calendar/teamstate" |
| +) |
| + |
| +// teamPerson is who one request's session speaks for in team mode, and |
| +// their standing. Never stored beyond the request. |
| +type teamPerson struct { |
| + person Person |
| + // subject is the Home subject the roster knows them by, "" for a |
| + // local account with no Oficina link (no standing). |
| + subject string |
| + // method is the session's sign-in method. |
| + method string |
| + access *teammode.Access |
| +} |
| + |
| +// unlinkedLocal reports whether p is a local account with no Oficina |
| +// link: identity, but nothing to ask the roster about. |
| +func (p *teamPerson) unlinkedLocal() bool { |
| + return p.subject == "" && (p.method == "magiclink" || p.method == "keymail") |
| +} |
| + |
| +var errNoIdentity = errors.New("calendar: no team identity") |
| + |
| +type teamPersonKey struct{} |
| + |
| +// withTeamPerson carries p, and its Access for the store's reads and |
| +// guard, on ctx. |
| +func withTeamPerson(ctx context.Context, p *teamPerson) context.Context { |
| + return context.WithValue(teammode.WithAccess(ctx, p.access), teamPersonKey{}, p) |
| +} |
| + |
| +func teamPersonFrom(ctx context.Context) (*teamPerson, bool) { |
| + p, ok := ctx.Value(teamPersonKey{}).(*teamPerson) |
| + return p, ok && p != nil |
| +} |
| + |
| +// teamIdentify resolves a session to the person it speaks for. A Home |
| +// subject resolves through its link or its Home-only row (connect's |
| +// Resolve, with the HomeOnly hook), and only reads; a local session |
| +// through the allowlist, which in team mode admits the local door and |
| +// nothing more, and its link, with its row and calendars made on first |
| +// sight exactly as requirePerson always has (identity, never standing). |
| +// errTeamUnavailable |
| +// is storage that cannot be read now; errNoIdentity a session that speaks |
| +// for nobody here. |
| +func (a *App) teamIdentify(ctx context.Context, s sessions.Session) (Person, string, error) { |
| + switch s.Method { |
| + case connect.HomeMethod: |
| + if a.home == nil { |
| + return Person{}, "", errNoIdentity |
| + } |
| + ref, err := a.home.bridge.Resolve(ctx, s.Subject) |
| + if errors.Is(err, linkstore.ErrStorage) { |
| + return Person{}, "", errTeamUnavailable |
| + } |
| + if err != nil { |
| + return Person{}, "", errNoIdentity |
| + } |
| + var p Person |
| + if err := a.db.G.WithContext(ctx).First(&p, ref.ID).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return Person{}, "", errNoIdentity |
| + } |
| + return Person{}, "", errTeamUnavailable |
| + } |
| + switch { |
| + case ref.Label == "": |
| + // Home-only: connect's HomeOnly hook found them (connect holds |
| + // it to an empty label, and the table's triggers to a |
| + // placeholder address). |
| + p.homeOnly = s.Subject |
| + case p.Address != ref.Label: |
| + return Person{}, "", errNoIdentity |
| + } |
| + return p, s.Subject, nil |
| + case "magiclink", "keymail": |
| + address := normalizeAddress(s.Subject) |
| + if a.home == nil || address == "" || !a.home.admitted.allows(address) { |
| + return Person{}, "", errNoIdentity |
| + } |
| + p, err := a.store.EnsurePersonSetup(ctx, address) |
| + if err != nil { |
| + return Person{}, "", errTeamUnavailable |
| + } |
| + subject, err := a.homeSubjectOf(ctx, p.ID) |
| + if err != nil { |
| + return Person{}, "", err |
| + } |
| + return p, subject, nil |
| + } |
| + return Person{}, "", errNoIdentity |
| +} |
| + |
| +// homeSubjectOf is the Home subject the roster knows a person by: a |
| +// Home-only row or an account link, "" for neither. |
| +func (a *App) homeSubjectOf(ctx context.Context, id int64) (string, error) { |
| + subject, err := teamstate.HomeSubject(ctx, a.team.db, a.team.issuer(), id) |
| + switch { |
| + case err == nil: |
| + return subject, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + return "", nil |
| + } |
| + return "", errTeamUnavailable |
| +} |
| + |
| +// teamRequirePerson is requirePerson in team mode: who the session is, |
| +// and the roster's answer, asked once and carried on the request. |
| +// |
| +// A definite NotMember is signed out and told so (offboard), existing |
| +// sessions included: that is removal within the lease. An unlinked local |
| +// account is let through to the routes that need only a person — and the |
| +// content routes send it to /account/home (standing). A session that |
| +// speaks for nobody is the 404 it has always been. Unknown ends nothing. |
| +func (a *App) teamRequirePerson(w http.ResponseWriter, r *http.Request, next http.Handler) { |
| + s, ok := sessions.Current(r) |
| + if !ok { |
| + a.h.errorPage(w, r, http.StatusNotFound, "") |
| + return |
| + } |
| + p, subject, err := a.teamIdentify(r.Context(), s) |
| + switch { |
| + case errors.Is(err, errTeamUnavailable): |
| + a.h.teamUnavailable(w, r) |
| + return |
| + case err != nil: |
| + a.h.errorPage(w, r, http.StatusNotFound, "") |
| + return |
| + } |
| + if p.homeOnly != "" { |
| + // A Home-only person's calendars are made on their first page, |
| + // as a local person's are (identity, never standing). |
| + if err := a.store.setupPerson(r.Context(), p); err != nil { |
| + a.h.teamUnavailable(w, r) |
| + return |
| + } |
| + } |
| + tp := &teamPerson{person: p, subject: subject, method: s.Method, access: a.team.Access(r.Context(), subject)} |
| + if tp.access.State() == roster.NotMember && !tp.unlinkedLocal() { |
| + a.offboard(w, r) |
| + return |
| + } |
| + ctx := context.WithValue(withTeamPerson(r.Context(), tp), personCtxKey{}, p) |
| + next.ServeHTTP(w, r.WithContext(ctx)) |
| +} |
| + |
| +// offboard ends a session the roster says is off the team and sends it to |
| +// the sign-in door, which says so (renderSignin's "removed"). A 303, so a |
| +// form POST lands on a page too. |
| +func (a *App) offboard(w http.ResponseWriter, r *http.Request) { |
| + a.home.sessions.SignOut(w, r) |
| + w.Header().Set("Cache-Control", "no-store") |
| + http.Redirect(w, r, "/signin?err=removed", http.StatusSeeOther) |
| +} |
| + |
| +// teamViewer is the account menu's identity on a page requirePerson has |
| +// not run for (a public page, an error raised before it). A Home session |
| +// is resolved read-only, a Home-only person shown by their label; a local |
| +// session is viewer's, as before. |
| +func (a *App) teamViewer(r *http.Request) (rauth.Identity, bool) { |
| + s, ok := sessions.Current(r) |
| + if !ok || s.Method != connect.HomeMethod { |
| + return viewer(r) |
| + } |
| + p, _, err := a.teamIdentify(r.Context(), s) |
| + if err != nil { |
| + return rauth.Identity{}, false |
| + } |
| + return rauth.Identity{Address: p.shownAddress()}, true |
| +} |
| + |
| +// teamSignin is homeSignin in team mode: GET /signin asks the question |
| +// requirePerson asks before connect's Signin may shortcut a signed-in |
| +// person to where they were headed. A session that speaks for nobody here |
| +// ends and /signin is asked again without it, as before; one the roster |
| +// says is off the team is offboarded (told so, not restarted, which would |
| +// only sign them straight back in through Oficina). Storage that cannot |
| +// be read is a 503, never a sign-out. Unknown ends nothing. |
| +func (a *App) teamSignin(w http.ResponseWriter, r *http.Request) { |
| + s, ok := a.home.sessions.From(r) |
| + if ok && (s.Method == connect.HomeMethod || s.Method == "magiclink" || s.Method == "keymail") { |
| + _, subject, err := a.teamIdentify(r.Context(), s) |
| + switch { |
| + case errors.Is(err, errTeamUnavailable): |
| + a.h.teamUnavailable(w, r) |
| + return |
| + case err != nil: |
| + a.home.sessions.SignOut(w, r) |
| + w.Header().Set("Cache-Control", "no-store") |
| + http.Redirect(w, r, r.URL.RequestURI(), http.StatusSeeOther) |
| + return |
| + } |
| + local := subject == "" && s.Method != connect.HomeMethod |
| + if !local && a.team.Access(r.Context(), subject).State() == roster.NotMember { |
| + a.offboard(w, r) |
| + return |
| + } |
| + } |
| + a.home.routes.Signin(w, r) |
| +} |
diff --git a/internal/calendar/team_access_test.go b/internal/calendar/team_access_test.go| new file mode 100644 |
| index 0000000..c74b68b |
| --- /dev/null |
| +++ b/internal/calendar/team_access_test.go |
| @@ -0,0 +1,257 @@ |
| +package calendar |
| + |
| +import ( |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/roster" |
| + |
| + "amadan.net/oficina/calendar/internal/calendar/teamstate" |
| +) |
| + |
| +func TestTeamHomeOnlyMemberSignsInToAnAddresslessPerson(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('a') |
| + p := f.member(subject, "member") |
| + if !teamstate.Addressless(p.Address) || !strings.HasPrefix(p.Address, "home-only:") || strings.Contains(p.Address, "@") { |
| + t.Fatalf("a Home-only person holds address %q", p.Address) |
| + } |
| + team, personal := f.calendarsOf(p) |
| + if team == 0 || personal == 0 { |
| + t.Fatal("no calendars") |
| + } |
| + f.event(p, subject, team, "Team standup", "2026-11-02T09:00", "2026-11-02T09:15") |
| + w := f.get("/day/2026-11-02") |
| + body := w.Body.String() |
| + if w.Code != http.StatusOK || !strings.Contains(body, "Team standup") { |
| + t.Fatalf("day = %d, want the team's event", w.Code) |
| + } |
| + if strings.Contains(body, "home-only:") || strings.Contains(body, "data-partial") { |
| + t.Fatal("the day page showed the placeholder, or a partial notice to a member") |
| + } |
| + if !strings.Contains(body, `aria-label="Account: Oficina account …`+subject[len(subject)-4:]+`"`) { |
| + t.Fatal("the account menu does not name a Home-only member by their label") |
| + } |
| + // A page outside the session group names them the same way, and |
| + // never by the placeholder. |
| + if open := f.get("/help/open-source").Body.String(); !strings.Contains(open, "Oficina account …"+subject[len(subject)-4:]) || strings.Contains(open, "home-only:") { |
| + t.Fatal("a public page does not name a Home-only member by their label") |
| + } |
| + // Signing in again finds the same person and allocates nothing. |
| + var before int64 |
| + f.app.db.G.Model(&Person{}).Count(&before) |
| + if w := f.signInHome(subject); w.Code != http.StatusSeeOther { |
| + t.Fatalf("second sign-in = %d", w.Code) |
| + } |
| + var after int64 |
| + f.app.db.G.Model(&Person{}).Count(&after) |
| + if f.personFor(subject).ID != p.ID || before != after { |
| + t.Fatal("a second sign-in allocated a person") |
| + } |
| +} |
| + |
| +func TestTeamOnlyACurrentMemberIsAllocated(t *testing.T) { |
| + f := newTeamFixture(t) |
| + people := func() int64 { |
| + var n int64 |
| + f.app.db.G.Model(&Person{}).Count(&n) |
| + return n |
| + } |
| + // A stranger: connect's unknown, nothing made. |
| + if w := f.signInHome(teamSubject('s')); w.Code != http.StatusForbidden { |
| + t.Fatalf("stranger = %d, want 403", w.Code) |
| + } |
| + if people() != 0 || f.cookies[f.app.home.sessions.CookieName()] != nil { |
| + t.Fatal("a stranger got a person or a session") |
| + } |
| + // Unknown: 503, nothing made. |
| + f.dir.Set(teamSubject('u'), "member") |
| + f.expired() |
| + if w := f.signInHome(teamSubject('u')); w.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("unknown = %d, want 503", w.Code) |
| + } |
| + if people() != 0 { |
| + t.Fatal("Unknown allocated a person") |
| + } |
| + // Over somebody else's live session: refused, nothing made, the |
| + // session kept. |
| + f.refreshed() |
| + f.member(teamSubject('m'), "member") |
| + kept := f.cookies[f.app.home.sessions.CookieName()] |
| + f.dir.Set(teamSubject('n'), "member") |
| + f.refreshed() |
| + // Over a Home session handoff's own store refuses a second subject |
| + // (400, CurrentSubject) before connect is asked; over a local one it is |
| + // connect's "unknown" (403, below). Either way nothing is made. |
| + if w := f.exchange(t, handoff.StartPath, teamSubject('n')); w.Code != http.StatusBadRequest { |
| + t.Fatalf("unknown arrival over a live Home session = %d, want 400", w.Code) |
| + } |
| + if people() != 1 { |
| + t.Fatal("an arrival over a live session allocated a person") |
| + } |
| + if c := f.cookies[f.app.home.sessions.CookieName()]; c == nil || c.Value != kept.Value { |
| + t.Fatal("the live session did not survive") |
| + } |
| + f.localSession("alice@example.test") |
| + kept = f.cookies[f.app.home.sessions.CookieName()] |
| + if w := f.exchange(t, handoff.StartPath, teamSubject('n')); w.Code != http.StatusForbidden { |
| + t.Fatalf("unknown arrival over a local session = %d, want 403", w.Code) |
| + } |
| + if c := f.cookies[f.app.home.sessions.CookieName()]; people() != 1 || c == nil || c.Value != kept.Value { |
| + t.Fatal("an arrival over a local session allocated a person or ended the session") |
| + } |
| + // A known Home-only member arriving over another's session: 403, and |
| + // that session survives too. |
| + f.member(teamSubject('k'), "member") |
| + f.localSession("alice@example.test") |
| + kept = f.cookies[f.app.home.sessions.CookieName()] |
| + if w := f.exchange(t, handoff.StartPath, teamSubject('k')); w.Code != http.StatusForbidden { |
| + t.Fatalf("known arrival over another session = %d, want 403", w.Code) |
| + } |
| + if c := f.cookies[f.app.home.sessions.CookieName()]; c == nil || c.Value != kept.Value { |
| + t.Fatal("the other session did not survive") |
| + } |
| +} |
| + |
| +func TestTeamRemovalSignsOutAnExistingSession(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('r') |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + f.event(p, subject, team, "Board meeting", "2026-11-02T10:00", "2026-11-02T11:00") |
| + if w := f.get("/day/2026-11-02"); !strings.Contains(w.Body.String(), "Board meeting") { |
| + t.Fatal("member cannot see the team's event") |
| + } |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| + w := f.get("/day/2026-11-02") |
| + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("removed member's page = %d %q, want 303 to the removed door", w.Code, w.Header().Get("Location")) |
| + } |
| + if strings.Contains(w.Body.String(), "Board meeting") { |
| + t.Fatal("the removed member saw the event") |
| + } |
| + if f.cookies[f.app.home.sessions.CookieName()] != nil { |
| + t.Fatal("the removed member kept their session") |
| + } |
| + door := f.get("/signin?err=removed") |
| + if door.Code != http.StatusOK || !strings.Contains(door.Body.String(), "no longer on this team") { |
| + t.Fatalf("removed door = %d, want the removed sentence", door.Code) |
| + } |
| + // Signing in again finds them, allocates nothing, and offboards them |
| + // on their first page. |
| + if w := f.signInHome(subject); w.Code != http.StatusSeeOther { |
| + t.Fatalf("re-sign-in = %d", w.Code) |
| + } |
| + if w := f.get("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("removed member after re-sign-in = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + // A POST is offboarded too, and writes nothing. |
| + f.signInHome(subject) |
| + var before int64 |
| + f.app.db.G.Model(&Event{}).Count(&before) |
| + w = f.post("/events", "calendar_id=1&title=Late&start_local=2026-11-03T09:00&end_local=2026-11-03T10:00&tz=UTC&kind=meeting") |
| + var after int64 |
| + f.app.db.G.Model(&Event{}).Count(&after) |
| + if w.Code != http.StatusSeeOther || before != after { |
| + t.Fatalf("removed member's POST = %d, events %d→%d", w.Code, before, after) |
| + } |
| + // /signin with that session offboards rather than signing them back in. |
| + f.signInHome(subject) |
| + if w := f.get("/signin"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("/signin for a removed member = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + // Re-added: they are back. |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + f.signInHome(subject) |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Board meeting") { |
| + t.Fatalf("re-added member = %d", w.Code) |
| + } |
| +} |
| + |
| +func TestTeamStandingEndsAtTheLeaseUnderAFailingRefresh(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('l') |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + e := f.event(p, subject, team, "Quarterly review", "2026-11-02T10:00", "2026-11-02T11:00") |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Second) |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Quarterly review") || strings.Contains(w.Body.String(), "data-partial") { |
| + t.Fatalf("59 s = %d, want the whole day", w.Code) |
| + } |
| + if w := f.get("/events/" + itoa(e.ID)); w.Code != http.StatusOK { |
| + t.Fatalf("59 s event = %d", w.Code) |
| + } |
| + f.clock.Step(2 * time.Second) |
| + w := f.get("/day/2026-11-02") |
| + if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "Quarterly review") || !strings.Contains(w.Body.String(), "data-partial") { |
| + t.Fatalf("61 s day = %d, want partial and without the event", w.Code) |
| + } |
| + retryable(t, "61 s event", f.get("/events/"+itoa(e.ID))) |
| + retryable(t, "61 s missing event", f.get("/events/999999")) |
| + // Still signed in: Unknown ends nothing. |
| + if f.cookies[f.app.home.sessions.CookieName()] == nil { |
| + t.Fatal("Unknown signed the member out") |
| + } |
| + // /signin under Unknown is the ordinary shortcut, never an offboard. |
| + if w := f.get("/signin"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/" || f.cookies[f.app.home.sessions.CookieName()] == nil { |
| + t.Fatalf("/signin under Unknown = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| +} |
| + |
| +func TestTeamEmptyPartialListSaysPartialNotEmpty(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('e'), "member") |
| + f.expired() |
| + for path, empty := range map[string]string{ |
| + "/day/2026-11-02": "Nothing on this day", |
| + "/agenda": "Nothing in the next fortnight", |
| + "/week/2026-11-02": "", |
| + "/month/2026-11": "", |
| + "/calendars": "", |
| + } { |
| + w := f.get(path) |
| + body := w.Body.String() |
| + if w.Code != http.StatusOK || !strings.Contains(body, "data-partial") || !strings.Contains(body, partialTitle) { |
| + t.Fatalf("%s under Unknown = %d, want the partial notice", path, w.Code) |
| + } |
| + if empty != "" && strings.Contains(body, empty) { |
| + t.Fatalf("%s under Unknown drew its empty state, which reads as a free day", path) |
| + } |
| + if strings.Contains(body, "cal-sentence>Nothing") || strings.Contains(body, "Shared with the team") { |
| + t.Fatalf("%s under Unknown said something about the team's time", path) |
| + } |
| + } |
| + if w := f.get("/"); w.Code != http.StatusSeeOther { |
| + t.Fatalf("/ under Unknown = %d, want today's redirect", w.Code) |
| + } |
| +} |
| + |
| +func TestTeamUnknownItemsAreRetryable(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('i') |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + e := f.event(p, subject, team, "Offsite", "2026-11-02T10:00", "2026-11-02T11:00") |
| + f.expired() |
| + for _, path := range []string{ |
| + "/events/" + itoa(e.ID), "/events/" + itoa(e.ID) + "/edit", "/events/" + itoa(e.ID) + "/delete", |
| + "/events/new", "/calendars/" + itoa(team) + ".ics", "/calendars/" + itoa(team) + "/share", |
| + "/import", "/settings", "/settings/booking", "/settings/booking/new", |
| + "/api/native/session", "/api/native/events?from=2026-11-01&to=2026-11-08", |
| + } { |
| + retryable(t, path, f.get(path)) |
| + } |
| + for _, path := range []string{"/events", "/events/quick", "/events/" + itoa(e.ID), "/settings", "/calendars/" + itoa(team) + "/feeds"} { |
| + retryable(t, "POST "+path, f.post(path, "title=x")) |
| + } |
| +} |
| + |
| +func itoa(n int64) string { return strconv.FormatInt(n, 10) } |
diff --git a/internal/calendar/team_answers.go b/internal/calendar/team_answers.go| new file mode 100644 |
| index 0000000..b53af0f |
| --- /dev/null |
| +++ b/internal/calendar/team_answers.go |
| @@ -0,0 +1,114 @@ |
| +package calendar |
| + |
| +// Team mode's answers: the retryable 503 for Unknown standing, the partial |
| +// list's notice, and the probe. None of it is reached outside team mode. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// retryAfter is the roster's own retry interval, in whole seconds, as |
| +// every team-mode 503 says it. |
| +var retryAfter = strconv.Itoa(int(roster.RetryAfter / time.Second)) |
| + |
| +// teamUnavailable is the retryable answer for Unknown standing: the app's |
| +// own 503 page, or a plain 503 for the native API and anything else that |
| +// did not ask for a page — never cached, with Retry-After. A 404 would |
| +// tell a team member their event is gone because Home was slow. |
| +func (h *handlers) teamUnavailable(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Retry-After", retryAfter) |
| + if strings.HasPrefix(r.URL.Path, "/api/") { |
| + http.Error(w, "Team access could not be checked just now. Try again in a moment.", http.StatusServiceUnavailable) |
| + return |
| + } |
| + h.errorPage(w, r, http.StatusServiceUnavailable, "") |
| +} |
| + |
| +// teamUnavailablePlain is teamUnavailable for a reader that is not a |
| +// person at a page: a subscription feed, the public booking routes. |
| +func teamUnavailablePlain(w http.ResponseWriter) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Retry-After", retryAfter) |
| + http.Error(w, "Unavailable just now. Try again in a moment.", http.StatusServiceUnavailable) |
| +} |
| + |
| +// requestUnknown reports whether this request's own standing is Unknown |
| +// now. It is also the partial-view rule (Paul, 2026-10-28, Home |
| +// implementation/teammode-package.md §4): the page shell asks it as the |
| +// page is drawn, after the view is built, of the same Access the view was |
| +// built with — State latches, so a lease that lapsed while building marks |
| +// the page partial. The store has already withheld the team rung |
| +// (team_reach.go), so a partial view holds what the person reaches |
| +// without standing, which in Calendar, with no shares, is nothing. |
| +// NotMember is never partial: it never reaches a view. Always false outside team mode, and for a request with no person |
| +// (a public page). It reads State, so a lease that lapsed since the gate |
| +// latches here, which is the point: a read that found nothing because the |
| +// lease ran out between the gate and the query must say "try again", not |
| +// "not found". |
| +func requestUnknown(r *http.Request) bool { |
| + p, ok := teamPersonFrom(r.Context()) |
| + return ok && p.access.State() == roster.Unknown |
| +} |
| + |
| +// The partial notice (Paul, 2026-10-28): what a view says when the roster |
| +// could not be read within its lease. Calendar has no shares, so the |
| +// partial view is always empty, and the notice is what keeps that from |
| +// reading as a free day. |
| +const ( |
| + partialTitle = "We couldn’t check your team access" |
| + partialBody = "The team’s calendars can’t be shown until it’s checked, so this view is not your real schedule. Try again in a moment." |
| +) |
| + |
| +// guardRefused answers a write the guard refused, and reports whether it |
| +// did. Standing lapsed between the route's gate and the commit: the same |
| +// retryable 503 as Unknown anywhere else, and a 404 for a definite "no" |
| +// (which one request's Access cannot reach once it has said Member, but |
| +// costs nothing to answer correctly). Outside team mode no error is ever |
| +// one of these. |
| +func (h *handlers) guardRefused(w http.ResponseWriter, r *http.Request, err error) bool { |
| + switch { |
| + case errors.Is(err, teammode.ErrUnavailable): |
| + h.teamUnavailable(w, r) |
| + case errors.Is(err, teammode.ErrNotMember): |
| + h.errorPage(w, r, http.StatusNotFound, "") |
| + default: |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// standingFor is the answer about somebody other than the request's own |
| +// person (App.standingOf), or nil outside team mode. |
| +func (h *handlers) standingFor(ctx context.Context, person int64) *teammode.Access { |
| + if h.standingOf == nil { |
| + return nil |
| + } |
| + return h.standingOf(ctx, person) |
| +} |
| + |
| +// teamProbe is GET /api/team, the readiness probe Alta polls at |
| +// provisioning step 11 before it activates this instance in Home's |
| +// directory: teammode's Probe, unauthenticated, no-store, |
| +// {team_mode, consumer, roster} and no account data, and |
| +// {"team_mode":false} with team mode off. |
| +func (a *App) teamProbe(w http.ResponseWriter, r *http.Request) { |
| + var rt *teammode.Runtime |
| + if a.team != nil { |
| + rt = a.team.Runtime |
| + } |
| + teammode.Probe(rt).ServeHTTP(w, r) |
| +} |
| + |
| +// PartialTitle and PartialBody are the partial notice's words |
| +// (team_answers.go), for the team-partial template. |
| +func (PageData) PartialTitle() string { return partialTitle } |
| +func (PageData) PartialBody() string { return partialBody } |
diff --git a/internal/calendar/team_booking.go b/internal/calendar/team_booking.go| new file mode 100644 |
| index 0000000..2ddb1e9 |
| --- /dev/null |
| +++ b/internal/calendar/team_booking.go |
| @@ -0,0 +1,58 @@ |
| +package calendar |
| + |
| +// Team mode's public booking pages. A published page is a live free/busy |
| +// oracle over every calendar its host can see (AGENTS.md, "What this rule |
| +// does NOT cover" 5), the team calendar included, and a hold or a move |
| +// writes onto the host's calendar. So the page, its picker, the hold, the |
| +// confirmation and a reschedule all stand on the HOST's standing, asked on |
| +// every request — as a presentation in Slides stands on its presenter |
| +// (oficina/slides #33): |
| +// |
| +// - Member: as before, with the host's Access carried so busy time is |
| +// read through the host's own reach and every write is guarded on it. |
| +// - NotMember: the page is gone, the router's own 404, as an unpublished |
| +// one is. A member taken off the team stops publishing the team's |
| +// free/busy within the lease. |
| +// - Unknown: 503, no-store, Retry-After; never a picker built from less |
| +// than the host's whole busy list (B23), and the picker asks again |
| +// after it is built (handlers_booking_public.go). |
| +// |
| +// A booker's own booking — its manage page, its .ics, and cancelling it — |
| +// is theirs by its token and stands on nobody's standing: those writes are |
| +// systemWrite. Mail to the host is decided at delivery (team_jobs.go). |
| + |
| +import ( |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// hostStanding decides a public booking request on its host's standing |
| +// and returns the request its reads and writes run on. Outside team mode |
| +// it is r and true. |
| +func (h *handlers) hostStanding(w http.ResponseWriter, r *http.Request, host Person) (*http.Request, bool) { |
| + if h.team == nil { |
| + return r, true |
| + } |
| + acc := h.standingFor(r.Context(), host.ID) |
| + switch acc.State() { |
| + case roster.Member: |
| + return r.WithContext(teammode.WithAccess(r.Context(), acc)), true |
| + case roster.NotMember: |
| + notFoundLikeTheRouter(w, r) |
| + default: |
| + teamUnavailablePlain(w) |
| + } |
| + return r, false |
| +} |
| + |
| +// bookersOwn is r for a booker acting on their own booking by its token: |
| +// in team mode its writes are the instance's (systemWrite), standing on |
| +// nobody's lease. Outside team mode it is r. |
| +func (h *handlers) bookersOwn(r *http.Request) *http.Request { |
| + if h.team == nil { |
| + return r |
| + } |
| + return r.WithContext(systemWrite(r.Context())) |
| +} |
diff --git a/internal/calendar/team_booking_test.go b/internal/calendar/team_booking_test.go| new file mode 100644 |
| index 0000000..4ebd7c6 |
| --- /dev/null |
| +++ b/internal/calendar/team_booking_test.go |
| @@ -0,0 +1,103 @@ |
| +package calendar |
| + |
| +import ( |
| + "amadan.net/oficina/home/roster" |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestTeamBookingPageStandsOnItsHost(t *testing.T) { |
| + w := newTeamWriteWorld(t) |
| + f := w.f |
| + box := f.mailbox() |
| + jar := f.cookies |
| + f.cookies = nil |
| + stranger := func(method, path, body string) *httptest.ResponseRecorder { |
| + f.cookies = map[string]*http.Cookie{} |
| + defer func() { f.cookies = nil }() |
| + return f.do(method, path, body) |
| + } |
| + if r := stranger("GET", w.path, ""); r.Code != http.StatusOK { |
| + t.Fatalf("host's page = %d", r.Code) |
| + } |
| + f.expired() |
| + if r := stranger("GET", w.path, ""); r.Code != http.StatusServiceUnavailable || r.Header().Get("Retry-After") == "" || !strings.Contains(r.Header().Get("Cache-Control"), "no-store") { |
| + t.Fatalf("host's page under Unknown = %d", r.Code) |
| + } |
| + retryable(t, "confirm under Unknown", stranger("POST", "/book/m/"+w.heldToken+"/confirm", "")) |
| + f.dir.Set(teamSubject('w'), "") |
| + f.refreshed() |
| + if r := stranger("GET", w.path, ""); r.Code != http.StatusNotFound { |
| + t.Fatalf("a removed host's page = %d, want 404", r.Code) |
| + } |
| + if r := stranger("POST", w.path, "start="+w.slots[2]+"&zone=UTC&name=Kim&address=kim%40example.org"); r.Code != http.StatusNotFound { |
| + t.Fatalf("a hold on a removed host's page = %d, want 404", r.Code) |
| + } |
| + if r := stranger("POST", "/book/m/"+w.heldToken+"/confirm", ""); r.Code != http.StatusNotFound { |
| + t.Fatalf("confirming with a removed host = %d, want 404", r.Code) |
| + } |
| + if r := stranger("GET", "/book/m/"+w.booked+"/reschedule", ""); r.Code != http.StatusNotFound { |
| + t.Fatalf("rescheduling with a removed host = %d, want 404", r.Code) |
| + } |
| + // The booker's own booking stays theirs: they can see it and cancel. |
| + if r := stranger("GET", "/book/m/"+w.booked, ""); r.Code != http.StatusOK { |
| + t.Fatalf("the booker's manage page = %d", r.Code) |
| + } |
| + if r := stranger("POST", "/book/m/"+w.booked+"/cancel", ""); r.Code != http.StatusOK { |
| + t.Fatalf("the booker's cancel = %d", r.Code) |
| + } |
| + var b Booking |
| + f.app.db.G.Where("state = ?", BookingCancelled).First(&b) |
| + if b.ID == 0 { |
| + t.Fatal("the booker could not cancel") |
| + } |
| + // The booker is told; the removed host is not. |
| + f.app.h.drain(context.Background(), time.Now()) |
| + if len(box.to("jo@example.org")) == 0 { |
| + t.Fatal("the booker was not told of their cancellation") |
| + } |
| + if got := box.to("alice@example.test"); len(got) != 0 { |
| + t.Fatalf("a removed host was mailed: %v", got) |
| + } |
| + var owed int64 |
| + f.app.db.G.Model(&BookingMail{}).Where("sent_at IS NULL AND recipient = ?", ToHost).Count(&owed) |
| + if owed != 0 { |
| + t.Fatal("a removed host's mail was left owed rather than retired") |
| + } |
| + f.cookies = jar |
| +} |
| + |
| +// The picker is the host's whole busy list or a retry: a lapse while busy |
| +// time was being read must never offer a slot the host is busy in (B23's |
| +// fail-closed, on the host's standing). |
| +func TestTeamBookingPickerNeverOffersBusyTimeDuringALapse(t *testing.T) { |
| + seen := map[string]bool{} |
| + for k := 1; k <= 40; k++ { |
| + w := newTeamWriteWorld(t) |
| + f := w.f |
| + day, _ := time.Parse("2006-01-02", w.day) |
| + busy := day.Add(14 * time.Hour) |
| + _, personal := f.calendarsOf(w.alice) |
| + f.event(w.alice, teamSubject('w'), personal, "Busy", busy.Format("2006-01-02T15:04"), busy.Add(30*time.Minute).Format("2006-01-02T15:04")) |
| + f.cookies = map[string]*http.Cookie{} |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + got := f.get(w.path + "?day=" + w.day + "&zone=UTC") |
| + switch { |
| + case got.Code == http.StatusServiceUnavailable: |
| + seen["retry"] = true |
| + case got.Code == http.StatusOK && !strings.Contains(got.Body.String(), `value="`+itoa(busy.Unix())+`"`): |
| + seen["whole"] = true |
| + default: |
| + t.Fatalf("k=%d: picker = %d, offering the busy slot %v", k, got.Code, strings.Contains(got.Body.String(), itoa(busy.Unix()))) |
| + } |
| + } |
| + if !seen["whole"] || !seen["retry"] { |
| + t.Fatalf("the sweep saw %v", seen) |
| + } |
| +} |
diff --git a/internal/calendar/team_config.go b/internal/calendar/team_config.go| new file mode 100644 |
| index 0000000..584396a |
| --- /dev/null |
| +++ b/internal/calendar/team_config.go |
| @@ -0,0 +1,109 @@ |
| +package calendar |
| + |
| +// Team mode: Home's roster decides standing (Home implementation/ |
| +// team-members.md Part B §7; implementation/teammode-package.md §7.3). |
| +// Configuration, the marker, the roster runtime and the probe are |
| +// home/teammode's: CALENDAR_TEAM_ID, _DIRECTORY_ORIGIN, |
| +// _PROVISIONING_BASE64, _OPERATOR_KEYS_BASE64 and _ROSTER_TOKEN, all or |
| +// none, and only beside CALENDAR_HOME_*. Without them nothing in this |
| +// file runs and Calendar is the allowlist app it has always been. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/handoff/seal" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/oficina/calendar/internal/calendar/teamstate" |
| +) |
| + |
| +var ( |
| + errTeamConfig = teammode.ErrConfig |
| + errTeamUnavailable = teammode.ErrUnavailable |
| +) |
| + |
| +// homeNamespace is Calendar's Home storage namespace: connect's link and |
| +// handoff sealing, and in team mode the roster evidence's. |
| +const homeNamespace = "oficina/calendar" |
| + |
| +// teamState is the activation marker and the roster evidence, in |
| +// calendar_team_required and calendar_team_roster_evidence (migration set |
| +// calendar_team, teammode's own SQL). The marker is read before anything |
| +// migrates (teamBootSchema). |
| +var teamState = teammode.MustState("calendar") |
| + |
| +// teamIssuerTables are the tables holding Home identities in an issuer |
| +// column: connect's links and Calendar's Home-only people. teammode.Open |
| +// refuses activation while any row names another issuer. |
| +var teamIssuerTables = []string{"home_identity_links", "calendar_team_home_people"} |
| + |
| +// teamBoot is base plus team state: teammode's marker set, then |
| +// Calendar's Home-only people (whose triggers name people and |
| +// home_identity_links, so it follows both). Applied only in team mode; |
| +// once applied it stays, because the marker in it is what keeps the |
| +// database in team mode. |
| +func teamBoot(base *migrate.Set) *migrate.Set { |
| + return migrate.Merge(base, teamState.Schema(), teamstate.Schema) |
| +} |
| + |
| +// teamSettings verifies team configuration for this instance: nil, nil |
| +// with team mode off; otherwise a verified record or errTeamConfig. Team |
| +// mode exists only beside Home, and the record is verified against the |
| +// same Home issuer, consumer ID and origin the bridge is built with. It |
| +// touches no database, which is what lets New decide the schema before |
| +// anything migrates. |
| +func teamSettings(cfg *teammode.Config, home *connect.DecodedCredentials, origin string) (*teammode.Settings, error) { |
| + if cfg == nil { |
| + return nil, nil |
| + } |
| + if home == nil { |
| + return nil, errTeamConfig |
| + } |
| + return teammode.Verify(cfg, &teammode.Home{Issuer: home.Issuer, ConsumerID: home.ConsumerID}, "calendar", origin) |
| +} |
| + |
| +// teamBootSchema is the schema New applies, chosen before anything is |
| +// migrated. A database activated in team mode refuses to boot without |
| +// team configuration, or with a different binding: an environment |
| +// variable dropped in a redeploy must not quietly hand standing back to |
| +// CALENDAR_ALLOWED_ADDRESSES. |
| +func teamBootSchema(ctx context.Context, db *sql.DB, settings *teammode.Settings, base *migrate.Set) (*migrate.Set, error) { |
| + return teamState.BootSchema(ctx, db, settings, base, teamBoot(base)) |
| +} |
| + |
| +// teamRuntime is the process's roster runtime and the database the |
| +// Home-only people table lives in. |
| +type teamRuntime struct { |
| + *teammode.Runtime |
| + db *sql.DB |
| +} |
| + |
| +func (t *teamRuntime) issuer() string { return t.Bindings().Issuer } |
| + |
| +// configureTeam runs after the schema is applied and Home is configured, |
| +// before serving. Without settings it does nothing. Anything else either |
| +// produces a verified, activated runtime or refuses boot: there is no |
| +// falling back to the allowlist. |
| +func (a *App) configureTeam(settings *teammode.Settings, home *connect.DecodedCredentials) error { |
| + if settings == nil { |
| + return nil |
| + } |
| + if a.home == nil || home == nil { |
| + return errTeamConfig |
| + } |
| + sealer, err := seal.New(home.DEK, homeNamespace) |
| + if err != nil { |
| + return errTeamConfig |
| + } |
| + w := a.db.Writer() |
| + rt, err := teammode.Open(context.Background(), teammode.RuntimeConfig{Settings: settings, State: teamState, DB: w, Sealer: sealer, |
| + IssuerTables: teamIssuerTables, Transport: a.cfg.teamTransport, Clock: a.cfg.teamClock}) |
| + if err != nil { |
| + return err |
| + } |
| + a.team = &teamRuntime{Runtime: rt, db: w} |
| + return nil |
| +} |
diff --git a/internal/calendar/team_config_test.go b/internal/calendar/team_config_test.go| new file mode 100644 |
| index 0000000..796b0bf |
| --- /dev/null |
| +++ b/internal/calendar/team_config_test.go |
| @@ -0,0 +1,278 @@ |
| +package calendar |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +// markerFor reports whether dbPath holds an activation marker, opening |
| +// it read-only of the app. |
| +func markerFor(t *testing.T, dbPath string) bool { |
| + t.Helper() |
| + d, err := db.Open(dbPath, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + _, activated, err := teamState.Required(context.Background(), d.Writer()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return activated |
| +} |
| + |
| +func TestTeamConfigPinsTheProvisioningRecord(t *testing.T) { |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, mutate := range map[string]func(*roster.Bindings){ |
| + "issuer": func(b *roster.Bindings) { b.Issuer = "https://id.elsewhere.test" }, |
| + "consumer": func(b *roster.Bindings) { b.Consumer = "someone-else" }, |
| + "app": func(b *roster.Bindings) { b.App = "slides" }, |
| + "origin": func(b *roster.Bindings) { b.Audience = "https://calendar.elsewhere.test" }, |
| + "team": func(b *roster.Bindings) { b.Team = "TeamB" }, |
| + "directory": func(b *roster.Bindings) { b.Directory = "https://home.elsewhere.test" }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + b := teamTestBindings() |
| + mutate(&b) |
| + dbPath := filepath.Join(t.TempDir(), "calendar.db") |
| + cfg, _, _ := teamConfigFor(t, b, key, dbPath, "") |
| + if name == "team" || name == "directory" { |
| + // The record names the team and directory; the instance's |
| + // own configuration must name the same ones. |
| + good, _, _ := teamConfigFor(t, teamTestBindings(), key, dbPath, "") |
| + good.Team.ProvisioningBase64 = cfg.Team.ProvisioningBase64 |
| + good.Team.OperatorKeysBase64 = cfg.Team.OperatorKeysBase64 |
| + cfg = good |
| + } |
| + a, err := New(cfg) |
| + if err == nil { |
| + a.Close() |
| + t.Fatalf("a record signed for another %s was accepted", name) |
| + } |
| + if markerFor(t, dbPath) { |
| + t.Fatalf("a refused %s wrote the marker", name) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestTeamEnvIsAllOrNoneAndNeedsHome(t *testing.T) { |
| + for _, name := range teammode.EnvNames("CALENDAR") { |
| + env := map[string]string{} |
| + for _, n := range teammode.EnvNames("CALENDAR") { |
| + env[n] = "x" |
| + } |
| + delete(env, name) |
| + if c := teammode.ConfigFromLookup("CALENDAR", func(k string) string { return env[k] }); c == nil { |
| + t.Fatalf("four of five (%s missing) read as team mode off", name) |
| + } else { |
| + key, _ := assertioncrypto.Generate() |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key, filepath.Join(t.TempDir(), "calendar.db"), "") |
| + cfg.Team = c |
| + if a, err := New(cfg); err == nil { |
| + a.Close() |
| + t.Fatalf("four of five (%s missing) booted", name) |
| + } |
| + } |
| + } |
| + key, _ := assertioncrypto.Generate() |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key, filepath.Join(t.TempDir(), "calendar.db"), "") |
| + cfg.Home = nil |
| + if a, err := New(cfg); err == nil { |
| + a.Close() |
| + t.Fatal("team mode booted without Home") |
| + } |
| +} |
| + |
| +func TestTeamTheAllowlistBecomesOptionalAndAdmitsOnlyLocally(t *testing.T) { |
| + team := &teammode.Config{TeamID: "TeamA"} |
| + for _, env := range []string{"production", "development"} { |
| + list, err := resolveAllowlist(Config{Env: env, Team: team}) |
| + if err != nil { |
| + t.Fatalf("%s team mode with no allowlist: %v", env, err) |
| + } |
| + // Never the development default that admits everyone. |
| + if list.addrs == nil || list.allows("anyone@example.test") { |
| + t.Fatalf("an empty %s team allowlist admits somebody locally", env) |
| + } |
| + list, err = resolveAllowlist(Config{Env: env, Team: team, AllowedAddresses: "alice@example.test"}) |
| + if err != nil || !list.allows("alice@example.test") || list.allows("bob@example.test") { |
| + t.Fatalf("a %s team allowlist is not the local door: %v", env, err) |
| + } |
| + } |
| + // Off team mode the old refusal stands. |
| + if _, err := resolveAllowlist(Config{Env: "production"}); err == nil { |
| + t.Fatal("production without team mode accepted no allowlist") |
| + } |
| + // The fixture's app: an empty list admits nobody. |
| + f := newTeamFixture(t, "") |
| + if f.app.home.admitted.allows("anyone@example.test") { |
| + t.Fatal("an empty team allowlist admits everyone") |
| + } |
| +} |
| + |
| +func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.app.Close() |
| + if !markerFor(t, f.dbPath) { |
| + t.Fatal("team mode wrote no marker") |
| + } |
| + // Without team configuration: refused, before anything migrates. |
| + off := f.cfg |
| + off.Team = nil |
| + if a, err := New(off); err == nil { |
| + a.Close() |
| + t.Fatal("an activated database booted without team mode") |
| + } |
| + // With another binding: refused. |
| + key, _ := assertioncrypto.Generate() |
| + b := teamTestBindings() |
| + b.Team = "TeamB" |
| + other, _, _ := teamConfigFor(t, b, key, f.dbPath, "") |
| + other.Home = f.cfg.Home |
| + if a, err := New(other); err == nil { |
| + a.Close() |
| + t.Fatal("an activated database booted on another team") |
| + } |
| + // The same configuration boots again. |
| + again, err := New(f.cfg) |
| + if err != nil { |
| + t.Fatalf("the same binding refused: %v", err) |
| + } |
| + defer again.Close() |
| + w := again.DBForTest() |
| + if _, err := w.Exec("DELETE FROM calendar_team_required"); err == nil { |
| + t.Fatal("the marker was deleted") |
| + } |
| + if _, err := w.Exec("UPDATE calendar_team_required SET bindings = 'x'"); err == nil { |
| + t.Fatal("the marker was rewritten") |
| + } |
| +} |
| + |
| +func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| + // Named here, not read from teamIssuerTables: a list that lost a table |
| + // would otherwise lose its test with it. |
| + for _, table := range []string{"home_identity_links", "calendar_team_home_people"} { |
| + t.Run(table, func(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.app.Close() |
| + // A fresh database, migrated in team mode's shape but not yet |
| + // activated, holding one row from another issuer. |
| + dbPath := filepath.Join(t.TempDir(), "calendar.db") |
| + cfg := f.cfg |
| + cfg.DBPath = dbPath |
| + d := teamMigratedNotActivated(t, dbPath) |
| + w := d.Writer() |
| + var person int64 |
| + if table == "calendar_team_home_people" { |
| + res, err := w.Exec(`INSERT INTO people(address,zone,created_at,updated_at,week_start,default_reminder_min,default_all_day_min) VALUES('home-only:x','UTC',0,0,1,0,0)`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + person, _ = res.LastInsertId() |
| + } else { |
| + person = 99 |
| + } |
| + if _, err := w.Exec("INSERT INTO "+table+"(issuer,subject,person_id) VALUES('https://id.elsewhere.test',?,?)", teamSubject('q'), person); err != nil { |
| + t.Fatal(err) |
| + } |
| + d.Close() |
| + if a, err := New(cfg); err == nil { |
| + a.Close() |
| + t.Fatalf("a foreign issuer in %s was accepted", table) |
| + } else if !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("refused for another reason: %v", err) |
| + } |
| + if markerFor(t, dbPath) { |
| + t.Fatal("a refused census wrote the marker") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestTeamProbeOffSaysOnlyThat(t *testing.T) { |
| + a := NewForTest(t, t.TempDir()) |
| + w := httptest.NewRecorder() |
| + a.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/api/team", nil)) |
| + if w.Code != http.StatusOK || strings.TrimSpace(w.Body.String()) != `{"team_mode":false}` || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { |
| + t.Fatalf("probe off = %d %q %q", w.Code, w.Body.String(), w.Header().Get("Cache-Control")) |
| + } |
| +} |
| + |
| +func TestTeamProbeStatesAndNoAccountData(t *testing.T) { |
| + f := newTeamFixture(t) |
| + probe := func() map[string]any { |
| + t.Helper() |
| + w := httptest.NewRecorder() |
| + f.app.Handler().ServeHTTP(w, httptest.NewRequest("GET", homeTestOrigin+"/api/team", nil)) |
| + if w.Code != http.StatusOK || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { |
| + t.Fatalf("probe = %d", w.Code) |
| + } |
| + var out map[string]any |
| + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + for k := range out { |
| + if k != "team_mode" && k != "consumer" && k != "roster" { |
| + t.Fatalf("probe carries %q", k) |
| + } |
| + } |
| + if strings.Contains(w.Body.String(), teamSubject('p')) || strings.Contains(w.Body.String(), "TeamA") { |
| + t.Fatal("probe names a member or the team") |
| + } |
| + return out |
| + } |
| + f.dir.SetDown(true) |
| + if got := probe(); got["team_mode"] != true || got["consumer"] != teamTestConsumer || got["roster"] != "unknown" { |
| + t.Fatalf("probe before any roster = %v", got) |
| + } |
| + f.dir.SetDown(false) |
| + f.clock.Step(10 * time.Second) |
| + if got := probe(); got["roster"] != "ok" { |
| + t.Fatalf("probe with a roster = %v", got) |
| + } |
| + f.member(teamSubject('p'), "owner") |
| + if got := probe(); got["roster"] != "ok" { |
| + t.Fatalf("probe after a member's request = %v", got) |
| + } |
| + f.expired() |
| + if got := probe(); got["roster"] != "stale" { |
| + t.Fatalf("probe past the lease = %v", got) |
| + } |
| +} |
| + |
| +// teamMigratedNotActivated opens a fresh database at dbPath with every |
| +// set team mode applies — Calendar's, Home's, teammode's marker and the |
| +// Home-only people — and no marker written. |
| +func teamMigratedNotActivated(t *testing.T, dbPath string) *db.DB { |
| + t.Helper() |
| + d, err := db.Open(dbPath, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + base := migrate.Merge(BootSchema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace)) |
| + if _, err := migrate.Apply(context.Background(), d, teamBoot(base)); err != nil { |
| + t.Fatal(err) |
| + } |
| + return d |
| +} |
diff --git a/internal/calendar/team_feed.go b/internal/calendar/team_feed.go| new file mode 100644 |
| index 0000000..e77f18c |
| --- /dev/null |
| +++ b/internal/calendar/team_feed.go |
| @@ -0,0 +1,71 @@ |
| +package calendar |
| + |
| +// Team mode's subscription feeds. A feed URL is a capability (Home |
| +// teammode-package.md §7.3: "Published .ics feed tokens stay capability |
| +// links"), but what it reads, it reads on its MINTER's standing, asked on |
| +// every poll — exactly as a presentation in Slides stands on its presenter |
| +// (oficina/slides #33). So: |
| +// |
| +// - Member: the calendar, as before. |
| +// - NotMember: the feed is gone, the same 404 as a revoked or unknown |
| +// token. A member taken off the team stops receiving the team's |
| +// calendar within the lease, in every account they pasted the URL |
| +// into, without anybody having to find and revoke it. Re-added, the |
| +// URL works again; the token was never touched. |
| +// - Unknown: 503, no-store, Retry-After. A subscriber (Google, Apple, |
| +// Outlook) is a cross-origin reader that cannot see a partial notice, |
| +// so it must never be served a short calendar (Paul's ruling, |
| +// 2026-10-28, condition 3). Those clients keep the copy they last |
| +// fetched when a poll fails, so a 503 is "keep the last good feed" |
| +// without this server rendering anything under Unknown or storing a |
| +// plaintext copy to replay (which the one rule forbids). |
| +// |
| +// Standing is read before the calendar is (the stream-order lesson), and |
| +// again after the feed is built: a lease that lapsed in between is a 503, |
| +// never a calendar some of whose events were withheld. |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// feedStanding decides a feed's poll on its minter's standing and returns |
| +// the context its reads run on. Outside team mode it is r's own context |
| +// and true. |
| +func (h *handlers) feedStanding(w http.ResponseWriter, r *http.Request, f Feed) (context.Context, bool) { |
| + if h.team == nil { |
| + return r.Context(), true |
| + } |
| + acc := h.standingFor(r.Context(), f.PersonID) |
| + switch acc.State() { |
| + case roster.Member: |
| + return teammode.WithAccess(r.Context(), acc), true |
| + case roster.NotMember: |
| + http.NotFound(w, r) |
| + default: |
| + teamUnavailablePlain(w) |
| + } |
| + return nil, false |
| +} |
| + |
| +// feedNotFound answers a feed whose calendar the minter no longer reaches: |
| +// the 404 it has always been, unless the minter's standing lapsed while |
| +// reading, which is a retry. |
| +func (h *handlers) feedNotFound(w http.ResponseWriter, r *http.Request, ctx context.Context) { |
| + if standingLapsed(ctx) { |
| + teamUnavailablePlain(w) |
| + return |
| + } |
| + http.NotFound(w, r) |
| +} |
| + |
| +// standingLapsed reports whether the standing a feed's (or a booking |
| +// page's) reads ran on is no longer Member. Always false outside team mode |
| +// (no Access on ctx is carried there, and none is asked for). |
| +func standingLapsed(ctx context.Context) bool { |
| + acc, ok := teammode.FromContext(ctx) |
| + return ok && acc.State() != roster.Member |
| +} |
diff --git a/internal/calendar/team_feeds_test.go b/internal/calendar/team_feeds_test.go| new file mode 100644 |
| index 0000000..3c65ed5 |
| --- /dev/null |
| +++ b/internal/calendar/team_feeds_test.go |
| @@ -0,0 +1,223 @@ |
| +package calendar |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/dashboard" |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +func TestTeamFeedStandsOnItsMinter(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('f') |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + f.event(p, subject, team, "Feed title", "2026-11-02T10:00", "2026-11-02T11:00") |
| + loc := f.post("/calendars/"+itoa(team)+"/feeds", "").Header().Get("Location") |
| + u, _ := url.Parse(loc) |
| + token := u.Query().Get("token") |
| + if token == "" { |
| + t.Fatalf("no token in %q", loc) |
| + } |
| + feed := func() (int, string, http.Header) { |
| + w := f.do("GET", "/feed/"+token+".ics", "") |
| + return w.Code, w.Body.String(), w.Header() |
| + } |
| + if code, body, _ := feed(); code != http.StatusOK || !strings.Contains(body, "Feed title") { |
| + t.Fatalf("member's feed = %d", code) |
| + } |
| + f.expired() |
| + if code, body, h := feed(); code != http.StatusServiceUnavailable || h.Get("Retry-After") == "" || !strings.Contains(h.Get("Cache-Control"), "no-store") || strings.Contains(body, "VCALENDAR") { |
| + t.Fatalf("feed under Unknown = %d %q %q, want a retryable no-store 503 and no calendar", code, h.Get("Retry-After"), h.Get("Cache-Control")) |
| + } |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| + if code, body, _ := feed(); code != http.StatusNotFound || strings.Contains(body, "Feed title") { |
| + t.Fatalf("a removed minter's feed = %d", code) |
| + } |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + if code, body, _ := feed(); code != http.StatusOK || !strings.Contains(body, "Feed title") { |
| + t.Fatalf("a re-added minter's feed = %d", code) |
| + } |
| + // Never a short calendar: whenever the lease runs out mid-read, the |
| + // answer is the whole calendar or a 503. |
| + sweep(t, func() (*teamFixture, func() string) { |
| + f := newTeamFixture(t) |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + f.event(p, subject, team, "Feed title", "2026-11-02T10:00", "2026-11-02T11:00") |
| + u, _ := url.Parse(f.post("/calendars/"+itoa(team)+"/feeds", "").Header().Get("Location")) |
| + token := u.Query().Get("token") |
| + return f, func() string { |
| + w := f.do("GET", "/feed/"+token+".ics", "") |
| + switch { |
| + case w.Code == http.StatusOK && strings.Contains(w.Body.String(), "Feed title"): |
| + return "whole" |
| + case w.Code == http.StatusServiceUnavailable: |
| + return "retry" |
| + } |
| + t.Fatalf("feed during a lapse = %d, with the event %v", w.Code, strings.Contains(w.Body.String(), "Feed title")) |
| + return "" |
| + } |
| + }, "whole", "retry") |
| +} |
| + |
| +func TestTeamDashboardFeedFollowsTheRoster(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('d') |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + start := time.Now().UTC().Add(26 * time.Hour) |
| + f.event(p, subject, team, "Dashboard item", start.Format("2006-01-02T15:04"), start.Add(time.Hour).Format("2006-01-02T15:04")) |
| + read := func() (dashboard.Response, error) { |
| + return f.app.dashboardEvents(context.Background(), p.ID, subject, time.Now()) |
| + } |
| + if got, err := read(); err != nil || len(got.Items) != 1 || got.Items[0].Title != "Dashboard item" { |
| + t.Fatalf("member's dashboard = %+v %v", got, err) |
| + } |
| + f.expired() |
| + if _, err := read(); !errors.Is(err, dashboard.ErrUnavailable) { |
| + t.Fatalf("dashboard under Unknown = %v, want unavailable (never short)", err) |
| + } |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| + if got, err := read(); err != nil || len(got.Items) != 0 { |
| + t.Fatalf("removed member's dashboard = %+v %v, want empty", got, err) |
| + } |
| + sweep(t, func() (*teamFixture, func() string) { |
| + f := newTeamFixture(t) |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + f.event(p, subject, team, "Dashboard item", start.Format("2006-01-02T15:04"), start.Add(time.Hour).Format("2006-01-02T15:04")) |
| + return f, func() string { |
| + got, err := f.app.dashboardEvents(context.Background(), p.ID, subject, time.Now()) |
| + switch { |
| + case err == nil && len(got.Items) == 1: |
| + return "whole" |
| + case errors.Is(err, dashboard.ErrUnavailable): |
| + return "retry" |
| + } |
| + t.Fatalf("dashboard during a lapse = %+v %v", got, err) |
| + return "" |
| + } |
| + }, "whole", "retry") |
| +} |
| + |
| +func TestTeamListsDuringALapseAreWholeOrSayPartial(t *testing.T) { |
| + subject := teamSubject('s') |
| + world := func() *teamFixture { |
| + f := newTeamFixture(t) |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + f.event(p, subject, team, "Swept", "2026-11-02T10:00", "2026-11-02T11:00") |
| + return f |
| + } |
| + sweep(t, func() (*teamFixture, func() string) { |
| + f := world() |
| + return f, func() string { |
| + w := f.get("/day/2026-11-02") |
| + body := w.Body.String() |
| + has, partial := strings.Contains(body, "Swept"), strings.Contains(body, "data-partial") |
| + switch { |
| + case w.Code == http.StatusOK && has && !partial: |
| + return "whole" |
| + case w.Code == http.StatusOK && partial: |
| + return "partial" |
| + } |
| + t.Fatalf("day during a lapse = %d, event %v, partial %v: short without a notice", w.Code, has, partial) |
| + return "" |
| + } |
| + }, "whole", "partial") |
| + sweep(t, func() (*teamFixture, func() string) { |
| + f := world() |
| + return f, func() string { |
| + w := f.get("/api/native/events?from=2026-11-01&to=2026-11-08") |
| + switch { |
| + case w.Code == http.StatusOK && strings.Contains(w.Body.String(), "Swept"): |
| + return "whole" |
| + case w.Code == http.StatusServiceUnavailable: |
| + return "retry" |
| + } |
| + t.Fatalf("native list during a lapse = %d, short", w.Code) |
| + return "" |
| + } |
| + }, "whole", "retry") |
| + sweep(t, func() (*teamFixture, func() string) { |
| + f := world() |
| + team, _ := f.calendarsOf(f.personFor(subject)) |
| + return f, func() string { |
| + w := f.get("/calendars/" + itoa(team) + ".ics") |
| + switch { |
| + case w.Code == http.StatusOK && strings.Contains(w.Body.String(), "Swept"): |
| + return "whole" |
| + case w.Code == http.StatusServiceUnavailable: |
| + return "retry" |
| + } |
| + t.Fatalf("export during a lapse = %d, short", w.Code) |
| + return "" |
| + } |
| + }, "whole", "retry") |
| + // An item page is the event or a retry: never "not found" because |
| + // Home was slow, never our 500. |
| + sweep(t, func() (*teamFixture, func() string) { |
| + f := world() |
| + var e Event |
| + f.app.db.G.First(&e) |
| + return f, func() string { |
| + w := f.get("/events/" + itoa(e.ID)) |
| + switch { |
| + case w.Code == http.StatusOK && strings.Contains(w.Body.String(), "Swept"): |
| + return "whole" |
| + case w.Code == http.StatusServiceUnavailable: |
| + return "retry" |
| + } |
| + t.Fatalf("event page during a lapse = %d", w.Code) |
| + return "" |
| + } |
| + }, "whole", "retry") |
| + // So is the native editor's save: saved, or a retry. |
| + sweep(t, func() (*teamFixture, func() string) { |
| + f := world() |
| + var e Event |
| + f.app.db.G.First(&e) |
| + return f, func() string { |
| + w := f.post("/api/native/events/"+itoa(e.ID), `{"title":"Swept again","start_local":"2026-11-02T10:00","end_local":"2026-11-02T11:00","tz":"UTC"}`) |
| + switch w.Code { |
| + case http.StatusOK: |
| + return "whole" |
| + case http.StatusServiceUnavailable: |
| + return "retry" |
| + } |
| + t.Fatalf("native save during a lapse = %d", w.Code) |
| + return "" |
| + } |
| + }, "whole", "retry") |
| +} |
| + |
| +// sweep runs read at the lease's edge — directory down, the clock k ms |
| +// short of the lease, 1 ms passing at every reading — for k from 1 to 40, |
| +// each on a fresh fixture from build, so the lease runs out at every point |
| +// inside one request; it fails unless every outcome in want was seen. |
| +func sweep(t *testing.T, build func() (*teamFixture, func() string), want ...string) { |
| + t.Helper() |
| + seen := map[string]bool{} |
| + for k := 1; k <= 40; k++ { |
| + f, read := build() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + seen[read()] = true |
| + } |
| + for _, w := range want { |
| + if !seen[w] { |
| + t.Fatalf("the sweep never saw %q (saw %v)", w, seen) |
| + } |
| + } |
| +} |
diff --git a/internal/calendar/team_fixture_test.go b/internal/calendar/team_fixture_test.go| new file mode 100644 |
| index 0000000..c5865e1 |
| --- /dev/null |
| +++ b/internal/calendar/team_fixture_test.go |
| @@ -0,0 +1,247 @@ |
| +package calendar |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// Team mode's fixture: Home configured exactly as homeRouterFixture does |
| +// (same issuer, origin and assertion key id, so its local and exchange |
| +// helpers drive this app too), and home/teammode's test directory |
| +// (teammodetest) answering the roster in memory from a member list a test |
| +// can change or take down, with a roster clock a test can step past the |
| +// lease. |
| + |
| +const teamTestConsumer = "calendar-test" |
| + |
| +// teamSubject is a well-formed person ref: "pr_" and 26 copies of c. |
| +func teamSubject(c byte) string { return teammodetest.Subject(c) } |
| + |
| +// teamTestBindings are this instance's: Home's issuer and consumer ID as |
| +// homeRouterFixture configures them, the test directory and team, |
| +// Calendar, and the test origin. |
| +func teamTestBindings() roster.Bindings { |
| + b := teammodetest.Bindings("calendar", teamTestConsumer, homeTestOrigin) |
| + b.Issuer = homeTestIssuer |
| + return b |
| +} |
| + |
| +type teamFixture struct { |
| + *homeRouterFixture |
| + t *testing.T |
| + dir *teammodetest.Directory |
| + clock *teammodetest.Clock |
| + cfg Config |
| + dbPath string |
| +} |
| + |
| +// teamConfigFor is a team-mode Config on bindings b over dbPath: Home as |
| +// homeRouterFixture has it, the record signed for b, and the test |
| +// directory and clock. allowed is CALENDAR_ALLOWED_ADDRESSES, which in team |
| +// mode only admits local sign-in; "" is Alta's shape. |
| +func teamConfigFor(t *testing.T, b roster.Bindings, key *assertioncrypto.Keypair, dbPath, allowed string) (Config, *teammodetest.Directory, *teammodetest.Clock) { |
| + t.Helper() |
| + tcfg, dir := teammodetest.Provision(t, b) |
| + clock := teammodetest.NewClock() |
| + manifest, _ := json.Marshal(map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}) |
| + cfg := Config{DBPath: dbPath, Env: "development", Origin: homeTestOrigin, AllowedAddresses: allowed, |
| + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), |
| + Home: &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: teamTestConsumer, KeysBase64: base64.StdEncoding.EncodeToString(manifest), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))}, |
| + Team: tcfg, teamTransport: dir, teamClock: clock} |
| + return cfg, dir, clock |
| +} |
| + |
| +func newTeamFixture(t *testing.T, allowed ...string) *teamFixture { |
| + t.Helper() |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + list := "alice@example.test" |
| + if len(allowed) == 1 { |
| + list = allowed[0] |
| + } |
| + dbPath := filepath.Join(t.TempDir(), "calendar.db") |
| + cfg, dir, clock := teamConfigFor(t, teamTestBindings(), key, dbPath, list) |
| + hf := &homeRouterFixture{key: key, cookies: map[string]*http.Cookie{}} |
| + cfg.homeNow = hf.now |
| + a, err := New(cfg) |
| + if err != nil { |
| + t.Fatalf("New in team mode: %v", err) |
| + } |
| + t.Cleanup(func() { a.Close() }) |
| + hf.app = a |
| + return &teamFixture{homeRouterFixture: hf, t: t, dir: dir, clock: clock, cfg: cfg, dbPath: dbPath} |
| +} |
| + |
| +// get and post are do with the fixture's cookie jar. |
| +func (f *teamFixture) get(path string) *httptest.ResponseRecorder { return f.do("GET", path, "") } |
| +func (f *teamFixture) post(path, body string) *httptest.ResponseRecorder { |
| + return f.do("POST", path, body) |
| +} |
| + |
| +// signInHome runs a full Home exchange for subject from an empty jar and |
| +// returns the finish response. |
| +func (f *teamFixture) signInHome(subject string) *httptest.ResponseRecorder { |
| + f.t.Helper() |
| + f.cookies = map[string]*http.Cookie{} |
| + return f.exchange(f.t, handoff.StartPath, subject) |
| +} |
| + |
| +// member adds subject to the roster with role, refreshes, and signs them |
| +// in with Home from an empty jar, failing unless they got a session; it |
| +// returns their person. |
| +func (f *teamFixture) member(subject, role string) Person { |
| + f.t.Helper() |
| + f.dir.Set(subject, role) |
| + f.refreshed() |
| + finish := f.signInHome(subject) |
| + if finish.Code != http.StatusSeeOther { |
| + f.t.Fatalf("sign-in of %s = %d %s", subject, finish.Code, finish.Body.String()) |
| + } |
| + if f.cookies[f.app.home.sessions.CookieName()] == nil { |
| + f.t.Fatalf("sign-in of %s minted no session", subject) |
| + } |
| + // The first page makes their calendars, as a local person's first |
| + // page does. |
| + if w := f.get("/calendars"); w.Code != http.StatusOK { |
| + f.t.Fatalf("first page of %s = %d", subject, w.Code) |
| + } |
| + return f.personFor(subject) |
| +} |
| + |
| +// personFor is the person a Home subject signs in as. |
| +func (f *teamFixture) personFor(subject string) Person { |
| + f.t.Helper() |
| + ref, err := f.app.home.bridge.Resolve(context.Background(), subject) |
| + if err != nil { |
| + f.t.Fatalf("resolve %s: %v", subject, err) |
| + } |
| + var p Person |
| + if err := f.app.db.G.First(&p, ref.ID).Error; err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return p |
| +} |
| + |
| +// linkedAlice signs alice@example.test in locally, links her to subject |
| +// through the real link flow, and leaves her signed in locally. subject |
| +// is put on the roster as role first, so the link is to a member. |
| +func (f *teamFixture) linkedAlice(subject, role string) Person { |
| + f.t.Helper() |
| + f.dir.Set(subject, role) |
| + f.refreshed() |
| + f.cookies = map[string]*http.Cookie{} |
| + f.local(f.t) |
| + if w := f.get("/account/home"); w.Code != http.StatusOK { |
| + f.t.Fatalf("link page %d %s", w.Code, w.Body.String()) |
| + } |
| + start := homeRedirect(f.t, f.post("/account/home", "")) |
| + if got := homeRedirect(f.t, f.exchange(f.t, start, subject)); got != "/account/home/confirm" { |
| + f.t.Fatalf("link exchange landed on %s", got) |
| + } |
| + homeRedirect(f.t, f.post("/account/home/confirm", "")) |
| + p, ok, err := f.app.store.PersonByAddress(context.Background(), "alice@example.test") |
| + if err != nil || !ok { |
| + f.t.Fatalf("alice: %v %v", ok, err) |
| + } |
| + if subj, err := f.app.homeSubjectOf(context.Background(), p.ID); err != nil || subj != subject { |
| + f.t.Fatalf("alice is linked to %q (%v), want %q", subj, err, subject) |
| + } |
| + return p |
| +} |
| + |
| +// refreshed steps the roster clock past the refresh point and waits for |
| +// the refresh, so the next request sees the directory's current list. |
| +func (f *teamFixture) refreshed() { |
| + f.t.Helper() |
| + f.dir.SetDown(false) |
| + f.clock.Step(roster.RefreshAfter + time.Second) |
| + if err := f.app.team.Refresh(context.Background()); err != nil { |
| + f.t.Fatalf("roster refresh: %v", err) |
| + } |
| +} |
| + |
| +// expired takes the directory down and steps past the lease: Unknown. |
| +func (f *teamFixture) expired() { |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| +} |
| + |
| +// withAccess is ctx carrying subject's standing now, for store calls a |
| +// test makes directly as that person. |
| +func (f *teamFixture) withAccess(subject string) context.Context { |
| + return teammode.WithAccess(context.Background(), f.app.team.Access(context.Background(), subject)) |
| +} |
| + |
| +// calendarsOf are p's team and personal calendar ids. |
| +func (f *teamFixture) calendarsOf(p Person) (team, personal int64) { |
| + f.t.Helper() |
| + var cals []Calendar |
| + if err := f.app.db.G.Joins("JOIN grants ON grants.calendar_id = calendars.id AND grants.person_id = ?", p.ID).Find(&cals).Error; err != nil { |
| + f.t.Fatal(err) |
| + } |
| + for _, c := range cals { |
| + switch c.Kind { |
| + case "team": |
| + team = c.ID |
| + case "personal": |
| + personal = c.ID |
| + } |
| + } |
| + if team == 0 || personal == 0 { |
| + f.t.Fatalf("person %d has calendars %+v", p.ID, cals) |
| + } |
| + return team, personal |
| +} |
| + |
| +// event makes an event on calendar as p, directly, standing on subject. |
| +func (f *teamFixture) event(p Person, subject string, calendar int64, title, start, end string) Event { |
| + f.t.Helper() |
| + e, err := f.app.store.CreateEvent(f.withAccess(subject), p.ID, EventInput{CalendarID: calendar, Title: title, StartLocal: start, EndLocal: end, TZ: "UTC", Kind: KindMeeting, Status: StatusConfirmed}) |
| + if err != nil { |
| + f.t.Fatalf("event %q: %v", title, err) |
| + } |
| + return e |
| +} |
| + |
| +// localSession puts a local (magic link) session for address in the jar, |
| +// as a sign-in the allowlist admitted would. |
| +func (f *teamFixture) localSession(address string) { |
| + f.t.Helper() |
| + w := httptest.NewRecorder() |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + if err := f.app.home.sessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + f.cookies = map[string]*http.Cookie{} |
| + for _, c := range w.Result().Cookies() { |
| + f.cookies[c.Name] = c |
| + } |
| +} |
| + |
| +// retryable fails unless w is the team-mode retryable 503. |
| +func retryable(t *testing.T, what string, w *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { |
| + t.Fatalf("%s = %d (Retry-After %q, Cache-Control %q), want a retryable no-store 503", what, w.Code, w.Header().Get("Retry-After"), w.Header().Get("Cache-Control")) |
| + } |
| +} |
diff --git a/internal/calendar/team_guard.go b/internal/calendar/team_guard.go| new file mode 100644 |
| index 0000000..9da572e |
| --- /dev/null |
| +++ b/internal/calendar/team_guard.go |
| @@ -0,0 +1,80 @@ |
| +package calendar |
| + |
| +// Team mode's write guard: the standing a write was admitted on, checked |
| +// again inside the transaction that commits it, before and after |
| +// (teammode.Guard; Home implementation/teammode-package.md §3, invariant |
| +// 13, and Fable's deviation 7 on oficina/sheets #52). The route's gate |
| +// (team_access.go) and the store's reach (team_reach.go) decide whether a |
| +// write may start; this decides whether it may commit, so a lease that |
| +// lapses between the two fails the write instead of landing it. It never |
| +// asks the roster: it reads the Access the context carries, whose lease |
| +// check never waits, so it is safe under the one-connection SQLite writer. |
| +// |
| +// Calendar has no shares (team_reach.go), so every person's write rests on |
| +// standing alone and needs Member: an event, a reminder, a feed, an |
| +// import, settings, a booking page. A public booking write stands on its |
| +// HOST's standing, carried the same way (team_booking.go). |
| +// |
| +// Outside team mode Store.team is false and every helper here is the |
| +// write path exactly as it was. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// teamGuard is teammode.Guard. A variable only so a test can let the |
| +// lease run out between a write and its commit on every write route. |
| +var teamGuard = teammode.Guard |
| + |
| +type systemWriteKey struct{} |
| + |
| +// systemWrite marks ctx as carrying writes that nobody's standing makes: |
| +// a booker's own cancellation, on the public routes, which stands on its |
| +// token alone (team_booking.go). The scheduled drain's bookkeeping — |
| +// claims, deferrals, fires, hold expiry, IP forgetting — and a feed's poll |
| +// counter never go through the guard at all. Whatever such work DELIVERS |
| +// to a person is decided on that person's own standing (team_jobs.go). |
| +func systemWrite(ctx context.Context) context.Context { |
| + return context.WithValue(ctx, systemWriteKey{}, true) |
| +} |
| + |
| +func isSystemWrite(ctx context.Context) bool { |
| + v, _ := ctx.Value(systemWriteKey{}).(bool) |
| + return v |
| +} |
| + |
| +// guard runs write under the standing ctx carries. Call it INSIDE the |
| +// write's transaction, with write using that transaction. Outside team |
| +// mode, and for a systemWrite, it is write alone. |
| +func (s *Store) guard(ctx context.Context, write func() error) error { |
| + if !s.team || isSystemWrite(ctx) { |
| + return write() |
| + } |
| + // A context with no Access reads as Unknown (teammode.Standing), so a |
| + // person's write that lost its standing on the way here is refused. |
| + return teamGuard(ctx, teammode.RequireMember, write) |
| +} |
| + |
| +// guarded runs write against the store's database exactly as it always |
| +// has outside team mode (and for a systemWrite), and in team mode in one |
| +// transaction, inside guard, against that transaction (never the outer |
| +// handle: the writer pool has one connection). |
| +func (s *Store) guarded(ctx context.Context, write func(db *gorm.DB) error) error { |
| + if !s.team || isSystemWrite(ctx) { |
| + return write(s.g.WithContext(ctx)) |
| + } |
| + return s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + return s.guard(ctx, func() error { return write(tx) }) |
| + }) |
| +} |
| + |
| +// standingRefusal reports whether err is the guard's (or a gate's) |
| +// refusal: Unknown standing, or a definite NotMember. |
| +func standingRefusal(err error) bool { |
| + return errors.Is(err, teammode.ErrUnavailable) || errors.Is(err, teammode.ErrNotMember) |
| +} |
diff --git a/internal/calendar/team_guard_test.go b/internal/calendar/team_guard_test.go| new file mode 100644 |
| index 0000000..a1d82b5 |
| --- /dev/null |
| +++ b/internal/calendar/team_guard_test.go |
| @@ -0,0 +1,252 @@ |
| +package calendar |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// teamSnapshot is every table a person's write can touch, row by row, so |
| +// "nothing it wrote survived" is read back rather than assumed. Sealed |
| +// columns carry a fresh nonce on every write, and every update moves |
| +// updated_at or a counter, so any write shows. |
| +func teamSnapshot(t *testing.T, f *teamFixture) string { |
| + t.Helper() |
| + var b strings.Builder |
| + for _, table := range []string{"events", "reminders", "reminder_queues", "feeds", "people", "booking_pages", "booking_windows", "bookings", "booking_mails", "attendees", "calendars", "grants"} { |
| + rows, err := f.app.DBForTest().Query("SELECT * FROM " + table + " ORDER BY rowid") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cols, _ := rows.Columns() |
| + for rows.Next() { |
| + vals := make([]any, len(cols)) |
| + ptrs := make([]any, len(cols)) |
| + for i := range vals { |
| + ptrs[i] = &vals[i] |
| + } |
| + if err := rows.Scan(ptrs...); err != nil { |
| + t.Fatal(err) |
| + } |
| + fmt.Fprintf(&b, "%s %v\n", table, vals) |
| + } |
| + rows.Close() |
| + } |
| + return b.String() |
| +} |
| + |
| +// lapsingGuard is teammode.Guard with the lease running out between the |
| +// write and its commit: authorize, write, the directory goes away and the |
| +// clock passes the lease, authorize again. |
| +func (f *teamFixture) lapsingGuard(ctx context.Context, authorize func(roster.State) error, write func() error) error { |
| + if err := authorize(teammode.Standing(ctx)); err != nil { |
| + return err |
| + } |
| + if err := write(); err != nil { |
| + return err |
| + } |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| + return authorize(teammode.Standing(ctx)) |
| +} |
| + |
| +// writeRoute is one write, and how to make it. |
| +type writeRoute struct { |
| + name string |
| + do func() *httptest.ResponseRecorder |
| +} |
| + |
| +// routes is every write a person (or, for the public booking routes, a |
| +// stranger on the host's standing) makes. Add yours. |
| +func (w *teamWriteWorld) routes() []writeRoute { |
| + f := w.f |
| + id := func(n int64) string { return itoa(n) } |
| + public := func(do func() *httptest.ResponseRecorder) func() *httptest.ResponseRecorder { |
| + return func() *httptest.ResponseRecorder { |
| + jar := f.cookies |
| + f.cookies = map[string]*http.Cookie{} |
| + defer func() { f.cookies = jar }() |
| + return do() |
| + } |
| + } |
| + json := func(path, body string) func() *httptest.ResponseRecorder { |
| + return func() *httptest.ResponseRecorder { return f.post(path, body) } |
| + } |
| + return []writeRoute{ |
| + {"create", func() *httptest.ResponseRecorder { |
| + return f.post("/events", "calendar_id="+id(w.team)+"&title=New&start=2027-01-06T10:00&end=2027-01-06T11:00&tz=UTC&kind=meeting&status=confirmed") |
| + }}, |
| + {"quick add", func() *httptest.ResponseRecorder { return f.post("/events/quick", "text=Lunch+tomorrow+at+1pm") }}, |
| + {"update", func() *httptest.ResponseRecorder { |
| + return f.post("/events/"+id(w.single.ID), "title=Renamed&start=2027-01-05T10:00&end=2027-01-05T11:00&tz=UTC&kind=meeting&status=confirmed") |
| + }}, |
| + {"update this occurrence", func() *httptest.ResponseRecorder { |
| + return f.post("/events/"+id(w.series.ID), "scope=this&occurrence=2027-01-06T09:00&title=Moved&start=2027-01-06T10:00&end=2027-01-06T10:15&tz=UTC&kind=meeting&status=confirmed") |
| + }}, |
| + {"split the series", func() *httptest.ResponseRecorder { |
| + return f.post("/events/"+id(w.series.ID), "scope=following&occurrence=2027-01-08T09:00&title=Later&start=2027-01-08T09:30&end=2027-01-08T09:45&tz=UTC&kind=meeting&status=confirmed&repeat=daily") |
| + }}, |
| + {"delete one occurrence", func() *httptest.ResponseRecorder { |
| + return f.post("/events/"+id(w.series.ID)+"/delete", "scope=this&occurrence=2027-01-07T09:00") |
| + }}, |
| + {"add reminder", func() *httptest.ResponseRecorder { |
| + return f.post("/events/"+id(w.single.ID)+"/reminders", "offset_min=60") |
| + }}, |
| + {"remove reminder", func() *httptest.ResponseRecorder { |
| + return f.post("/events/"+id(w.single.ID)+"/reminders/remove", "reminder_id="+id(w.reminder)) |
| + }}, |
| + {"mint feed", func() *httptest.ResponseRecorder { return f.post("/calendars/"+id(w.team)+"/feeds", "") }}, |
| + {"revoke feed", func() *httptest.ResponseRecorder { |
| + return f.post("/calendars/"+id(w.team)+"/feeds/revoke", "feed_id="+id(w.feed)) |
| + }}, |
| + {"import", func() *httptest.ResponseRecorder { return w.importICS() }}, |
| + {"settings", func() *httptest.ResponseRecorder { |
| + return f.post("/settings", "zone=Europe%2FDublin&week_start=7&default_reminder_min=30&default_all_day_min=0&handle=alice") |
| + }}, |
| + {"new booking page", func() *httptest.ResponseRecorder { |
| + return f.post("/settings/booking", "title=Two&availability=weekdays+9-5&duration_min=30") |
| + }}, |
| + {"edit booking page", func() *httptest.ResponseRecorder { |
| + return f.post("/settings/booking/1", "title=Chat+again&availability=every+day+9-5&duration_min=30") |
| + }}, |
| + {"native create", json("/api/native/events", `{"calendar_id":`+id(w.team)+`,"title":"Native","start_local":"2027-01-09T10:00","end_local":"2027-01-09T11:00","tz":"UTC"}`)}, |
| + {"native update", json("/api/native/events/"+id(w.single.ID), `{"title":"Native rename","start_local":"2027-01-05T10:00","end_local":"2027-01-05T11:00","tz":"UTC"}`)}, |
| + {"native quick", json("/api/native/quick", `{"calendar_id":`+id(w.team)+`,"title":"Native quick","start_local":"2027-01-10T10:00","end_local":"2027-01-10T11:00","tz":"UTC","repeat":"none"}`)}, |
| + {"booker holds", public(func() *httptest.ResponseRecorder { |
| + return f.post(w.path, "start="+w.slots[len(w.slots)-1]+"&zone=UTC&name=Sam&address=sam%40example.org¬e=hi") |
| + })}, |
| + {"booker confirms", public(func() *httptest.ResponseRecorder { return f.post("/book/m/"+w.heldToken+"/confirm", "") })}, |
| + {"booker reschedules", public(func() *httptest.ResponseRecorder { |
| + picker := f.get("/book/m/" + w.booked + "/reschedule?day=" + w.day + "&zone=UTC") |
| + rev := reWorldRev.FindStringSubmatch(picker.Body.String()) |
| + if rev == nil { |
| + return picker |
| + } |
| + return f.post("/book/m/"+w.booked+"/reschedule", "start="+w.slots[len(w.slots)-3]+"&zone=UTC&rev="+rev[1]) |
| + })}, |
| + // Last: they take what the routes above act on. |
| + {"unpublish", func() *httptest.ResponseRecorder { return f.post("/settings/booking/1/publish", "publish=0") }}, |
| + {"delete", func() *httptest.ResponseRecorder { return f.post("/events/"+id(w.single.ID)+"/delete", "") }}, |
| + } |
| +} |
| + |
| +func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) { |
| + w := newTeamWriteWorld(t) |
| + f := w.f |
| + defer func() { teamGuard = teammode.Guard }() |
| + for _, route := range w.routes() { |
| + f.refreshed() |
| + before := teamSnapshot(t, f) |
| + teamGuard = f.lapsingGuard |
| + got := route.do() |
| + teamGuard = teammode.Guard |
| + retryable(t, route.name+" through a lapse", got) |
| + if after := teamSnapshot(t, f); after != before { |
| + t.Fatalf("%s: a write refused at commit left something behind", route.name) |
| + } |
| + } |
| + // The success half: the same routes under the real guard, as a |
| + // member (not an owner), each change the database. |
| + for _, route := range w.routes() { |
| + f.refreshed() |
| + before := teamSnapshot(t, f) |
| + got := route.do() |
| + if got.Code >= 400 { |
| + t.Fatalf("%s as a member = %d %s", route.name, got.Code, got.Body.String()) |
| + } |
| + if teamSnapshot(t, f) == before { |
| + t.Fatalf("%s as a member changed nothing", route.name) |
| + } |
| + } |
| +} |
| + |
| +func TestTeamGuardRefusesWithoutStanding(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('x') |
| + p := f.member(subject, "member") |
| + team, _ := f.calendarsOf(p) |
| + in := EventInput{CalendarID: team, Title: "Nope", StartLocal: "2027-01-05T10:00", EndLocal: "2027-01-05T11:00", TZ: "UTC", Kind: KindMeeting, Status: StatusConfirmed} |
| + count := func() int64 { |
| + var n int64 |
| + f.app.db.G.Model(&Event{}).Count(&n) |
| + return n |
| + } |
| + // No Access at all: refused closed, in the store itself. |
| + err := f.app.store.guarded(context.Background(), func(db *gorm.DB) error { |
| + return db.Create(&Event{CalendarID: team, Kind: KindMeeting, Status: StatusConfirmed}).Error |
| + }) |
| + if !errors.Is(err, teammode.ErrUnavailable) || count() != 0 { |
| + t.Fatalf("a write with no standing = %v, %d events", err, count()) |
| + } |
| + // Unknown: the read finds nothing to write to. |
| + f.expired() |
| + if _, err := f.app.store.CreateEvent(f.withAccess(subject), p.ID, in); err == nil || count() != 0 { |
| + t.Fatalf("a write under Unknown = %v", err) |
| + } |
| + // A write whose own body lapses the lease rolls back (the guard's |
| + // after-check, independent of the test seam). |
| + f.refreshed() |
| + ctx := f.withAccess(subject) |
| + err = f.app.store.guarded(ctx, func(db *gorm.DB) error { |
| + if err := db.Create(&Event{CalendarID: team, Kind: KindMeeting, Status: StatusConfirmed}).Error; err != nil { |
| + return err |
| + } |
| + f.expired() |
| + return nil |
| + }) |
| + if !errors.Is(err, teammode.ErrUnavailable) || count() != 0 { |
| + t.Fatalf("a write that lapsed inside itself = %v, %d events", err, count()) |
| + } |
| + // A write that takes an id rather than reading through a grant |
| + // (attendees, after the event was made) is guarded all the same. |
| + f.refreshed() |
| + made := f.event(p, subject, team, "Attended", "2027-01-05T10:00", "2027-01-05T11:00") |
| + f.expired() |
| + if err := f.app.store.SetAttendees(f.withAccess(subject), made.ID, []string{"guest@example.org"}); !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("attendees under Unknown = %v", err) |
| + } |
| + var attendees int64 |
| + f.app.db.G.Model(&Attendee{}).Count(&attendees) |
| + if attendees != 0 { |
| + t.Fatal("attendees were written under Unknown") |
| + } |
| + withAddress := p // as a person with an address would be |
| + withAddress.Address = "someone@example.test" |
| + if err := f.app.store.EnsureDefaultReminder(f.withAccess(subject), withAddress, made); !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("a default reminder under Unknown = %v", err) |
| + } |
| + var reminders int64 |
| + f.app.db.G.Model(&Reminder{}).Count(&reminders) |
| + if reminders != 0 { |
| + t.Fatal("a default reminder was written under Unknown") |
| + } |
| + f.app.db.G.Exec("DELETE FROM events") |
| + // The instance's own work is not a person's write. |
| + f.refreshed() |
| + if err := f.app.store.guarded(systemWrite(f.withAccess(subject)), func(db *gorm.DB) error { |
| + f.expired() |
| + return db.Create(&Event{CalendarID: team, Kind: KindMeeting, Status: StatusConfirmed}).Error |
| + }); err != nil || count() != 1 { |
| + t.Fatalf("system work = %v, %d events", err, count()) |
| + } |
| + // Outside team mode: no guard, exactly as before. |
| + f.app.store.team = false |
| + defer func() { f.app.store.team = true }() |
| + if err := f.app.store.guarded(context.Background(), func(db *gorm.DB) error { |
| + return db.Create(&Event{CalendarID: team, Kind: KindMeeting, Status: StatusConfirmed}).Error |
| + }); err != nil || count() != 2 { |
| + t.Fatalf("team mode off = %v", err) |
| + } |
| + _ = url.Values{} |
| +} |
diff --git a/internal/calendar/team_home_only.go b/internal/calendar/team_home_only.go| new file mode 100644 |
| index 0000000..3cbc152 |
| --- /dev/null |
| +++ b/internal/calendar/team_home_only.go |
| @@ -0,0 +1,114 @@ |
| +package calendar |
| + |
| +// Home sign-in for a roster member with no account here: connect's two |
| +// team-mode hooks over Calendar's people table. connect completes an |
| +// ordinary Home sign-in only for a subject with an account link, and |
| +// refuses the rest as "unknown" — right for an allowlist instance, where |
| +// nobody may enter on a Home identity alone. In team mode a roster member |
| +// who has never had a local account must be able to, so newHome gives |
| +// connect these, and connect's own completion does the rest (its cookie |
| +// checks, the same-person rule, the link flow). |
| +// |
| +// The person Unlinked creates is identity, never standing: every request |
| +// after this one asks the roster again (team_access.go). |
| +// |
| +// A Home-only person has NO address, here or in Home (Home's design keeps |
| +// no address at rest for them). Their people row's address column holds a |
| +// random "home-only:" placeholder, because the column is NOT NULL and |
| +// UNIQUE and migrations are additive-only; nothing mails it or shows it. |
| +// What that costs them, said once here and in the spec (§team mode): |
| +// |
| +// - no email reminders: none is made by default, adding one is refused, |
| +// and the drain sends none (team_jobs.go); |
| +// - no published booking page: the booker's invitation names the host by |
| +// address, and the host's own booking mail has nowhere to go; |
| +// - no local sign-in: they sign in through Oficina only. |
| +// |
| +// Storing an address they type for reminders would be a new address |
| +// column in this app, which needs its own privacy review (Fable on |
| +// oficina/home #98); it is not in this branch. The options are Paul's. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/calendar/internal/calendar/teamstate" |
| +) |
| + |
| +// ErrNoAddress is a Home-only person asking for something that needs an |
| +// address: a reminder, or publishing a booking page. Team mode only. |
| +var ErrNoAddress = errors.New("calendar: this needs an email address, and this account has none here") |
| + |
| +// teamHomeOnly is connect's HomeOnly: the addressless person Unlinked gave |
| +// a subject, read and never created. |
| +func (a *App) teamHomeOnly(d *sql.DB) func(context.Context, string, string) (connect.Person, error) { |
| + return func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + id, err := teamstate.HomePerson(ctx, d, issuer, subject) |
| + switch { |
| + case err == nil: |
| + return connect.Person{ID: id}, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| +} |
| + |
| +// teamUnlinked is connect's Unlinked, asked only when nobody is signed in |
| +// and the subject has neither a link nor a Home-only person: an |
| +// addressless person for a subject the roster says is a Member now, with |
| +// the lease on that answer still valid (Runtime.AdmitUnlinked). A stranger |
| +// is connect's "unknown"; an undecidable roster is a 503. Their calendars |
| +// are made on their first page (teamRequirePerson), as a local person's |
| +// are. |
| +func (a *App) teamUnlinked(d *sql.DB) func(context.Context, string, string) (connect.Person, error) { |
| + return func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + if a.team == nil { |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + if err := a.team.AdmitUnlinked(ctx, issuer, subject); err != nil { |
| + if errors.Is(err, teammode.ErrNotMember) { |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + id, _, err := teamstate.EnsureHomePerson(ctx, d, issuer, subject, teamstate.Defaults{ |
| + Zone: defaultZone, WeekStart: WeekStartMonday, ReminderMin: DefaultReminderMin, AllDayMin: DefaultAllDayMin, |
| + }) |
| + switch { |
| + case err == nil: |
| + return connect.Person{ID: id}, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + // Linked to a local account in the meantime: that person |
| + // signs in as that account, not as a new one. |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| +} |
| + |
| +// refuseAddressless is ErrNoAddress for a Home-only person in team mode, |
| +// nil for everybody else and always nil outside team mode. |
| +func (s *Store) refuseAddressless(ctx context.Context, personID int64) error { |
| + if !s.team { |
| + return nil |
| + } |
| + var p Person |
| + if err := s.g.WithContext(ctx).Select("id", "address").First(&p, personID).Error; err != nil { |
| + return err |
| + } |
| + if teamstate.Addressless(p.Address) { |
| + return ErrNoAddress |
| + } |
| + return nil |
| +} |
| + |
| +// noAddress reports whether p is a Home-only person in team mode, for the |
| +// pages that say what that costs them. Always false outside team mode. |
| +func (h *handlers) noAddress(p Person) bool { |
| + return h.team != nil && p.homeOnly != "" |
| +} |
diff --git a/internal/calendar/team_identity_test.go b/internal/calendar/team_identity_test.go| new file mode 100644 |
| index 0000000..29ab7af |
| --- /dev/null |
| +++ b/internal/calendar/team_identity_test.go |
| @@ -0,0 +1,223 @@ |
| +package calendar |
| + |
| +import ( |
| + "amadan.net/oficina/calendar/internal/calendar/teamstate" |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestTeamUnlinkedLocalAccountIsSentToLink(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.localSession("alice@example.test") |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/account/home" { |
| + t.Fatalf("unlinked local view = %d %q, want /account/home", w.Code, w.Header().Get("Location")) |
| + } |
| + if w := f.get("/events/new"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/account/home" { |
| + t.Fatalf("unlinked local form = %d", w.Code) |
| + } |
| + var before int64 |
| + f.app.db.G.Model(&Event{}).Count(&before) |
| + if w := f.post("/events", "title=x"); w.Code != http.StatusNotFound { |
| + t.Fatalf("unlinked local POST = %d, want 404", w.Code) |
| + } |
| + if w := f.get("/account/home"); w.Code != http.StatusOK { |
| + t.Fatalf("unlinked local link page = %d", w.Code) |
| + } |
| + // Off the allowlist, a local session speaks for nobody: in team mode |
| + // the list is the local door, and only that. |
| + f.localSession("mallory@example.test") |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusNotFound { |
| + t.Fatalf("local session off the list = %d, want 404", w.Code) |
| + } |
| +} |
| + |
| +func TestTeamLinkedAccountStandsOnTheRosterNotTheAllowlist(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('b') |
| + alice := f.linkedAlice(subject, "member") |
| + team, _ := f.calendarsOf(alice) |
| + f.event(alice, subject, team, "Planning", "2026-11-02T10:00", "2026-11-02T11:00") |
| + // Locally signed in and linked: a member. |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Planning") { |
| + t.Fatalf("linked local member = %d", w.Code) |
| + } |
| + // Through Home, off the allowlist entirely: still the roster's member. |
| + delete(f.app.home.admitted.addrs, "alice@example.test") |
| + f.signInHome(subject) |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Planning") { |
| + t.Fatalf("linked member off the allowlist = %d", w.Code) |
| + } |
| + if !strings.Contains(f.get("/day/2026-11-02").Body.String(), `aria-label="Account: alice@example.test"`) { |
| + t.Fatal("a linked member is not named by their address") |
| + } |
| + // Off the roster: offboarded, allowlist or not. |
| + f.app.home.admitted.addrs["alice@example.test"] = struct{}{} |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("linked member off the roster = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + f.localSession("alice@example.test") |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("linked local session off the roster = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| +} |
| + |
| +func TestTeamStorageFailureIsNeverASignOut(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('f'), "member") |
| + if _, err := f.app.db.G.DB(); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The Home-only table unreadable: identity cannot be read now. |
| + if err := f.app.db.G.Exec("ALTER TABLE calendar_team_home_people RENAME TO calendar_team_home_people_away").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + retryable(t, "identity storage down", f.get("/day/2026-11-02")) |
| + if f.cookies[f.app.home.sessions.CookieName()] == nil { |
| + t.Fatal("a storage failure signed the member out") |
| + } |
| + if err := f.app.db.G.Exec("ALTER TABLE calendar_team_home_people_away RENAME TO calendar_team_home_people").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := f.get("/day/2026-11-02"); w.Code != http.StatusOK { |
| + t.Fatalf("after storage returned = %d", w.Code) |
| + } |
| +} |
| + |
| +func TestTeamHomeOnlyRowsNeverGainAnAddress(t *testing.T) { |
| + f := newTeamFixture(t) |
| + p := f.member(teamSubject('g'), "member") |
| + if err := f.app.db.G.Exec("UPDATE people SET address = 'g@example.test' WHERE id = ?", p.ID).Error; err == nil { |
| + t.Fatal("a Home-only person was given an address") |
| + } |
| + // Held by the trigger, not only by the foreign key: with keys off |
| + // (an import tool, a hand repair), the row still stays. |
| + if err := f.app.db.G.Exec("PRAGMA foreign_keys = OFF").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.db.G.Exec("DELETE FROM people WHERE id = ?", p.ID).Error; err == nil { |
| + t.Fatal("a Home-only person was deleted") |
| + } |
| + if err := f.app.db.G.Exec("PRAGMA foreign_keys = ON").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.db.G.Exec("DELETE FROM calendar_team_home_people").Error; err == nil { |
| + t.Fatal("a Home-only row was deleted") |
| + } |
| + if err := f.app.db.G.Exec("UPDATE calendar_team_home_people SET subject = 'x'").Error; err == nil { |
| + t.Fatal("a Home-only row was moved") |
| + } |
| + // A row for a person who has an address is refused. |
| + local, err := f.app.store.EnsurePerson(context.Background(), "carol@example.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.db.G.Exec("INSERT INTO calendar_team_home_people(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('h'), local.ID).Error; err == nil { |
| + t.Fatal("a person with an address was made Home-only") |
| + } |
| + // A link to a Home-only person or subject is refused. |
| + if err := f.app.db.G.Exec("INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('g'), local.ID).Error; err == nil { |
| + t.Fatal("a Home-only subject was linked") |
| + } |
| + // A Home-only row for a subject already linked to an account is |
| + // refused: that subject is that account. |
| + linked := f.linkedAlice(teamSubject('j'), "member") |
| + _ = linked |
| + if err := f.app.db.G.Exec(`INSERT INTO people(address,zone,created_at,updated_at,week_start,default_reminder_min,default_all_day_min) VALUES('home-only:spare','UTC',0,0,1,0,0)`).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + var spare int64 |
| + f.app.db.G.Raw("SELECT id FROM people WHERE address = 'home-only:spare'").Scan(&spare) |
| + if err := f.app.db.G.Exec("INSERT INTO calendar_team_home_people(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('j'), spare).Error; err == nil { |
| + t.Fatal("a linked subject was made Home-only") |
| + } |
| + // Settings still save: only the address is frozen. |
| + if err := f.app.db.G.Exec("UPDATE people SET zone = 'Europe/Dublin' WHERE id = ?", p.ID).Error; err != nil { |
| + t.Fatalf("a Home-only person's zone: %v", err) |
| + } |
| +} |
| + |
| +// /signin with a session that speaks for nobody here ends it and starts |
| +// over, as it always has; it never shortcuts it to a page that 404s. |
| +func TestTeamSigninEndsASessionForNobody(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.localSession("mallory@example.test") |
| + w := f.get("/signin") |
| + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin" { |
| + t.Fatalf("/signin for nobody = %d %q, want a restart", w.Code, w.Header().Get("Location")) |
| + } |
| + if f.cookies[f.app.home.sessions.CookieName()] != nil { |
| + t.Fatal("/signin kept a session that speaks for nobody") |
| + } |
| +} |
| + |
| +// Off team mode nothing sends err=removed, and if it arrives it reads as |
| +// any other err did: the team sentence is team mode's alone. |
| +func TestTeamRemovedSentenceIsTeamModesAlone(t *testing.T) { |
| + a := NewForTest(t, t.TempDir()) |
| + w := httptest.NewRecorder() |
| + a.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/signin?err=removed", nil)) |
| + if strings.Contains(w.Body.String(), "no longer on this team") || !strings.Contains(w.Body.String(), "That link did not work") { |
| + t.Fatal("team mode off drew the team's removed sentence") |
| + } |
| +} |
| + |
| +// teamstate's own refusals, asked directly: a subject linked to a local |
| +// account is that account and never gets a Home-only person (connect asks |
| +// Unlinked only for an unlinked subject, but a link can land in between), |
| +// and nothing shaped like an address is ever a subject. |
| +func TestTeamHomeOnlyAllocationRefusesLinksAndAddresses(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('l') |
| + f.linkedAlice(subject, "member") |
| + people := func() int64 { |
| + var n int64 |
| + f.app.db.G.Model(&Person{}).Count(&n) |
| + return n |
| + } |
| + before := people() |
| + defaults := teamstate.Defaults{Zone: "UTC", WeekStart: 1} |
| + if _, _, err := teamstate.EnsureHomePerson(context.Background(), f.app.team.db, homeTestIssuer, subject, defaults); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatalf("a linked subject = %v, want refused", err) |
| + } |
| + for _, s := range []string{"a@b.example", "pr_x@y", ""} { |
| + if _, _, err := teamstate.EnsureHomePerson(context.Background(), f.app.team.db, homeTestIssuer, s, defaults); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatalf("subject %q = %v, want refused", s, err) |
| + } |
| + if _, err := teamstate.HomePerson(context.Background(), f.app.team.db, homeTestIssuer, s); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatalf("lookup of %q = %v, want refused", s, err) |
| + } |
| + } |
| + if people() != before { |
| + t.Fatal("a refused allocation made a person") |
| + } |
| +} |
| + |
| +// Every scoped read joins through grantJoin, which withholds the team |
| +// rung without Member standing (team_reach.go). A raw grant join written |
| +// anywhere else would reach the team calendar on no standing at all. |
| +func TestTeamEveryGrantJoinIsTheRungs(t *testing.T) { |
| + files, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, name := range files { |
| + if strings.HasSuffix(name, "_test.go") || name == "team_reach.go" { |
| + continue |
| + } |
| + src, err := os.ReadFile(name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(strings.ToUpper(string(src)), "JOIN GRANTS") { |
| + t.Fatalf("%s joins grants itself; use grantJoin", name) |
| + } |
| + } |
| +} |
diff --git a/internal/calendar/team_jobs.go b/internal/calendar/team_jobs.go| new file mode 100644 |
| index 0000000..a7e18ed |
| --- /dev/null |
| +++ b/internal/calendar/team_jobs.go |
| @@ -0,0 +1,130 @@ |
| +package calendar |
| + |
| +// Team mode's scheduled work. The drain acts as the system: it is not a |
| +// person's request and holds nobody's lease, as Memoria's connector runs |
| +// do (oficina/memoria #32, deviation 3). Its bookkeeping writes — claims, |
| +// deferrals, fires, hold expiry — are the instance's own and unguarded. |
| +// |
| +// What it DELIVERS to a person is decided on that person's standing, |
| +// asked when it is about to go, so a job acting on a removed member's |
| +// events leaks nothing to them: |
| +// |
| +// - a reminder is sent only to a recipient the roster says is a Member |
| +// now, who still reaches the event on that standing, and who has an |
| +// address. NotMember, no reach, or a Home-only recipient settles that |
| +// occurrence unsent and queues the next, which is decided the same way |
| +// when it comes due (re-added, they are reminded again). Unknown defers |
| +// it, unsent and unattempted, by standingRetry. |
| +// - a booking's HOST mail goes only to a host who is a Member with an |
| +// address; NotMember or addressless retires it unsent, Unknown defers |
| +// it. The booker's own mail is theirs (they typed the address to be |
| +// mailed, B5) and is unchanged. |
| +// |
| +// Outside team mode every decision here is deliverNow and the drain is |
| +// what it always was. |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/calendar/internal/calendar/teamstate" |
| +) |
| + |
| +// delivery is what the drain may do with one item owed to a person. |
| +type delivery int |
| + |
| +const ( |
| + deliverNow delivery = iota |
| + // deliverLater: standing cannot be read now. Nothing is sent and |
| + // nothing is decided against the person. |
| + deliverLater |
| + // deliverNever: definitely not to them — off the team, out of reach, |
| + // or no address. |
| + deliverNever |
| +) |
| + |
| +// standingRetry is how long a reminder waits when its recipient's |
| +// standing cannot be read. Longer than the sender's own deferral: every |
| +// wake costs a quarter hour of residency (AGENTS.md §Ticks), and a Home |
| +// outage should not keep the instance awake polling it every thirty |
| +// seconds. A reminder that arrives late says so. |
| +const standingRetry = 5 * time.Minute |
| + |
| +// reminderDelivery decides one claimed reminder on its recipient's |
| +// standing. Standing is read before reach and again after it (the |
| +// stream-order lesson): a lease that lapsed in between is a deferral. |
| +func (h *handlers) reminderDelivery(ctx context.Context, due DueReminder) delivery { |
| + if h.team == nil { |
| + return deliverNow |
| + } |
| + if teamstate.Addressless(due.Address) { |
| + return deliverNever |
| + } |
| + acc := h.standingFor(ctx, due.PersonID) |
| + switch acc.State() { |
| + case roster.NotMember: |
| + return deliverNever |
| + case roster.Unknown: |
| + return deliverLater |
| + } |
| + _, err := h.store.Event(teammode.WithAccess(ctx, acc), due.PersonID, due.EventID) |
| + if acc.State() != roster.Member { |
| + return deliverLater |
| + } |
| + switch { |
| + case NotFound(err): |
| + return deliverNever |
| + case err != nil: |
| + return deliverLater |
| + } |
| + return deliverNow |
| +} |
| + |
| +// settleWithoutSending applies reminderDelivery: true when the reminder |
| +// was settled (deferred or retired) without a send, false when it should |
| +// be sent. A bookkeeping failure is the drain's error, as any other is. |
| +func (h *handlers) settleWithoutSending(ctx context.Context, due DueReminder, now time.Time) (bool, error) { |
| + switch h.reminderDelivery(ctx, due) { |
| + case deliverLater: |
| + _, err := h.store.deferReminderFor(keep(ctx), due.Queue.ID, due.ClaimID, now.Unix(), standingRetry) |
| + return true, err |
| + case deliverNever: |
| + // This occurrence is settled, unsent; the next is queued and |
| + // decided on its own day. |
| + return true, h.store.CompleteReminder(keep(ctx), due, now.Unix()) |
| + } |
| + return false, nil |
| +} |
| + |
| +// hostMail decides a booking's host mail on the host's standing. |
| +func (h *handlers) hostMail(ctx context.Context, host Person) delivery { |
| + if h.team == nil { |
| + return deliverNow |
| + } |
| + if teamstate.Addressless(host.Address) { |
| + return deliverNever |
| + } |
| + switch h.standingFor(ctx, host.ID).State() { |
| + case roster.Member: |
| + return deliverNow |
| + case roster.NotMember: |
| + return deliverNever |
| + } |
| + return deliverLater |
| +} |
| + |
| +// deferReminderFor is DeferReminder by wait, for a deferral that is not |
| +// the sender's (team mode's unknown standing: team_jobs.go). |
| +func (s *Store) deferReminderFor(ctx context.Context, queueID int64, claimID string, now int64, wait time.Duration) (ok bool, err error) { |
| + res := s.g.WithContext(ctx).Model(&ReminderQueue{}). |
| + Where("id = ? AND claim_id = ?", queueID, claimID). |
| + Updates(map[string]any{"retry_at": now + int64(wait.Seconds()), "claimed_at": nil, "claim_id": nil}) |
| + if res.Error != nil { |
| + return false, fmt.Errorf("calendar: defer reminder: %w", res.Error) |
| + } |
| + return res.RowsAffected == 1, nil |
| +} |
diff --git a/internal/calendar/team_jobs_test.go b/internal/calendar/team_jobs_test.go| new file mode 100644 |
| index 0000000..9faf21f |
| --- /dev/null |
| +++ b/internal/calendar/team_jobs_test.go |
| @@ -0,0 +1,268 @@ |
| +package calendar |
| + |
| +import ( |
| + "amadan.net/oficina/home/roster" |
| + "context" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// teamMailbox records every message's recipient and subject, so a test |
| +// can say who was mailed what — not only the last body. |
| +type teamMailbox struct { |
| + mu sync.Mutex |
| + sent []string |
| +} |
| + |
| +func (m *teamMailbox) Send(_ context.Context, to, subject, _ string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.sent = append(m.sent, to+" | "+subject) |
| + return nil |
| +} |
| + |
| +func (m *teamMailbox) to(who string) []string { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + var out []string |
| + for _, s := range m.sent { |
| + if strings.HasPrefix(s, who+" | ") { |
| + out = append(out, s) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// mailbox swaps the fixture's mailer for a teamMailbox, behind the same |
| +// bounded sender every send goes through. |
| +func (f *teamFixture) mailbox() *teamMailbox { |
| + box := &teamMailbox{} |
| + f.app.h.mailer = newBoundedSender(box) |
| + return box |
| +} |
| + |
| +// soon is a start a few minutes from now, as a local UTC string, so a |
| +// reminder ten minutes before it is due now. |
| +func soon(minutes int) (string, string) { |
| + t := time.Now().UTC().Add(time.Duration(minutes) * time.Minute) |
| + return t.Format("2006-01-02T15:04"), t.Add(30 * time.Minute).Format("2006-01-02T15:04") |
| +} |
| + |
| +func TestTeamRemindersGoOnlyToMembersWhoReachTheEvent(t *testing.T) { |
| + f := newTeamFixture(t) |
| + box := f.mailbox() |
| + subject := teamSubject('m') |
| + alice := f.linkedAlice(subject, "member") |
| + team, _ := f.calendarsOf(alice) |
| + remind := func(title string) Event { |
| + t.Helper() |
| + start, end := soon(5) |
| + e := f.event(alice, subject, team, title, start, end) |
| + if err := f.app.store.AddReminder(f.withAccess(subject), alice.ID, e.ID, 10); err != nil { |
| + t.Fatal(err) |
| + } |
| + return e |
| + } |
| + drain := func(now time.Time) int { |
| + t.Helper() |
| + sent, _, err := f.app.h.drain(context.Background(), now) |
| + if err != nil { |
| + t.Fatalf("drain: %v", err) |
| + } |
| + return sent |
| + } |
| + mailed := func(title string) bool { |
| + for _, s := range box.to("alice@example.test") { |
| + if strings.Contains(s, title) { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| + |
| + // A member: reminded. |
| + remind("Member reminder") |
| + if drain(time.Now()) != 1 || !mailed("Member reminder") { |
| + t.Fatal("a member was not reminded") |
| + } |
| + |
| + // Removed: nothing sent, and the occurrence is settled rather than |
| + // left due. |
| + removed := remind("Removed reminder") |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| + if drain(time.Now()) != 0 || mailed("Removed reminder") { |
| + t.Fatal("a removed member was reminded") |
| + } |
| + var due int64 |
| + f.app.db.G.Model(&ReminderQueue{}).Joins("JOIN reminders ON reminders.id = reminder_queues.reminder_id"). |
| + Where("reminders.event_id = ? AND reminder_queues.fired_at IS NULL AND reminder_queues.due_at <= ?", removed.ID, time.Now().Unix()).Count(&due) |
| + if due != 0 { |
| + t.Fatal("a removed member's reminder was left due") |
| + } |
| + |
| + // Unknown: deferred, unsent and unattempted, then sent once standing |
| + // returns. |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + held := remind("Held reminder") |
| + f.expired() |
| + if drain(time.Now()) != 0 || mailed("Held reminder") { |
| + t.Fatal("a reminder was sent while standing was unknown") |
| + } |
| + var q ReminderQueue |
| + f.app.db.G.Joins("JOIN reminders ON reminders.id = reminder_queues.reminder_id").Where("reminders.event_id = ?", held.ID).First(&q) |
| + if q.FiredAt != nil || q.RetryAt == nil || q.Attempts != 0 { |
| + t.Fatalf("an unknown recipient's reminder = fired %v retry %v attempts %d, want deferred", q.FiredAt, q.RetryAt, q.Attempts) |
| + } |
| + // By standingRetry, not the sender's thirty seconds: a Home outage |
| + // must not keep the instance awake polling it (AGENTS.md §Ticks). |
| + if wait := *q.RetryAt - time.Now().Unix(); wait < int64((standingRetry - 10*time.Second).Seconds()) { |
| + t.Fatalf("an unknown recipient's reminder retries in %ds, want about %s", wait, standingRetry) |
| + } |
| + f.refreshed() |
| + if drain(time.Now().Add(standingRetry+time.Second)) != 1 || !mailed("Held reminder") { |
| + t.Fatal("a deferred reminder was not sent once standing returned") |
| + } |
| + |
| + // The opportunistic drain a page view runs decides the same way, on |
| + // the RECIPIENT's standing, not the viewer's. |
| + viewer := teamSubject('v') |
| + f.member(viewer, "member") |
| + remind("Viewer's drain") |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| + f.signInHome(viewer) |
| + f.get("/day/2026-11-02") |
| + if mailed("Viewer's drain") { |
| + t.Fatal("a page view's drain reminded a removed member") |
| + } |
| +} |
| + |
| +func TestTeamHomeOnlyMembersGetNoRemindersAndPublishNoPage(t *testing.T) { |
| + f := newTeamFixture(t) |
| + box := f.mailbox() |
| + p := f.member(teamSubject('h'), "member") |
| + team, _ := f.calendarsOf(p) |
| + start, end := soon(5) |
| + w := f.post("/events", "calendar_id="+itoa(team)+"&title=Home+only&start="+url.QueryEscape(start)+"&end="+url.QueryEscape(end)+"&tz=UTC&kind=meeting&status=confirmed") |
| + if w.Code != http.StatusSeeOther { |
| + t.Fatalf("create = %d", w.Code) |
| + } |
| + reminders := func() int64 { |
| + var n int64 |
| + f.app.db.G.Model(&Reminder{}).Where("person_id = ?", p.ID).Count(&n) |
| + return n |
| + } |
| + if reminders() != 0 { |
| + t.Fatal("a Home-only member got a default reminder") |
| + } |
| + var e Event |
| + f.app.db.G.Where("calendar_id = ?", team).Last(&e) |
| + if w := f.post("/events/"+itoa(e.ID)+"/reminders", "offset_min=10"); w.Code != http.StatusSeeOther || reminders() != 0 { |
| + t.Fatalf("adding a reminder = %d, %d reminders", w.Code, reminders()) |
| + } |
| + page := f.get("/events/" + itoa(e.ID)).Body.String() |
| + if !strings.Contains(page, "data-no-address") || strings.Contains(page, "cal-reminder-add") { |
| + t.Fatal("the event page offers a Home-only member a reminder") |
| + } |
| + if !strings.Contains(f.get("/settings").Body.String(), "No email from this calendar") { |
| + t.Fatal("settings do not say what a Home-only member lacks") |
| + } |
| + // A reminder row made behind the app's back is still never mailed. |
| + if err := f.app.db.G.Create(&Reminder{EventID: e.ID, PersonID: p.ID, OffsetMin: 10, Channel: "email", CreatedAt: time.Now()}).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + var rem Reminder |
| + f.app.db.G.Where("person_id = ?", p.ID).First(&rem) |
| + if err := f.app.store.RescheduleReminder(context.Background(), rem.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if sent, _, err := f.app.h.drain(context.Background(), time.Now()); err != nil || sent != 0 { |
| + t.Fatalf("drain for a Home-only member = %d %v", sent, err) |
| + } |
| + if len(box.sent) != 0 { |
| + t.Fatalf("mail went out: %v", box.sent) |
| + } |
| + // Booking: a page may be drafted, never published. |
| + mustRedirect(t, "handle", f.post("/settings", "zone=UTC&week_start=1&default_reminder_min=0&default_all_day_min=0&handle=homeonly")) |
| + mustRedirect(t, "draft", f.post("/settings/booking", "title=Chat&availability=every+day+9-5&duration_min=30")) |
| + if w := f.post("/settings/booking/1/publish", "publish=1"); w.Code != http.StatusUnprocessableEntity || !strings.Contains(w.Body.String(), "Booking pages need an email address") { |
| + t.Fatalf("publish by a Home-only member = %d", w.Code) |
| + } |
| + var published int64 |
| + f.app.db.G.Model(&BookingPage{}).Where("published_at IS NOT NULL").Count(&published) |
| + if published != 0 { |
| + t.Fatal("a Home-only member published a booking page") |
| + } |
| + if strings.Contains(f.get("/settings/booking").Body.String(), "home-only:") { |
| + t.Fatal("the placeholder was shown") |
| + } |
| +} |
| + |
| +// A reminder decided at the lease's edge is sent or deferred, never |
| +// settled unsent: a lapse between reading standing and reading reach is |
| +// "cannot tell", not "out of reach". |
| +func TestTeamReminderDecisionAtTheLeaseEdgeNeverSettles(t *testing.T) { |
| + subject := teamSubject('k') |
| + seen := map[delivery]bool{} |
| + for k := 1; k <= 40; k++ { |
| + f := newTeamFixture(t) |
| + alice := f.linkedAlice(subject, "member") |
| + team, _ := f.calendarsOf(alice) |
| + e := f.event(alice, subject, team, "Edge", "2026-11-02T10:00", "2026-11-02T11:00") |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + got := f.app.h.reminderDelivery(context.Background(), DueReminder{PersonID: alice.ID, EventID: e.ID, Address: alice.Address}) |
| + if got == deliverNever { |
| + t.Fatalf("k=%d: a member's reminder was settled unsent at the lease's edge", k) |
| + } |
| + seen[got] = true |
| + } |
| + if !seen[deliverNow] || !seen[deliverLater] { |
| + t.Fatalf("the sweep saw %v, want both sent and deferred", seen) |
| + } |
| +} |
| + |
| +// A host with no address is never mailed, member or not. |
| +func TestTeamHostMailNeedsAnAddress(t *testing.T) { |
| + f := newTeamFixture(t) |
| + p := f.member(teamSubject('o'), "member") |
| + if got := f.app.h.hostMail(context.Background(), p); got != deliverNever { |
| + t.Fatalf("host mail to a Home-only member = %v, want never", got) |
| + } |
| + alice := f.linkedAlice(teamSubject('q'), "member") |
| + if got := f.app.h.hostMail(context.Background(), alice); got != deliverNow { |
| + t.Fatalf("host mail to a member with an address = %v, want now", got) |
| + } |
| +} |
| + |
| +// A member is reminded only of what they still reach: a reminder on an |
| +// event whose calendar they no longer hold a grant on is settled unsent. |
| +func TestTeamReminderNeedsReach(t *testing.T) { |
| + f := newTeamFixture(t) |
| + box := f.mailbox() |
| + subject := teamSubject('n') |
| + alice := f.linkedAlice(subject, "member") |
| + team, _ := f.calendarsOf(alice) |
| + start, end := soon(5) |
| + e := f.event(alice, subject, team, "Out of reach", start, end) |
| + if err := f.app.store.AddReminder(f.withAccess(subject), alice.ID, e.ID, 10); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.db.G.Exec("DELETE FROM grants WHERE person_id = ? AND calendar_id = ?", alice.ID, team).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if sent, _, err := f.app.h.drain(context.Background(), time.Now()); err != nil || sent != 0 || len(box.sent) != 0 { |
| + t.Fatalf("a reminder out of reach = %d sent %v, %v", sent, box.sent, err) |
| + } |
| + var q ReminderQueue |
| + if f.app.db.G.Joins("JOIN reminders ON reminders.id = reminder_queues.reminder_id").Where("reminders.event_id = ? AND fired_at IS NULL AND due_at <= ?", e.ID, time.Now().Unix()).First(&q).Error == nil { |
| + t.Fatal("a reminder out of reach was left due") |
| + } |
| +} |
diff --git a/internal/calendar/team_reach.go b/internal/calendar/team_reach.go| new file mode 100644 |
| index 0000000..f7187ee |
| --- /dev/null |
| +++ b/internal/calendar/team_reach.go |
| @@ -0,0 +1,51 @@ |
| +package calendar |
| + |
| +// Team mode's reach: which grants a scoped read may join through. |
| +// |
| +// Calendar has no shares. Every grant is made by EnsurePersonSetup for the |
| +// person themselves — editor on the team calendar, owner of their own — |
| +// so every grant is the team rung, and in team mode counts only while the |
| +// roster says Member (Docs' owner rule, Sheets' "self-grants count only |
| +// while Member"). Somebody whose standing is anything else reaches |
| +// nothing: NotMember is signed out before any read (team_access.go), and |
| +// under Unknown a view is the empty partial list with its notice. |
| +// |
| +// The standing is read from the context, once, BEFORE the query is built |
| +// (Sheets' stream-order lesson, oficina/slides #33 and oficina/sheets |
| +// #54): a read never decides reach and then asks standing. A view asks |
| +// Partial again after it is built, of the same Access, because State |
| +// latches (requestUnknown). |
| +// |
| +// Outside team mode reaches is always true and every join is exactly the |
| +// one it has always been. |
| + |
| +import ( |
| + "context" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// reaches reports whether a read on ctx may join through the team rung: |
| +// always outside team mode, and inside it only while the Access ctx |
| +// carries says Member. A context with none (a path that forgot to carry |
| +// one) reaches nothing: the closed answer is the one that cannot leak. |
| +func (s *Store) reaches(ctx context.Context) bool { |
| + if !s.team { |
| + return true |
| + } |
| + return teammode.Standing(ctx) == roster.Member |
| +} |
| + |
| +// grantJoin is the join every scoped read goes through: the viewer's grant |
| +// on the calendar named by on, decided by rung (reaches, asked once per |
| +// read). A read that does not reach keeps the join and matches nothing, |
| +// so its shape — and every caller's handling of "not found" — is the |
| +// same. |
| +func grantJoin(on string, rung bool) string { |
| + join := "JOIN grants ON grants.calendar_id = " + on + " AND grants.person_id = ?" |
| + if !rung { |
| + join += " AND 0" |
| + } |
| + return join |
| +} |
diff --git a/internal/calendar/team_standing.go b/internal/calendar/team_standing.go| new file mode 100644 |
| index 0000000..9eae161 |
| --- /dev/null |
| +++ b/internal/calendar/team_standing.go |
| @@ -0,0 +1,105 @@ |
| +package calendar |
| + |
| +// Team mode's route gates, the roster's answer about somebody other than |
| +// the request's own person, and how a Home-only person is named. Split |
| +// from team_access.go so neither passes the 300-line cap. |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// standingNeed is what a route needs of the roster. |
| +type standingNeed int |
| + |
| +const ( |
| + // needMember: Member. Unknown is a retryable 503. Every item page, |
| + // every form, every write and the native API. |
| + needMember standingNeed = iota |
| + // needListing: a view (day, week, month, agenda, the calendar list). |
| + // Unknown renders it partial, with the notice; the page asks again |
| + // after building it (requestUnknown). |
| + needListing |
| +) |
| + |
| +// standing is the session group's gate, after requirePerson. Outside team |
| +// mode it is no gate at all: next, unchanged. |
| +func (a *App) standing(need standingNeed) func(http.Handler) http.Handler { |
| + return func(next http.Handler) http.Handler { |
| + if a.teamOn == nil { |
| + return next |
| + } |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + p, ok := teamPersonFrom(r.Context()) |
| + if !ok { |
| + // requirePerson puts the person on every request that |
| + // reaches here; a route outside it is a wiring bug, and |
| + // the closed answer is the one that cannot leak. |
| + a.h.teamUnavailable(w, r) |
| + return |
| + } |
| + switch p.access.State() { |
| + case roster.Member: |
| + case roster.NotMember: |
| + // Only an unlinked local account gets this far |
| + // (teamRequirePerson): it has no standing until it links. |
| + if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| + w.Header().Set("Cache-Control", "no-store") |
| + http.Redirect(w, r, "/account/home", http.StatusSeeOther) |
| + return |
| + } |
| + a.h.errorPage(w, r, http.StatusNotFound, "") |
| + return |
| + default: |
| + if need != needListing { |
| + a.h.teamUnavailable(w, r) |
| + return |
| + } |
| + } |
| + next.ServeHTTP(w, r) |
| + }) |
| + } |
| +} |
| + |
| +// standingOf builds the roster's answer about somebody other than the |
| +// request's own person — a feed's minter, a booking page's host, a |
| +// reminder's recipient — so what it says about them is what their own |
| +// requests would be told. Nil outside team mode. A person the roster |
| +// cannot be asked about (no link, no Home-only row) is NotMember; one |
| +// whose subject cannot be read now is Unknown (a nil Access). |
| +func (a *App) standingOf(ctx context.Context, person int64) *teammode.Access { |
| + if a.team == nil { |
| + return nil |
| + } |
| + subject, err := a.homeSubjectOf(ctx, person) |
| + if err != nil { |
| + return nil |
| + } |
| + return a.team.Access(ctx, subject) |
| +} |
| + |
| +// teamLabel is how a Home-only person, who has no address, is shown where |
| +// an address would be: the account menu. |
| +const teamLabel = "Oficina account" |
| + |
| +// homeOnlyLabel is teamLabel and the last four characters of the person |
| +// ref ("Oficina account …k7qz"), as Home's Team page shows a ref. |
| +func homeOnlyLabel(subject string) string { |
| + if len(subject) <= 4 { |
| + return teamLabel |
| + } |
| + return teamLabel + " …" + subject[len(subject)-4:] |
| +} |
| + |
| +// shownAddress is how a person is named where an address would be: their |
| +// address, or for a Home-only person, who has none, the Home-only label. |
| +// Outside team mode it is exactly Address. |
| +func (p Person) shownAddress() string { |
| + if p.homeOnly != "" { |
| + return homeOnlyLabel(p.homeOnly) |
| + } |
| + return p.Address |
| +} |
diff --git a/internal/calendar/team_world_test.go b/internal/calendar/team_world_test.go| new file mode 100644 |
| index 0000000..59aaa80 |
| --- /dev/null |
| +++ b/internal/calendar/team_world_test.go |
| @@ -0,0 +1,134 @@ |
| +package calendar |
| + |
| +import ( |
| + "bytes" |
| + "fmt" |
| + "mime/multipart" |
| + "net/http" |
| + "net/http/httptest" |
| + "regexp" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// teamWriteWorld is a member with something on every write route to act |
| +// on: alice, linked and on the roster, with a handle, a published booking |
| +// page, a single event with a reminder and attendees, a daily series, a |
| +// feed, and a stranger's held booking and confirmed booking on her page. |
| +type teamWriteWorld struct { |
| + f *teamFixture |
| + alice Person |
| + team int64 |
| + single, series Event |
| + reminder int64 |
| + feed int64 |
| + path string // the public booking page |
| + day string // a future day with free slots |
| + slots []string |
| + heldToken, booked string // manage tokens |
| +} |
| + |
| +var ( |
| + reWorldManage = regexp.MustCompile(`/book/m/([0-9a-f]{64})`) |
| + reWorldStart = regexp.MustCompile(`name="start" value="(\d+)"`) |
| + reWorldDay = regexp.MustCompile(`\?day=(\d{4}-\d{2}-\d{2})`) |
| + reWorldRev = regexp.MustCompile(`name="rev" value="(\d+)"`) |
| + reWorldPage = regexp.MustCompile(`/book/alice/[a-z0-9]{8}`) |
| +) |
| + |
| +func newTeamWriteWorld(t *testing.T) *teamWriteWorld { |
| + t.Helper() |
| + f := newTeamFixture(t) |
| + w := &teamWriteWorld{f: f} |
| + subject := teamSubject('w') |
| + w.alice = f.linkedAlice(subject, "member") |
| + w.team, _ = f.calendarsOf(w.alice) |
| + mustRedirect(t, "settings", f.post("/settings", "zone=UTC&week_start=1&default_reminder_min=10&default_all_day_min=0&handle=alice")) |
| + mustRedirect(t, "page", f.post("/settings/booking", "title=Chat&description=Half+an+hour&availability=every+day+9-5&duration_min=30&buffer_min=0¬ice_min=0&horizon_days=30")) |
| + mustRedirect(t, "publish", f.post("/settings/booking/1/publish", "publish=1")) |
| + w.path = reWorldPage.FindString(f.get("/settings/booking").Body.String()) |
| + if w.path == "" { |
| + t.Fatal("no public booking URL") |
| + } |
| + ctx := f.withAccess(subject) |
| + var err error |
| + w.single, err = f.app.store.CreateEvent(ctx, w.alice.ID, EventInput{CalendarID: w.team, Title: "Single", StartLocal: "2027-01-05T10:00", EndLocal: "2027-01-05T11:00", TZ: "UTC", Kind: KindMeeting, Status: StatusConfirmed}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w.series, err = f.app.store.CreateEvent(ctx, w.alice.ID, EventInput{CalendarID: w.team, Title: "Daily", StartLocal: "2027-01-04T09:00", EndLocal: "2027-01-04T09:15", TZ: "UTC", Kind: KindMeeting, Status: StatusConfirmed, RRule: "FREQ=DAILY"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.store.AddReminder(ctx, w.alice.ID, w.single.ID, 15); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.app.db.G.Model(&Reminder{}).Where("event_id = ?", w.single.ID).Pluck("id", &w.reminder) |
| + if _, err := f.app.store.MintFeed(ctx, w.alice.ID, w.team); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.app.db.G.Model(&Feed{}).Pluck("id", &w.feed) |
| + // A stranger's two bookings: one held, one confirmed. |
| + jar := f.cookies |
| + f.cookies = map[string]*http.Cookie{} |
| + page := f.get(w.path) |
| + today := time.Now().UTC().Format("2006-01-02") |
| + day := "" |
| + for _, m := range reWorldDay.FindAllStringSubmatch(page.Body.String(), -1) { |
| + if m[1] > today { |
| + day = m[1] |
| + break |
| + } |
| + } |
| + w.day = day |
| + for _, m := range reWorldStart.FindAllStringSubmatch(f.get(w.path+"?day="+day+"&zone=UTC").Body.String(), -1) { |
| + w.slots = append(w.slots, m[1]) |
| + } |
| + if len(w.slots) < 6 { |
| + t.Fatalf("only %d slots", len(w.slots)) |
| + } |
| + hold := func(start string) string { |
| + if r := f.post(w.path, "start="+start+"&zone=UTC&name=Jo&address=jo%40example.org¬e=hi"); r.Code != http.StatusOK { |
| + t.Fatalf("hold = %d", r.Code) |
| + } |
| + f.app.signinMail.wait() |
| + m := reWorldManage.FindStringSubmatch(f.app.mailRecorder.last()) |
| + if m == nil { |
| + t.Fatal("no manage link mailed") |
| + } |
| + return m[1] |
| + } |
| + w.booked = hold(w.slots[0]) |
| + if r := f.post("/book/m/"+w.booked+"/confirm", ""); r.Code != http.StatusOK { |
| + t.Fatalf("confirm = %d", r.Code) |
| + } |
| + w.heldToken = hold(w.slots[1]) |
| + f.cookies = jar |
| + return w |
| +} |
| + |
| +func mustRedirect(t *testing.T, what string, w *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if w.Code != http.StatusSeeOther { |
| + t.Fatalf("%s = %d %s", what, w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +// importICS posts a one-event .ics file to the team calendar. |
| +func (w *teamWriteWorld) importICS() *httptest.ResponseRecorder { |
| + var body bytes.Buffer |
| + mw := multipart.NewWriter(&body) |
| + _ = mw.WriteField("calendar_id", itoa(w.team)) |
| + fw, _ := mw.CreateFormFile("file", "in.ics") |
| + fmt.Fprint(fw, "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:imported-1\r\nSUMMARY:Imported\r\nDTSTART;TZID=UTC:20270111T100000\r\nDTEND;TZID=UTC:20270111T110000\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n") |
| + mw.Close() |
| + r := httptest.NewRequest("POST", homeTestOrigin+"/import", &body) |
| + r.Header.Set("Content-Type", mw.FormDataContentType()) |
| + r.Header.Set("Origin", homeTestOrigin) |
| + for _, c := range w.f.cookies { |
| + r.AddCookie(c) |
| + } |
| + rec := httptest.NewRecorder() |
| + w.f.app.mux.ServeHTTP(rec, r) |
| + return rec |
| +} |
diff --git a/internal/calendar/teamstate/migrations/0001_home_people.sql b/internal/calendar/teamstate/migrations/0001_home_people.sql| new file mode 100644 |
| index 0000000..9d3239d |
| --- /dev/null |
| +++ b/internal/calendar/teamstate/migrations/0001_home_people.sql |
| @@ -0,0 +1,13 @@ |
| +CREATE TABLE calendar_team_home_people ( |
| + issuer TEXT NOT NULL, |
| + subject TEXT NOT NULL, |
| + person_id INTEGER NOT NULL UNIQUE REFERENCES people(id), |
| + PRIMARY KEY(issuer,subject) |
| +); |
| +CREATE TRIGGER calendar_team_home_person_addressless BEFORE INSERT ON calendar_team_home_people WHEN NOT EXISTS(SELECT 1 FROM people WHERE id=NEW.person_id AND substr(address,1,10)='home-only:' AND instr(address,'@')=0) BEGIN SELECT RAISE(ABORT,'calendar team: refused'); END; |
| +CREATE TRIGGER calendar_team_home_person_unlinked BEFORE INSERT ON calendar_team_home_people WHEN EXISTS(SELECT 1 FROM home_identity_links WHERE issuer=NEW.issuer AND subject=NEW.subject) BEGIN SELECT RAISE(ABORT,'calendar team: refused'); END; |
| +CREATE TRIGGER calendar_team_home_people_keep_update BEFORE UPDATE ON calendar_team_home_people BEGIN SELECT RAISE(ABORT,'calendar team: refused'); END; |
| +CREATE TRIGGER calendar_team_home_people_keep_delete BEFORE DELETE ON calendar_team_home_people BEGIN SELECT RAISE(ABORT,'calendar team: refused'); END; |
| +CREATE TRIGGER calendar_team_link_not_home_only BEFORE INSERT ON home_identity_links WHEN EXISTS(SELECT 1 FROM calendar_team_home_people WHERE (issuer=NEW.issuer AND subject=NEW.subject) OR person_id=NEW.person_id) BEGIN SELECT RAISE(ABORT,'calendar team: refused'); END; |
| +CREATE TRIGGER calendar_team_home_person_keeps_no_address BEFORE UPDATE OF address ON people WHEN EXISTS(SELECT 1 FROM calendar_team_home_people WHERE person_id=OLD.id) BEGIN SELECT RAISE(ABORT,'calendar team: refused'); END; |
| +CREATE TRIGGER calendar_team_home_person_keep_row BEFORE DELETE ON people WHEN EXISTS(SELECT 1 FROM calendar_team_home_people WHERE person_id=OLD.id) BEGIN SELECT RAISE(ABORT,'calendar team: refused'); END; |
diff --git a/internal/calendar/teamstate/store.go b/internal/calendar/teamstate/store.go| new file mode 100644 |
| index 0000000..bede700 |
| --- /dev/null |
| +++ b/internal/calendar/teamstate/store.go |
| @@ -0,0 +1,180 @@ |
| +// Package teamstate keeps the Home-only people a roster admitted in team |
| +// mode, and the reverse lookup from a person to the Home subject the |
| +// roster knows them by. |
| +// |
| +// The marker and the roster evidence are not here: they are |
| +// home/teammode's State ("calendar", set calendar_team), merged beside |
| +// this package's own set (calendar_team_home). Calendar's local people |
| +// are its people table, whose address column is NOT NULL and UNIQUE, so a |
| +// Home-only person is a people row whose address is a random "home-only:" |
| +// placeholder that holds no address — no "@", never mailed, never shown — |
| +// and this package's table says which Home subject it belongs to. |
| +// |
| +// None of it is standing. A Home-only row says who a Home subject is on |
| +// this instance, never whether they are on the team: that is the |
| +// roster's answer, asked again on every request. |
| +package teamstate |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "database/sql" |
| + "embed" |
| + "encoding/hex" |
| + "errors" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrations embed.FS |
| + |
| +// Schema is the Home-only people table and its triggers. They name people |
| +// and home_identity_links, so it is merged after Calendar's own schema and |
| +// linkstore's (team_config.go's teamBoot). |
| +var Schema = migrate.MustFromFS(migrations, "calendar_team_home") |
| + |
| +var ( |
| + // ErrRefused is a definite "no": no such person, or a subject that |
| + // cannot be one. |
| + ErrRefused = errors.New("calendar team: refused") |
| + // ErrUnavailable is "cannot read it now". |
| + ErrUnavailable = errors.New("calendar team: unavailable") |
| +) |
| + |
| +// placeholderPrefix starts every Home-only person's address column. The |
| +// triggers check it, and Addressless recognises it: nothing that sends |
| +// mail or shows an address may use such a value. |
| +const placeholderPrefix = "home-only:" |
| + |
| +// Addressless reports whether a people.address value is a Home-only |
| +// placeholder rather than an address. |
| +func Addressless(address string) bool { |
| + return strings.HasPrefix(address, placeholderPrefix) || !strings.Contains(address, "@") |
| +} |
| + |
| +// HomePerson reads the person a Home-only identity was given. It never |
| +// creates one: ErrRefused means there is none. |
| +func HomePerson(ctx context.Context, db *sql.DB, issuer, subject string) (int64, error) { |
| + if !Opaque(subject) { |
| + return 0, ErrRefused |
| + } |
| + var id int64 |
| + e := db.QueryRowContext(ctx, "SELECT person_id FROM calendar_team_home_people WHERE issuer=? AND subject=?", issuer, subject).Scan(&id) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return 0, ErrRefused |
| + } |
| + if e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return id, nil |
| +} |
| + |
| +// HomeSubject is the reverse: the Home subject a person is known by on |
| +// this instance, through a Home-only row or an explicit account link. |
| +// ErrRefused means neither, which is no team standing, never an error. |
| +func HomeSubject(ctx context.Context, db *sql.DB, issuer string, person int64) (string, error) { |
| + var subject string |
| + e := db.QueryRowContext(ctx, `SELECT subject FROM calendar_team_home_people WHERE issuer=? AND person_id=? |
| + UNION ALL SELECT subject FROM home_identity_links WHERE issuer=? AND person_id=? LIMIT 1`, issuer, person, issuer, person).Scan(&subject) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return "", ErrRefused |
| + } |
| + if e != nil { |
| + return "", ErrUnavailable |
| + } |
| + return subject, nil |
| +} |
| + |
| +// EnsureHomePerson gives a Home subject an addressless person, or returns |
| +// the one it already has; created says which. The caller must have just |
| +// had a current roster answer of Member for this subject: this records |
| +// identity, not standing, and a later request asks the roster again. A |
| +// subject already linked to a local account is refused — that person |
| +// signs in as that account. |
| +// |
| +// The person's preferences start as a first local sign-in's do |
| +// (EnsurePerson): zone, week start and the two reminder defaults are the |
| +// caller's. Their calendars are made on their first page, as everybody's |
| +// are (requirePerson). |
| +func EnsureHomePerson(ctx context.Context, db *sql.DB, issuer, subject string, defaults Defaults) (id int64, created bool, err error) { |
| + if !Opaque(subject) || issuer == "" { |
| + return 0, false, ErrRefused |
| + } |
| + tx, e := db.BeginTx(ctx, nil) |
| + if e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + defer tx.Rollback() |
| + var linked int |
| + if e = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM home_identity_links WHERE issuer=? AND subject=?", issuer, subject).Scan(&linked); e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + if linked != 0 { |
| + return 0, false, ErrRefused |
| + } |
| + e = tx.QueryRowContext(ctx, "SELECT person_id FROM calendar_team_home_people WHERE issuer=? AND subject=?", issuer, subject).Scan(&id) |
| + if e == nil { |
| + if tx.Commit() != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + return id, false, nil |
| + } |
| + if !errors.Is(e, sql.ErrNoRows) { |
| + return 0, false, ErrUnavailable |
| + } |
| + placeholder, e := newPlaceholder() |
| + if e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + now := time.Now().UTC() |
| + res, e := tx.ExecContext(ctx, `INSERT INTO people(address,zone,created_at,updated_at,week_start,default_reminder_min,default_all_day_min) |
| + VALUES(?,?,?,?,?,?,?)`, placeholder, defaults.Zone, now, now, defaults.WeekStart, defaults.ReminderMin, defaults.AllDayMin) |
| + if e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + if id, e = res.LastInsertId(); e != nil || id <= 0 { |
| + return 0, false, ErrUnavailable |
| + } |
| + if _, e = tx.ExecContext(ctx, "INSERT INTO calendar_team_home_people(issuer,subject,person_id) VALUES(?,?,?)", issuer, subject, id); e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + if tx.Commit() != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + return id, true, nil |
| +} |
| + |
| +// Defaults are a new person's starting preferences. |
| +type Defaults struct { |
| + Zone string |
| + WeekStart, ReminderMin, AllDayMin int |
| +} |
| + |
| +// newPlaceholder is the people.address a Home-only person holds: the |
| +// prefix and sixteen random bytes, unique (the column is) and never an |
| +// address (no "@"). |
| +func newPlaceholder() (string, error) { |
| + b := make([]byte, 16) |
| + if _, err := rand.Read(b); err != nil { |
| + return "", err |
| + } |
| + return placeholderPrefix + hex.EncodeToString(b), nil |
| +} |
| + |
| +// Opaque is a Home subject's shape: bounded, printable, and never an |
| +// address, so a subject can never be mistaken for one. |
| +func Opaque(s string) bool { |
| + if s == "" || len(s) > 512 || !utf8.ValidString(s) || strings.Contains(s, "@") { |
| + return false |
| + } |
| + for _, r := range s { |
| + if r <= 32 || r == 127 { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/calendar/templates/agenda.html b/internal/calendar/templates/agenda.html| index 27bbb25..76f6251 100644 |
| --- a/internal/calendar/templates/agenda.html |
| +++ b/internal/calendar/templates/agenda.html |
| @@ -14,7 +14,7 @@ |
| </div> |
| </header> |
| -{{template "calendar-toolbar" (dict "View" "agenda" "Noun" "fortnight" "Prev" (printf "/agenda?from=%s" .Data.PrevISO) "Today" "/agenda" "Next" (printf "/agenda?from=%s" .Data.NextISO) "Day" (printf "/day/%s" .Data.Agenda.FromISO) "Week" (printf "/week/%s" .Data.Agenda.FromISO) "Month" (printf "/month/%s?date=%s" (slice .Data.Agenda.FromISO 0 7) .Data.Agenda.FromISO) "Agenda" (printf "/agenda?from=%s" .Data.Agenda.FromISO))}} |
| +{{template "calendar-toolbar" (dict "View" "agenda" "Noun" "fortnight" "Prev" (printf "/agenda?from=%s" .Data.PrevISO) "Today" "/agenda" "Next" (printf "/agenda?from=%s" .Data.NextISO) "Day" (printf "/day/%s" .Data.Agenda.FromISO) "Week" (printf "/week/%s" .Data.Agenda.FromISO) "Month" (printf "/month/%s?date=%s" (slice .Data.Agenda.FromISO 0 7) .Data.Agenda.FromISO) "Agenda" (printf "/agenda?from=%s" .Data.Agenda.FromISO))}}{{if .Partial}}{{template "team-partial" .}}{{end}} |
| {{/* The agenda's scope, below the toolbar like the day's sentence. */}} |
| <p cal-sentence cal-sentence-muted>The next fortnight, and only the days with something in them.</p> |
| @@ -30,7 +30,7 @@ |
| </div> |
| </section> |
| {{end}} |
| -{{else}} |
| +{{else if not .Partial}} |
| {{/* An empty state that teaches. "No events found" earns nothing. */}} |
| {{template "empty-state" dict |
| "Title" "Nothing in the next fortnight" |
diff --git a/internal/calendar/templates/booking_pages.html b/internal/calendar/templates/booking_pages.html| index 9d7e32c..89b3345 100644 |
| --- a/internal/calendar/templates/booking_pages.html |
| +++ b/internal/calendar/templates/booking_pages.html |
| @@ -8,7 +8,7 @@ |
| <a rst-btn="primary" href="/settings/booking/new">New page</a> |
| </header> |
| -{{if .Data.Saved}} |
| +{{if .Data.NoAddress}}{{template "callout" dict "Tone" "warning" "Title" "Booking pages need an email address" "Body" "You signed in with an Oficina account, which doesn’t give this calendar an email address. A booker’s invitation names you by address and booking mail is sent to you, so a page can be drafted here but not published."}}{{end}}{{if .Data.Saved}} |
| {{template "callout" dict "Tone" "positive" "Body" "Saved."}} |
| {{end}} |
diff --git a/internal/calendar/templates/calendars.html b/internal/calendar/templates/calendars.html| index f2e8e5f..686cb29 100644 |
| --- a/internal/calendar/templates/calendars.html |
| +++ b/internal/calendar/templates/calendars.html |
| @@ -4,7 +4,7 @@ |
| <div rst-page-header-titles> |
| <h1>Calendars</h1> |
| </div> |
| -</header> |
| +</header>{{if .Partial}}{{template "team-partial" .}}{{end}} |
| <div rst-list> |
| {{range .Data.Calendars}} |
diff --git a/internal/calendar/templates/day.html b/internal/calendar/templates/day.html| index 3184cb5..bd8a270 100644 |
| --- a/internal/calendar/templates/day.html |
| +++ b/internal/calendar/templates/day.html |
| @@ -14,12 +14,12 @@ |
| </div> |
| </header> |
| -{{template "calendar-toolbar" (dict "View" "day" "Noun" "day" "Prev" (printf "/day/%s" .Data.PrevISO) "Today" (printf "/day/%s" .Data.TodayISO) "Next" (printf "/day/%s" .Data.NextISO) "Day" (printf "/day/%s" .Data.Day.ISO) "Week" (printf "/week/%s" .Data.Day.ISO) "Month" (printf "/month/%s?date=%s" (slice .Data.Day.ISO 0 7) .Data.Day.ISO) "Agenda" (printf "/agenda?from=%s" .Data.Day.ISO))}} |
| +{{template "calendar-toolbar" (dict "View" "day" "Noun" "day" "Prev" (printf "/day/%s" .Data.PrevISO) "Today" (printf "/day/%s" .Data.TodayISO) "Next" (printf "/day/%s" .Data.NextISO) "Day" (printf "/day/%s" .Data.Day.ISO) "Week" (printf "/week/%s" .Data.Day.ISO) "Month" (printf "/month/%s?date=%s" (slice .Data.Day.ISO 0 7) .Data.Day.ISO) "Agenda" (printf "/agenda?from=%s" .Data.Day.ISO))}}{{if .Partial}}{{template "team-partial" .}}{{end}} |
| {{/* The day's own sentence. Not a caption — it is the answer to the |
| question somebody opened this page to ask. Below the toolbar, so its |
| length (and whether it wraps) never moves the controls. */}} |
| -<p cal-sentence>{{.Data.Day.Summary.Sentence}}</p> |
| +{{if not .Partial}}<p cal-sentence>{{.Data.Day.Summary.Sentence}}</p>{{end}} |
| {{if .Data.Day.AllDay}} |
| <div cal-allday> |
| @@ -52,11 +52,11 @@ |
| </div> |
| </div> |
| -{{if not .Data.Day.Placed}}{{if not .Data.Day.AllDay}} |
| +{{if not .Partial}}{{if not .Data.Day.Placed}}{{if not .Data.Day.AllDay}} |
| {{template "empty-state" dict |
| "Title" "Nothing on this day" |
| "Body" "Pick a time in the grid above, or use New event."}} |
| -{{end}}{{end}} |
| +{{end}}{{end}}{{end}} |
| </main> |
| {{end}} |
| {{define "content"}}{{end}} |
diff --git a/internal/calendar/templates/event.html b/internal/calendar/templates/event.html| index fd68a1a..dc7876e 100644 |
| --- a/internal/calendar/templates/event.html |
| +++ b/internal/calendar/templates/event.html |
| @@ -67,7 +67,7 @@ |
| <div cal-box-body> |
| {{/* Yours only. Whether a colleague wants a warning is a fact |
| about them, and not something this page should carry. */}} |
| - {{if .Data.Reminders}} |
| + {{if .Data.NoAddress}}<p data-no-address>Email reminders need an email address, and you signed in with an Oficina account that doesn’t give this calendar one, so this calendar can’t remind you.</p>{{else}}{{if .Data.Reminders}} |
| {{range .Data.Reminders}} |
| <form cal-reminder method="post" action="/events/{{$.Data.Event.ID}}/reminders/remove"> |
| <input type="hidden" name="reminder_id" value="{{.ID}}"> |
| @@ -93,7 +93,7 @@ |
| (dict "Value" "60" "Label" "1 hour before") |
| (dict "Value" "1440" "Label" "1 day before"))}} |
| <button rst-btn type="submit">Add</button> |
| - </form> |
| + </form>{{end}} |
| </div> |
| </section> |
diff --git a/internal/calendar/templates/layout.html b/internal/calendar/templates/layout.html| index d97894c..e2abad1 100644 |
| --- a/internal/calendar/templates/layout.html |
| +++ b/internal/calendar/templates/layout.html |
| @@ -48,6 +48,11 @@ |
| each link's accessible name), so switching views or stepping through |
| them moves nothing. A view's own lead line (the day's sentence, the |
| agenda's scope) sits BELOW this row, never above it. */}} |
| +{{/* Team mode's partial notice (Paul, 2026-10-28): the roster could not |
| + be read within its lease, so the view below holds only what the |
| + person reaches without team standing — nothing, in Calendar. Never |
| + drawn outside team mode, and never for somebody off the team. */}} |
| +{{define "team-partial"}}<div data-partial>{{template "callout" dict "Tone" "warning" "Title" .PartialTitle "Body" .PartialBody "Alert" true}}</div>{{end}} |
| {{define "calendar-toolbar"}}<div cal-bar> |
| <div cal-bar-steps> |
| <a rst-btn href="{{.Prev}}">Previous<span class="rst-sr-only"> {{.Noun}}</span></a> |
diff --git a/internal/calendar/templates/month.html b/internal/calendar/templates/month.html| index d21a2e0..e5bd4e0 100644 |
| --- a/internal/calendar/templates/month.html |
| +++ b/internal/calendar/templates/month.html |
| @@ -14,7 +14,7 @@ |
| </div> |
| </header> |
| -{{template "calendar-toolbar" (dict "View" "month" "Noun" "month" "Prev" (printf "/month/%s" .Data.Month.PrevISO) "Today" (printf "/month/%s" .Data.TodayMonth) "Next" (printf "/month/%s" .Data.Month.NextISO) "Day" (printf "/day/%s" .Data.SelectedISO) "Week" (printf "/week/%s" .Data.SelectedISO) "Month" (printf "/month/%s?date=%s" .Data.Month.ISO .Data.SelectedISO) "Agenda" (printf "/agenda?from=%s" .Data.SelectedISO))}} |
| +{{template "calendar-toolbar" (dict "View" "month" "Noun" "month" "Prev" (printf "/month/%s" .Data.Month.PrevISO) "Today" (printf "/month/%s" .Data.TodayMonth) "Next" (printf "/month/%s" .Data.Month.NextISO) "Day" (printf "/day/%s" .Data.SelectedISO) "Week" (printf "/week/%s" .Data.SelectedISO) "Month" (printf "/month/%s?date=%s" .Data.Month.ISO .Data.SelectedISO) "Agenda" (printf "/agenda?from=%s" .Data.SelectedISO))}}{{if .Partial}}{{template "team-partial" .}}{{end}} |
| {{/* A real table. A month IS tabular data — seven weekday columns |
| against week rows — so the headers come free for a screen reader, |
diff --git a/internal/calendar/templates/settings.html b/internal/calendar/templates/settings.html| index baf3fc0..4dd48b9 100644 |
| --- a/internal/calendar/templates/settings.html |
| +++ b/internal/calendar/templates/settings.html |
| @@ -6,7 +6,7 @@ |
| </div> |
| </header> |
| -{{if .Data.Saved}} |
| +{{if .Data.NoAddress}}{{template "callout" dict "Tone" "info" "Title" "No email from this calendar" "Body" "You signed in with an Oficina account, which doesn’t give this calendar an email address. Reminders are not sent, and booking pages cannot be published."}}{{end}}{{if .Data.Saved}} |
| {{template "callout" dict "Tone" "positive" "Body" "Saved."}} |
| {{end}} |
| {{with .Data.Error}} |
diff --git a/internal/calendar/templates/week.html b/internal/calendar/templates/week.html| index eabef19..938bd71 100644 |
| --- a/internal/calendar/templates/week.html |
| +++ b/internal/calendar/templates/week.html |
| @@ -15,7 +15,7 @@ |
| </div> |
| </header> |
| -{{template "calendar-toolbar" (dict "View" "week" "Noun" "week" "Prev" (printf "/week/%s" .Data.PrevISO) "Today" (printf "/week/%s" .Data.TodayISO) "Next" (printf "/week/%s" .Data.NextISO) "Day" (printf "/day/%s" .Data.StartISO) "Week" (printf "/week/%s" .Data.StartISO) "Month" (printf "/month/%s?date=%s" (slice .Data.StartISO 0 7) .Data.StartISO) "Agenda" (printf "/agenda?from=%s" .Data.StartISO))}} |
| +{{template "calendar-toolbar" (dict "View" "week" "Noun" "week" "Prev" (printf "/week/%s" .Data.PrevISO) "Today" (printf "/week/%s" .Data.TodayISO) "Next" (printf "/week/%s" .Data.NextISO) "Day" (printf "/day/%s" .Data.StartISO) "Week" (printf "/week/%s" .Data.StartISO) "Month" (printf "/month/%s?date=%s" (slice .Data.StartISO 0 7) .Data.StartISO) "Agenda" (printf "/agenda?from=%s" .Data.StartISO))}}{{if .Partial}}{{template "team-partial" .}}{{end}} |
| {{/* The week keeps its two dimensions on a phone and scrolls sideways. |
| Flattening it to a list would make it the agenda, which already |
diff --git a/internal/calendar/viewer.go b/internal/calendar/viewer.go| index b5aec32..c10dafe 100644 |
| --- a/internal/calendar/viewer.go |
| +++ b/internal/calendar/viewer.go |
| @@ -20,7 +20,7 @@ func viewer(r *http.Request) (rauth.Identity, bool) { |
| if !found { |
| return rauth.Identity{}, false |
| } |
| - return rauth.Identity{Address: p.Address}, true |
| + return rauth.Identity{Address: p.shownAddress()}, true |
| } |
| if s, ok := sessions.Current(r); ok && (s.Method == "magiclink" || s.Method == "keymail") { |
| return rauth.Identity{Address: normalizeAddress(s.Subject)}, s.Subject != "" |