Skip to content

v0.1.0-rc.3 - #349

Closed
jeroenrinzema wants to merge 140 commits into
release/v0.1.0from
main
Closed

jeroenrinzema wants to merge 140 commits into
release/v0.1.0from
main

Conversation

@jeroenrinzema

Copy link
Copy Markdown
Contributor

Release candidate v0.1.0-rc.3: everything merged on main since v0.1.0-rc.2, including #327 (GET /api/admin/auth/key lets an API key look up its own project, which the Go/JS/Python SDKs now use when no project ID is configured).

The console renders a "Sending" badge for a scheduled message whenever
`has_pending_events` is true. That field was computed as "any unfired
event exists", but recurring schedules pre-generate the next
occurrence's event the moment they advance (anchor + N*interval). As a
result every recurring schedule perpetually had an unfired future event
and was shown as "Sending" indefinitely, even while idle months before
its next run.

Scope `has_pending_events` to events that are actually due
(`fired_at IS NULL AND fire_at <= NOW()`) in ListUserSchedules and
ListOrganizationSchedules. This matches the existing scan-due predicate
and the "up to 1 minute to process" tooltip: the badge now reflects an
event being actively delivered, not one queued for a future occurrence.

No frontend change needed — the badge keys solely off this field.
Recurring schedules advanced to their next occurrence with a
generate_series(1, 10000) scan from the anchor. That scan both capped how
far a schedule could be advanced and was O(N) in the number of skipped
occurrences: a schedule dormant for more than 10000 intervals (e.g. a
1-minute interval idle for ~7 days, or hourly for ~1 year) could never
resume — the advance query returned no row and errored every cycle.

Replace the scan with a next_schedule_occurrence SQL function that
estimates the occurrence number in O(1) from the average interval length
and then corrects it exactly with a couple of interval-arithmetic loops.
The estimate only seeds the loops; the returned occurrence is exact for
any strictly-increasing interval and there is no upper bound on the
catch-up gap. Both the user and organization advance paths and
computeNextOccurrence now call it, removing the duplicated calendar math.

Tested: exact known cases (yearly, month-end clamping, boundary, ~470yr
dormancy), a 640-case property grid asserting the defining properties
across leap years / mixed calendar intervals / horizons to year 3025, and
rejection of non-positive intervals.
The create button stayed disabled after enabling and then disabling the
transactional toggle, even with a subscription selected. Toggling
transactional on cleared subscription_id, and the auto-select effect
restored a subscription via form.setValue without revalidating, leaving
formState.isValid stale at false.

Pass shouldValidate so the form revalidates when subscription_id is set
programmatically.
…are usable

The gate (and other downstream) variable picker only surfaces a step's
event variables when that step has a `data_key` — the backend likewise
only exposes step state under `journey.<data_key>.*`. Entrance steps never
got a data_key assigned automatically (it was a manual, easily-missed
field), so the triggering "input" event's variables never appeared in the
picker; only the always-present "User" group showed.

Give entrances a readable, unique default data_key ("entrance",
"entrance_2", …):
- at creation, in both the drag-drop and trigger-setup paths, and
- as a non-destructive backfill on load for entrances that predate this,
  persisted on the next manual save.
An exit step requires an `entrance_uuid` (the entrance it terminates), but
it was always empty on drop, forcing a manual pick and failing validation
until set. Default it to the first entrance when placed, so single-entrance
journeys — the common case — need no extra configuration.
The Journey editor's Send node renders the email preview inside a small
250x200 thumbnail (size="small"), but EmailFrame always laid out at full
scale: 22px subject, large avatar, generous padding, and a full row of
Gmail action icons. Crammed into the thumbnail this wrapped the subject,
sender name, and timestamp onto multiple lines and overlapped the reply
icon, leaving the preview looking broken.

Thread the existing `size` prop through to EmailFrame and add a compact
layout for "small": tighter padding, smaller subject/sender/avatar type,
truncation instead of wrapping, and hidden action icons. Full-size
previews are unchanged.
Replace the previous compact-header approach. For the small thumbnail in
the Journey Send node the Gmail-style header chrome (subject, sender,
action icons) doesn't fit and looked broken. Instead, render the
compiled email itself, clipped to the thumbnail height — a truer preview
of what will be sent. EmailFrame is reverted to its original full-size
layout; large previews are unchanged.
The generated oapi `HandlerWithOptions` wrapper composes middlewares with a
forward-wrapping loop (`handler = mw(handler)`), so the LAST entry in the
`Middlewares` slice becomes the outermost wrapper and executes FIRST. The
slice was ordered `[Validator, RateLimit]`, so RateLimit actually ran BEFORE
the validator's authentication.

As a result `rbac.FromContext` was always nil when the limiter computed its
key, and every request fell back to the `ip:` bucket. Behind a reverse proxy
or ingress (and `TrustedProxyHops` defaults to 0, so `RemoteAddr` is used),
that IP is the proxy's — identical for all traffic — collapsing the entire
deployment into a single shared 600/min bucket. API-key ingestion and
Clerk-authenticated console sessions then starved each other's budget instead
of being keyed independently per auth method.

List RateLimit before the validator on both surfaces so it runs *after*
authentication and keys on the resolved actor, and add a regression test that
composes the chain like the generated wrapper and asserts two actors from the
same IP get independent budgets.
…e scheduling (#280)

* feat(scheduled): address schedule assignments by id for multi-instance scheduling

Schedule assignments are now addressed by their own id. Submitting with an
existing assignment id upserts that row; omitting it creates a new instance, so
a single subject can hold multiple assignments to the same named schedule
(e.g. several reminders of the same kind, or rescheduling a specific one).

- migration drops the unique (user_id, schedule_id) / (organization_id,
  schedule_id) indexes; the non-unique lookup indexes are kept
- UpsertUserSchedule / UpsertOrganizationSchedule take an id and conflict on
  (id), guarded by user/schedule so a supplied id cannot hijack another
  subject's row (ErrScheduleOwnershipMismatch otherwise)
- ScheduledMsg carries assignment_id; the client API exposes an optional id on
  the upsert requests and returns the assignment id in the 202 response; the
  management API exposes an optional id so the console can target an instance
- journey schedule steps derive a deterministic assignment id from
  (user, schedule) so re-runs/retries stay idempotent (no behaviour change)
- regenerated client + management Go oapi and the console TS types

* feat(scheduled): journeys schedule a new instance per entry; client delete-by-id

Follow-up to the id-based assignment change:

- Journey schedule steps now create a NEW assignment per journey entry (a user's
  pass through the journey), so re-entering schedules an additional instance.
  The id is derived from (journey_entry_id, step_id) so a redelivered/retried
  step message stays idempotent instead of duplicating.
- Client API delete now accepts an optional id to remove a single assignment
  (ownership-checked); without an id it still deletes every assignment by name.
  name is now optional (either id or name required); regenerated client oapi.

* fix(scheduled): regenerate oapi with pinned oapi-codegen v2.7.0

The generated files were produced with v2.5.1 locally, which diverges from the
CI-pinned v2.7.0 and broke the generate check. Regenerated with v2.7.0; the diff
vs main is now scoped to the new schedule id fields only.

* fix(scheduled): keep omitted-id messages idempotent; require delete identifier

Addresses PR review:
- Consumer derives a deterministic assignment id from (subject, schedule) when a
  ScheduledMsg omits assignment_id, so producers that don't set one (user/org
  anniversary schedules) stay idempotent under at-least-once redelivery instead
  of minting a fresh id per delivery and duplicating the assignment. The client
  API still sends an explicit id, so its create-new-per-submit behaviour is
  unchanged.
- DeleteUserScheduledRequest now requires identifier in the schema (the handler
  already rejected requests without one); regenerated client oapi and updated the
  handler for the now non-pointer identifier.
- Added a unit test for resolveAssignmentID.

* docs(scheduled): update upsert doc comments for id-based semantics

The UpsertUserSchedule / UpsertOrganizationSchedule doc comments still described
the old (subject, schedule) conflict model. Updated to reflect that assignments
are keyed by their own id (nil creates a new instance; an existing id updates in
place, guarded by ErrScheduleOwnershipMismatch).
When a scheduled item is created with a brand-new schedule name, the
server registers a new schedule schema (new id). The id→name map backing
the list, however, was fetched once on mount and never refreshed, so the
freshly created row had no name entry and fell back to rendering its raw
scheduled_id (a UUID) instead of the name the user just entered.

Capture the schema resolver's reload function and call it alongside the
instance reload after a successful create, so the new id→name mapping is
available immediately.
GetSession read an "oauth" cookie at the highest precedence, above the
HttpOnly __session cookie and the Authorization header. Nothing in the
platform ever wrote that cookie -- not the providers, not the console,
not any service -- so the intake was reachable only by something else
setting it. Because it is a plain, non-HttpOnly cookie, anything able to
write a cookie on the origin could use it to override the real session
for the whole management API.

Remove the intake, the OAuthResponse type and its decoder, and pin the
removal with a test so the precedence cannot come back.
Split admin identity out of the admins.external_id scalar into
admin_identities, keyed on (issuer, subject) so per-organization SSO
connections with colliding subject spaces stay distinguishable, and add
admin_sessions as the revocation handle the stateless admin JWT never had.

The email index becomes case-insensitive because email is now an
identity-linking key. Colliding addresses are reconciled rather than
merged: one canonical row per address is elected by a deterministic
ranking and the rest are quarantined via email_conflict_at, keeping
every admin able to authenticate through admin_identities while the
email join fails closed on a contested address.

external_id is backfilled under a sentinel issuer and dropped rather
than deprecated, so the two-sources-of-truth divergence cannot return.

Session lookups go through a two-tier cache (5s in-process over 60s
Redis over Postgres) that, unlike the JWKS cache, never serves a value
it could not confirm.
WithJWT decided which signature algorithms to accept from the presence of
key material rather than from the configured driver: RS256 was always
accepted, and HS256 was added whenever AUTH_JWT_SECRET was non-empty. The
comment defending that arrangement argued the two algorithms never share
key material, so RS256->HS256 confusion is impossible. That is true, but
it only covers confusion between two TRUSTED keys. It says nothing about
a secret the attacker knows: a deployment that authenticates through
Clerk but also carries a stray AUTH_JWT_SECRET has a fully trusted HS256
verification path keyed on that secret, so anyone holding it can sign a
token whose sub names an admin and be authenticated as that admin.

Select both the accepted algorithms and the verification key from the
driver instead, so exactly one algorithm and one key source is live:
clerk verifies RS256 against the provider JWKS, basic verifies HS256
against the local signing secret, and an unused secret grants nothing.
An unrecognised driver now fails closed rather than defaulting to an
accepted set.

A driver that issues HS256 tokens must also have a secret worth trusting,
so construction rejects one that is empty, equal to the example value
published in the repository, or under 32 bytes, naming the variable and
the command to generate a good value. WithJWT therefore returns an error
and the server refuses to start on such a configuration, instead of
serving forgeable admin sessions until someone notices.
The admin token parse treated exp as optional, so a token minted without
one was accepted forever: it could not be aged out, and revoking it meant
rotating the signing secret and cutting every other session. Require the
claim. Every token this codebase mints already sets exp, so no existing
session is affected.
The Clerk provider listed HS256 alongside RS256 in its accepted methods
while being handed a JWKS-only keyfunc, so an HMAC token could never
resolve a key there. Not a live hole, but config that advertises trust
the provider does not actually extend invites someone to wire an HMAC
keyfunc in later and turn it into one. Accept only what Clerk signs.
docker-compose.yml supplied a working fallback for AUTH_JWT_SECRET, and
that value shipped in a public repository. Any self-hosted deployment
that did not override it was signing admin sessions with a secret anyone
could read, which is enough on its own to mint a session for an
arbitrary admin.

Drop the fallback and mark the variable required, so compose stops with
a message telling the operator what to set and how to generate it rather
than silently starting on a public secret. Document the same in the
README quickstart and the contributor setup, and correct the README's
stale reference to APP_SECRET, which this codebase does not read.
Two token shapes flowed through one admin middleware: basic minted HS256
with sub = admin UUID, Clerk supplied RS256 with sub = external_id, and a
keyfunc dispatched on algorithm. That single fact produced the
external-id-then-UUID fallback, the "parse as UUID, else external id"
branches, one identity per admin, and no revocation of any kind.

Every credential now terminates in one Lunogram-issued ES256 console
session: a Verifier proves it and stops, an Exchanger resolves or links
the admin, records an admin_sessions row, mints the token and sets the
cookie. The token carries only sub and sid -- no email, role, or
organization, since those are authorization inputs that must be re-read
per request rather than frozen into a bearer credential.

Deleted: WithJWT, multiKeyfunc, GetAdminBySubject, the oauth cookie
intake (read at highest precedence, written nowhere), the whole
providers package, and both copies of provisionMembership. The
transactional, post-commit-ordered one survives as
access.ProvisionMembership; the login path's non-transactional copy,
which was the one every first login ran, is gone.

The console cookie moves off __session, which the Clerk SDK owns and
rewrites on our own origin. UpgradeLegacySession exchanges a legacy
cookie in flight so this deploy logs nobody out.

Also fixes a latent bug: uuid.Parse(actor.ID) was used as an "is this an
admin?" guard, but an API-key actor's id is a UUID too, so the parse
succeeded and the request continued with a key id where an admin id was
expected -- a 500 where it should have been a 403.
logout() now calls POST /api/auth/logout BEFORE signing out of the
upstream provider. The order matters: signing out upstream first leaves
our own session alive with nothing left to authenticate the revocation,
so it would be orphaned until it expired on its own.

The console session cookies are HttpOnly and cannot be cleared from the
page at all, which is why the server call is the actual logout and
clearAuthCookies is only cleanup of what is left.
The basic driver refuses to start when its signing secret cannot keep a
session private, but the clerk driver accepted a nil keyfunc. With
AUTH_JWKS_URL unset the process started and then rejected every admin
login, which reads as "Clerk login is broken" rather than as a missing
variable. Validate both drivers' key material the same way.
Startup now refuses to run a configured auth driver without a console
signing key, so the compose quickstart needs one. The default shipped
here is a publicly known development key and says so; a real deployment
must supply its own.

A PEM whose newlines arrive escaped is accepted, because that is how a
multi-line key reaches the process from a compose file, a Kubernetes env
var, or a PaaS dashboard.
Add a step visit condition to the gate step so a recursive flow can be
capped: "has passed this step more than 3 times" sends the user down the
no path until they exceed the limit, after which they take the yes path.

Counts come from journey_user_state rather than from counting
journey.step.entered events. The state table already keeps one row per
step entry, keyed by (journey_entry_id, external_step_id, occurrence), so
the count is exact and read in the same request. The event is published
to NATS just before the gate runs and lands in user_events through a
separate consumer, which would make the count of the visit in progress a
race.

A count includes the visit in progress: a user standing on a step for the
third time compares against 3. The state row for that visit is only
written once the step completes, so the current step counts one higher
unless its row already exists, as it does for a resumed step.

Rules carry the target step in path (empty meaning the step the gate sits
on) and an optional step_scope selecting whether visits are counted within
the user's current run through the journey or across all of their runs.
The rule set now splits three ways - local, step visits, historical -
evaluated cheapest first so a decided AND/OR skips the queries behind it.
Step visit rules are rejected by the user query builder, since they carry
no meaning outside a running journey.
An idle window longer than the absolute lifetime violates a CHECK on
admin_sessions, so it is rejected at startup rather than surfacing as
every login failing on a constraint violation.

HMAC and TokenClaims went unused when WithJWT was deleted, and the
session cache is now invalidated exactly when the cached row changes:
switching the active organization changes nothing that is cached, since
the active organization deliberately lives on the admin and is
re-validated against current membership on every request.
The actor carries the impersonation attribution, but nothing downstream
is obliged to log it, and "who was actually driving this session" is
exactly the question an audit has to answer. The middleware logs it
once per request, where the session row is already in hand.
Reversibility is the justification for dropping admins.external_id
outright rather than deprecating it, so it is worth proving rather than
assuming: the three migrations are walked down one at a time,
external_id is reconstructed from admin_identities, and the whole set is
re-applied, electing the same duplicate-email keepers as the first run.

Also makes ErrAmbiguousEmail describe the single-survivor case honestly:
one quarantined row left after its counterpart was deleted is still not
a confirmed owner, but it is not "more than one admin" either.
Comparing Origin only against the configured public URL turns a
PUBLIC_URL that does not match how the console is actually reached into
a 401 on every write the console makes. Accepting the request's own
origin as well degrades that misconfiguration to ordinary same-origin
enforcement.

It is not a loophole: on a cross-site request the browser sets Origin to
the attacker's page while the URL, and so the Host, is still ours, so
the two can only agree when the request really is same-origin.
CreateProjectInvite logged actor.ID on the not-an-admin path without
first checking that an actor was present, so an unauthenticated request
would have turned that error path into a panic. The other two invite
handlers already guarded; this makes the third match them.
Replaces the two hardcoded webhook URLs with a hook engine modelled on
Ory's web_hook. Hooks are declared per event in a YAML file, many
subscribers per event, each with its own JSONNet body template,
credential, retry policy and network policy. Templates are compiled at
boot so a broken one fails startup rather than the first event.

Splits transport from events, which is the change the rest depends on.
internal/outbound owns the authenticated, SSRF-guarded, retrying HTTP
primitive; internal/webhook owns the event registry and hook dispatch;
internal/gallery uses the transport directly for the email-template
fetch. That fetch is a synchronous GET whose response is the handler's
return value, so every degree of freedom the hook model offers would be
pinned to one legal value; it is not a hook and is no longer modelled as
one.

Stops forwarding the API caller's request headers to operator-configured
endpoints. The previous implementation copied every inbound header,
including the caller's bearer token, handing the receiver the caller's
full API privileges. Receivers now authenticate with their own
credential and read the triggering identity from the actor block in the
payload. Forwarding requires agreement in two places -- an explicit
config allowlist and an opt-in at the call site -- so it cannot reappear
by accident in a new event.

The wire payload is unchanged: the embedded default template reproduces
ProjectCreatedEvent exactly, so existing receivers are unaffected.

internal/ssrf gains a Policy type so a hook aimed at an in-cluster
receiver can opt out of individual guards per destination rather than
process-wide. Cloud instance metadata and link-local addresses are
refused under every policy.
The handler chain that authenticates the OpenAPI surfaces was reachable
only as an openapi3filter.AuthenticationFunc, so a route registered
directly on the router had no way to reuse it. Lift the chain walk into a
shared helper and add Require, a plain func(http.Handler) http.Handler
that runs it, resolves the credential with GetSession, and renders a 401
problem in the calling surface's shape.

Require deliberately leaves the response writer untouched so a wrapped
streaming handler keeps its http.Flusher, and it renders a 500 when a
handler fails to evaluate a credential rather than falling through to the
next one.
jeroenrinzema and others added 27 commits August 31, 2026 22:55
…eview

Two drivers proved an email and a password. They differed only in where the
secret lived, and only one of them had the login throttle, the constant-time
comparison against a dummy hash, and the re-hash on login. The console grew two
buttons submitting the same form to different callbacks, and admin_identities
two provider values meaning nearly the same thing.

There is one driver now, and it is still called basic.

## The configured pair seeds an account instead of being compared against

AUTH_BASIC_EMAIL / AUTH_BASIC_PASSWORD are written into a real admin at boot
with the password hashed, so the quickstart account holds its own RBAC tuples,
appears in the admin list and can change its own password like any other. Three
things follow:

  - The plaintext is needed once. It used to have to stay in the environment for
    as long as the deployment ran, because every login compared against it.
  - A restart cannot undo a password change. The seed fills a MISSING secret and
    never replaces a stored one; re-applying the environment on every boot would
    silently revert a password set in the console.
  - Existing deployments cross over without doing anything. One already signing
    in with the configured pair has the admin already, found by address, and
    only the hash is new -- its id, organization and permissions are untouched.

Migration 1787000000005 folds the providers together and relaxes the CHECK that
bound a secret to the removed one. What still holds is the half that matters: a
federated identity can never carry a local secret. The other half could not
survive, because a local identity may legitimately be waiting for a password --
an admin holding an invite, and the seeded account between the migration and the
boot that fills it in.

## Findings from the review

An action token named an account rather than a mailbox. admins.email can be
changed by an owner with nothing proving the new address, so a verification link
sent to an address you control stayed redeemable after pointing the account at
an invited one -- reopening the invite escalation this branch set out to close.
Tokens carry the address they were sent to and redemption compares it in the
same statement (1787000000006), so there is no window between the check and the
consumption.

Re-hashing on login could restore an old password: it read a hash, computed a
stronger one and wrote it back unconditionally, so a password change committing
in between was undone. The write is compare-and-swap on the hash that was
verified, and losing that race is the correct outcome for maintenance work.

Nothing bounded concurrent argon2. Each computation reserves 64MiB, and the
source budget deliberately admits a burst, counts failures rather than attempts,
and fails open without Redis -- so a few dozen simultaneous logins reserved
gigabytes. Hashing is bounded to between 2 and 8 in flight, tracking GOMAXPROCS
because argon2id at p=1 saturates one core each. A burst queues rather than
failing: turning it into failed sign-ins would hand anyone who can generate one
a way to lock everybody out.

Check-then-spend was a race on the endpoints that count attempts. Concurrent
registrations all read an unspent budget, all passed, and only then started
recording, so a burst got through whatever the limit said. Those endpoints claim
atomically now; the ones that count failures keep the split, which is what lets
a working password go uncharged.

Change-password verified without checking the budget first. It recorded every
wrong guess and refused none of them, leaving unlimited guesses at the current
password through a stolen session.

Reset and change committed the hash before revoking. A failure in either later
write left the password changed while the links and sessions it was meant to
kill were still live -- the exact guarantee both flows advertise. All three
writes are one transaction, and the session cache is invalidated after the
commit rather than inside it, where a rollback would have left a live session
missing from the cache.

Auth.Enabled did not normalise driver names, so AUTH_DRIVER=" BASIC " built and
advertised a driver that every later check reported as off. Normalised once at
load.

The console AuthDriver union excluded the driver: seven real type errors, missed
because tsc -p is a no-op in this project.

Not done: "Change password" is still offered on a deployment-wide capability
rather than an account-level one. The merge narrows it to SSO-only admins in a
mixed deployment, and the fix needs account-level capability in the session
response -- an API change better made on its own.

Verified: both build tags compile and vet clean, golangci-lint clean, console
eslint clean and no auth type errors under tsc -b, full suite green across 45
packages.
Seven findings, of which the first is the one that mattered.

Stored argon2 parameters went into argon2.IDKey unvalidated. It panics outright
on t=0 or p=0, and a large enough m allocates until the process is killed, so a
single malformed row turned every sign-in on that address into a crash or an
out-of-memory. The values come from a stored hash rather than from a request,
which makes this a data-integrity check -- but the effect of skipping it was not
proportional to how likely the row was, so zero and out-of-range values are now
ErrMalformedHash before the KDF is reached.

The mail dispatcher logged the rendered subject. That was true and harmless
until this branch made subjects operator templates with .Recipient and
.ActionURL in scope; after that a delivery outage could write addresses or live
reset tokens into the log, which is precisely what the comment above it promised
did not happen. It logs the message kind, which identifies the flow and nothing
about the person.

Flow enablement read the raw driver list while the verifier registry read a
normalised one, so a configured " BASIC " could build and advertise a working
driver while registration, reset and the mail setup were all skipped. Taken from
the built verifiers, which cannot disagree with themselves.

Email verification consumed the token and then marked the address proved. A
failure in between left the address unverified with its only link already spent:
single-use is there to stop a replay, not to let a transient database error burn
a link. One transaction.

The confirmation link was redeemed as soon as the page rendered. Mail security
scanners and link-preview fetchers follow URLs out of a mailbox, and one
arriving first would both spend the recipient's link and confirm an address
nobody had demonstrated control of -- the invite escalation again, reached from
a different direction. It takes a click now, which is the thing a crawler does
not do.

Dispatcher.Close had no production caller, so the drain-on-shutdown it documents
only ever happened in tests and a deploy dropped whatever was queued. Registered
with the server's graceful lifecycle.

Expired and consumed action tokens were never deleted. Every registration and
every reset wrote one, and the rows and their unique index entries accumulated
for the life of the deployment. Purged on the existing reconciliation tick with
a week's retention -- long enough to answer "was this link ever used" during an
incident, short enough that the table does not grow without bound.

Not fixed: a concurrent burst can still exceed the login failure ceiling,
because the budget is checked, the password is verified, and the failure is
recorded afterwards. Doing it properly means claiming before verification and
refunding on success, and the sliding-window limiter has no release operation --
claiming without one would charge successful logins and lock out anybody signing
in more than ten times in fifteen minutes, which is worse than what it fixes. It
needs a new limiter primitive. The sharpest edge, each guess reserving 64MiB, is
closed by the concurrency bound added in the previous commit.

Verified: both build tags compile and vet clean, golangci-lint clean, console
eslint clean with no auth type errors under tsc -b, full suite green across 45
packages.
Eleven findings, eight of them about code added in the two commits before this
one. Three mattered.

The seed hashed the configured secret without applying the password policy, so
the compose default -- five characters -- would have become the persistent,
stored owner credential, walking past the rules the console refuses to let
anybody opt out of. password.Validate now runs before hashing on both the create
and the fill-a-missing-secret paths, and the shipped defaults are passphrases.
Validation happens only when a write is actually going to occur, so a deployment
whose account already has a password is not broken by a stale weak variable left
behind in its environment.

Every verifier error charged the login budget, including a failure to reach the
database. A Postgres outage would therefore have spent the account and source
budgets on ordinary attempts and left people locked out after it recovered --
the protection turning into the aftermath. Only a credential the verifier
actually turned down spends now.

SetAdminIdentitySecret reported success when it matched no row. An identity
unlinked concurrently meant a reset or change could go on to burn the outstanding
links, end every session and answer 204, reporting a password change that never
happened. It requires an affected row and returns store.ErrNoRows otherwise.

The rest:

  - Seeding was a read followed by a write across separate transactions, so a
    multi-replica cold start had both processes provision and the loser report an
    expected unique-violation as a fatal boot error. It holds the existing
    registration bootstrap advisory lock for the whole operation, in its own
    transaction so the writes underneath keep their own connections.
  - A half-configured seed pair was silently ignored: nothing created, and the
    operator finding out by not being able to sign in. One of the two set is now
    a startup error naming the one that is missing.
  - The public callback contract still accepted `password` as a driver, so
    generated clients exposed a route the verifier map always answers with 404.
    Enum reduced and both clients regenerated.
  - The registration endpoint's description named AUTH_PASSWORD_REGISTRATION,
    which nothing reads.
  - Two documented configuration snippets could not be copied: one used the
    removed driver and section, the other put an `html` field on a per-message
    template, where only copy lives. Both fixed, the second with a note on where
    markup does belong.
  - Register.tsx checked `!drivers` before rendering `error`, so a failed
    methods request hung on the spinner forever with the message it had set
    unreachable. An explicit failed state is checked first.
  - The compose comment told operators to switch to the webhook channel by
    setting two environment variables. That could not work: the network
    relaxations are YAML-only and the default policy rejects both plaintext HTTP
    and a private address, so it would have failed at boot. This adds
    etc/lunogram.mailpit.yaml carrying the policy, points the comment at it, and
    documents the constraint in the mail page rather than leaving it to be
    discovered.

Verified: both build tags compile and vet clean, golangci-lint clean, console
eslint clean with no auth type errors under tsc -b, generated clients in sync
with the spec, full suite green across 45 packages.
Remove internal/password/policy.go and every caller: the registration,
reset and change flows no longer validate a submitted password, and the
boot seeder no longer holds AUTH_BASIC_PASSWORD to it.

The OpenAPI schema and the console still declare the 12-1024 bounds, so
the constraint survives where it is advisory rather than enforced.
It is a local development dependency like postgres and redis, not part of the platform stack itself.
Replace the enterprise-gated invites screen with a Members screen that
manages the people on a project, not just the invitations to it: a roster
with inline role changes and removal, and pending invites, as two tabs.

The invite flow now delivers. Creating an invite mails the invitee through
the platform mailer rather than waiting for them to happen to sign in, and
the link carries a parameter that lands a stranger on sign-up instead of
sign-in. Invite expiry is a fixed 48 hours.

Drop email verification entirely. It gated the invite endpoints, the org
resolver, and the sign-up flow, and confirming an address bought nothing
the invite token did not already prove. Removing it uncovered three
consequences, each fixed here: invitees landed in a throwaway organization
because the resolver skipped unverified identities; accepting an invite
404'd because the active organization never followed; and a re-invited
member kept their old OpenFGA grant because a soft-deleted membership row
reads as absent. Project role grants are now set rather than added, so
re-accepting reconciles instead of accumulating.

Re-roling yourself asks first, since dropping below admin takes the screen
with it, and refetches the project afterwards rather than assuming the new
role -- an organization owner keeps project admin by inheritance.

The sidebar's stacked organization and project switchers become one
workspace control. Invite mails render durations through a real humaniser,
and mailer template kinds move to dotted names.
mail.webhook.network let a deployment relax the SSRF guards for the mail
endpoint. It carried its weight only in development, where it pointed the
channel at the Mailpit container over plaintext HTTP — and the SMTP channel
already reaches Mailpit without giving up a guard. The endpoint is now held
to https on a public address with no way to opt out, and a receiver inside
the deployment's own network is reached over SMTP.

Removes etc/lunogram.mailpit.yaml, which existed only to carry the two
relaxations, and the compose comment pointing at it.
Expiry is already a predicate at redemption, so the scheduled sweep was
only reclaiming rows. Fold that into token issuance -- the one path that
adds them -- scoped by index to a single admin and purpose, and the table
stays bounded without a background task to schedule, recover and observe.
The documentation still described the state before this branch: the SMTP
page opened on a roadmap note, the quickstart handed out a password that no
longer works, and nothing covered password sign-in or project membership at
all. Every page here states what the platform does rather than what changed.

Add two pages. Sign-in covers the login drivers, the seeded first account,
the registration modes, passwords and their throttles, and console session
signing and lifetimes. Members covers the roster, the project role
hierarchy, the least-privilege ceiling on granting one, and invitations.

Correct the mail reference. Email verification is gone, so the message set
is four rather than five and verify_email no longer names anything; the
webhook kinds are the dotted constants the platform actually sends, and the
invitation's ProjectName and InviterName were missing from the context.

Fix the /docs/ prefix on the internal links added with the new pages: the
site is served from the root, so every one of them was a 404. APP_SECRET
survived only in the README and is dropped with it.
The cost parameters have never been raised, and the PHC encoding already
keeps old hashes verifiable if they ever are. Everything built to act on
that day went with it: the outdated return from Verify, weakerThan, the
upgrade write in the basic verifier, and the compare-and-swap store
method it needed to lose a race against a concurrent password change.
It can come back as a batch job when there is a reason for it.

Fold HashWith into Hash, collapse usable() to one condition, and cut the
commentary down to what the signatures do not already say.

Keep the inFlight bound. Login is unauthenticated, so the rate limit
keys on client IP at 600/minute with no burst shaping; without the
semaphore one source can land enough concurrent argon2 calls to reserve
tens of gigabytes at 64 MiB apiece.
The azurite module's only readiness gate is wait.ForListeningPort, which
Docker's port proxy satisfies as soon as the container is created — before
the Node process inside binds and serves. The first request out of the test
binary then read a closed connection rather than a response, failing with
"EOF" or "server closed idle connection".

Only TestAzureStorageWrite ever failed, which is the test that boots the
container; every test after it found Azurite up and passed. CI hit it on two
of the last six runs.

Wait for an HTTP answer instead. Any 4xx to an unauthenticated, account-less
"GET /" means the blob service parsed a request and rejected it, which is the
only question being asked; a 500 keeps the probe retrying, so the matcher
fails in the safe direction.
feat(auth): multi-user email and password sign-in
The tests and tests-enterprise jobs were identical apart from their
final step, duplicating ~30 lines of setup. Collapse them into a
single matrixed job so the setup is defined once.

Name the matrix axis after the build it covers rather than the make
target, giving "tests (oss)" and "tests (enterprise)" instead of
"tests" and "tests-enterprise".

Drop the test-enterprise target in favour of a TAGS variable, which
removes the need for a separate ENTERPRISE_PKGS package list and lets
test-short run against the enterprise build too.
Bumps [nanoid](https://github.com/ai/nanoid) from 3.3.11 to 3.3.18.
- [Release notes](https://github.com/ai/nanoid/releases)
- [Changelog](https://github.com/ai/nanoid/blob/3.3.18/CHANGELOG.md)
- [Commits](ai/nanoid@3.3.11...3.3.18)

---
updated-dependencies:
- dependency-name: nanoid
  dependency-version: 3.3.18
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Bumps  and [brace-expansion](https://github.com/juliangruber/brace-expansion). These dependencies needed to be updated together.

Updates `brace-expansion` from 1.1.12 to 1.1.18
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](juliangruber/brace-expansion@v1.1.12...v1.1.18)

Updates `brace-expansion` from 5.0.4 to 5.0.9
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](juliangruber/brace-expansion@v1.1.12...v1.1.18)

Updates `brace-expansion` from 2.0.2 to 2.1.4
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](juliangruber/brace-expansion@v1.1.12...v1.1.18)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.18
  dependency-type: indirect
- dependency-name: brace-expansion
  dependency-version: 5.0.9
  dependency-type: indirect
- dependency-name: brace-expansion
  dependency-version: 2.1.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Bumps [next](https://github.com/vercel/next.js) from 16.1.6 to 16.2.11.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](vercel/next.js@v16.1.6...v16.2.11)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.2.11
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
The console installs exclusively with pnpm (Dockerfile, ci.yml,
release.yml), so package-lock.json was never used to resolve
dependencies. Keeping it tracked meant Dependabot maintained both
lockfiles in parallel, doubling the diff on dependency bumps.
* feat(metrics): serve the registry and instrument dataset queries

Two gaps, both invisible until you go looking for them.

The registry was never exposed. metrics.NewHandler() had no caller, so
roughly 35 carefully maintained metrics were collected in-process and
then dropped on the floor -- there was no endpoint to scrape. This
mounts the handler on its own listener, configured by METRICS_ADDRESS
(:9101 by default), and skips the public HTTP server on purpose: that
one mounts the console on a catch-all route and sits behind the public
ingress, so anything registered there is reachable from the internet.
A failure to bind is logged and swallowed rather than fatal -- a node
that cannot report metrics can still serve traffic perfectly well.

The rule-driven dataset queries had no instrumentation at all. Each of
them compiles a customer-authored ruleset into SQL, so their cost is
bounded by the customer's data rather than by anything we control, and
RecomputeList is the sharpest edge: it MERGEs a full match set against
list_users with no limit anywhere in the statement. When one of these
spikes today there is nothing to look at.

All four call sites now report duration, row count and failures under
lunogram_dataset_query_*, labelled by query and project:

  list_recompute        unbounded MERGE, the most expensive query we run
  list_preview          bounded by a limit, but someone is waiting on it
  gate_historical       cheap alone, runs once per user per gate
  organization_members  cursor scan over a rule

Rows are recorded as a histogram as well as a counter, because the
question worth asking is "did one query return a million rows", not
"how many rows did we return in total".

Three details worth flagging for review:

  * The duration buckets run to 120s rather than reusing DefBuckets. A
    recompute over a large project is expected to take tens of seconds
    and DefBuckets tops out at 10, so every interesting query would
    pile into the overflow bucket -- precisely the ones worth alerting
    on.
  * project_id is a label, matching the existing journey metrics. It is
    what turns "something spiked" into "this customer's segment
    spiked", at the usual cardinality cost.
  * ScanOrganizationMembers moved to named returns so the observation
    can be deferred. Rows stream, so most of the query's cost is paid
    while iterating, not in the call that opens the cursor -- timing
    only the latter would have measured almost nothing.

Noted but deliberately not changed: evaluateHistoricalRules treats a
query failure and a non-match identically (err == nil, nil), so a
database error silently reads as "the gate did not match". The
instrumentation follows the existing behaviour rather than quietly
altering control flow in a journey hot path, and does not report those
as errors. Worth a separate look.

Dashboards for all of this are in cloudproud/lunogram.cloud#14.

* fix(metrics): observe the query rather than what surrounds it

Three gaps from review, all of them the instrumentation describing
something other than the query it claims to measure.

A gate whose database is down reported success. GetContext returns
sql.ErrNoRows for a miss and something else for a failure, but every
result was observed as nil, so an outage in the hottest of the four
paths read as a run of quiet non-matches. Only non-ErrNoRows errors now
count. The caller still cannot tell the two apart -- that is existing
behaviour in a journey hot path and is left alone -- which is precisely
why the error series has to.

ScanOrganizationMembers timed its callback. Both callers publish to NATS
for every row, so broker latency was reported as database latency and a
failed publish as a failed dataset query. The callback's time is
subtracted and its failures are no longer the query's.

ObserveDatasetQuery takes a duration instead of a start time, which is
what lets that subtraction happen at the call site.

The endpoint test never called Serve. It built its own mux, mounted the
handler by hand and would have stayed green through a listener that
never registered /metrics or never shut down. Serve now splits at the
listener so a test can drive the real path: both tests fail if the route
moves, and the shutdown test fails if the closer is not registered.
)

* feat(config): configure the deployment's OpenID Connect provider

AUTH_OIDC_* sits beside AUTH_BASIC_* and AUTH_CLERK_*: one provider serves
the whole deployment, selected with AUTH_DRIVER like every other login
method.

The issuer is taken verbatim. OpenID Connect issuer identifiers are
compared exactly, trailing slash included, so normalising it would break
every provider that publishes one.

The defaults live in Defaults() rather than in envDefault tags, because a
tag default is written over a configuration file whenever the variable is
unset. auth.oidc is pinned by its own test rather than against
testdata/defaults.json: the driver did not exist when that snapshot was
captured, so it has no former tags to match.

* feat(sso): cache provider metadata and hold authorization flows

Two pieces the login needs and HTTP does not own.

Discovery binds a document to its issuer twice over: it must be served by
the issuer's own origin and must name the issuer as its own. Without both,
whoever chooses the discovery URL chooses the token endpoint and the JWKS,
which is to say they can mint an ID token for any issuer they like. The
cache is keyed on the pair rather than the URL alone, so a document checked
for one issuer is never served to another.

Every endpoint the document advertises is validated under the deployment's
outbound policy before it is used. The document -- not the operator -- is
what names the token endpoint and the JWKS, so a plaintext token endpoint
or a JWKS pointed inside the network is refused there.

The flow store keeps the nonce, the PKCE verifier and the browser binding
server-side under a ten-minute TTL, read with GETDEL so a state parameter
is redeemable exactly once. Redis rather than process memory because a
login starts on whichever replica answered /start and finishes on whichever
answers /callback.

* feat(auth): sign in with the deployment's OpenID Connect provider

AUTH_DRIVER=oidc offers a federated login beside the existing ones. Like
every other verifier it stops at the proof: it resolves no admin, creates
no organization and mints no session, and an admin provisioned through it
lands exactly where one provisioned through Clerk does.

What it adds over the others is the challenge half of the exchange. A
redirect-based credential is only provable if the same component issued the
challenge, so Authorize mints the state, nonce, PKCE verifier and browser
binding that Complete later checks the response against.

The binding is the part that is easy to leave out. The state parameter is a
bearer value: without a second value tied to the browser that started the
login, somebody could authenticate as themselves, stop before following the
callback, and hand that URL to another person, whose browser would then be
given the attacker's session. It is a Secure, HttpOnly, SameSite=Lax cookie
-- Lax rather than Strict because the browser arrives back by top-level
navigation, which Strict would strip the cookie from.

redirect_uri derives from PUBLIC_URL and never from a request parameter,
and the post-login redirect comes from the stored flow and is reduced to a
same-site path. Signing algorithms are an allow-list (RS/ES/PS) rather than
whatever the issuer advertises, so an issuer announcing "none" cannot cause
a non-signature to be verified. EmailVerified requires the provider's own
claim, because that is the flag the exchange links identities by.

The driver is refused at boot when AUTH_DRIVER names it without an issuer,
client id and client secret: the failure is a variable nobody set and it
should read that way. The generic login callback refuses it too, since it
completes at /api/auth/oidc/callback and answering it in two places would
be two surfaces for one credential.

* test(auth): cover the federated login end to end

Against an OpenID Connect provider on loopback -- a discovery document, a
JWKS, and a token endpoint that mints whatever the test asks it to. Nothing
reaches the network, and the stub enforces the PKCE challenge itself, so a
flow that forgot to send the verifier fails exactly where a real provider
would fail it.

The rejections are the point: a callback answered in a different browser, a
callback carrying somebody else's binding, a replayed state, a nonce that
answers no login, a token minted for another audience or by another issuer,
an expired token, a token response with no id_token, and a provider that
refused outright. Each has to leave no session behind.

* feat(console): offer single sign-on on the login page

One button. The deployment has one provider, so there is nothing to choose
and no address to type before choosing it -- pressing it navigates to
/api/auth/oidc/start, which is a full-page navigation rather than an XHR
because the browser has to follow the redirect and come back with a cookie.

A failed login bounces back here with a coarse reason in the query string:
enough to say something true, never enough to describe the deployment's
identity provider to a stranger.

* docs: describe the OpenID Connect driver

Registering the application, the three variables that turn it on, the
claims and scopes that have defaults, and what happens when the driver is
named without them. The redirect URI is spelled out because most providers
reject a mismatch outright.

The README's inherited "SSO (SAML/OpenID) out of the box" claim is now
accurate: OpenID Connect is provided, SAML is not and will not be.

* feat(auth): sign in with any of the deployment's providers

A deployment picks one of two configuration forms. AUTH_OIDC_* configures a
single provider and is what a compose-only deployment can express;
auth.oidc.providers declares a list in the configuration file, where ${VAR}
references keep the secrets in the environment. Setting both is refused
rather than merged, because there is no order in which one obviously wins.
The single form is given the id "default", which is not cosmetic: the id is
half of the redirect URI an operator registers with their provider.

Claims, scopes and allowed domains are per provider, so the claim defaults
move out of Defaults() and into the verifier, which is the only place that
can apply them to each one.

The provider is a path segment -- /api/auth/oidc/{provider}/start and its
matching callback -- so each has its own redirect URI to register.
GET /api/auth/oidc/providers names them for the login page.

The set is deliberately not in the verifier map. A federated credential
arrives as a browser navigation naming a provider, which the generic "prove
what is on this request" contract has no room for, and keeping it out is
what makes the ordinary login callback answer 404 for oidc without a
special case asking it to. Every provider is built at boot, so a deployment
offering four ways in does not discover on a Monday morning that one of
them was never going to work; ids must be unique and usable in a URL path.

A flow records the provider it was started with, and the callback refuses a
state that names a different one. The state is a value the browser carries,
so without that check one issued for provider A could be redeemed at B's
callback and proved against B's issuer and client id.

allowed_domains bounds what a provider may assert. It is the boundary
between providers rather than a proof of ownership: a verified address
links a login to an existing admin whichever provider asserted it, so
without it the least trustworthy provider decides who can reach every
account.

Three corrections to this branch's earlier rounds ride along, because they
are the same code:

- The binding cookie is read only under the name this request's scheme
  would have set. Falling back to the unprefixed name on a secure request
  let a sibling subdomain write a binding with Domain=... and hand the
  victim's browser the attacker's flow, which is the whole thing the
  binding prevents.
- The flow is redeemed and its binding checked BEFORE the provider's own
  error parameter is read. An authorization error carries a state too, so
  reading it first reported an unknown or already-spent state as a genuine
  denial and skipped the binding check entirely.
- UserInfo is fetched when the ID token omits the address OR its
  attestation, not only the address. A provider may return email_verified
  there and the address in the token, and skipping the fetch then left
  every such login unlinkable to an account that already exists. An
  attestation is only accepted for the address it accompanies, and a null
  is treated as no answer rather than as a negative one.

* test(auth): cover several providers and the browser binding

Two stub providers on loopback, so a state issued for one and redeemed at
the other's callback is a real request rather than a mocked one. The cases
that matter: each provider signs in its own people, a provider may not
assert a domain outside its allow-list, an id nobody declared is absent,
and a cross-provider state is refused.

The binding cookie gets a secure-request test, because the hole it closes
-- an unprefixed cookie planted by a sibling subdomain -- is invisible over
plaintext, which is what the other tests run on.

A nil claim override now omits the claim rather than emitting a null, which
is what a provider that simply does not send it looks like. Writing that
found the production nuance beside it: present-and-null was being read as
an attestation.

* feat(console): let people pick a provider

One button when the deployment configured one provider, a button per
provider by name when it configured several. The list is fetched only once
GET /api/auth/methods says the driver is offered, so a deployment without
single sign-on makes no call that would 404.

* docs: describe several providers

The YAML form, what an id is for -- it is half of the redirect URI, so it
cannot change without re-registering -- and why allowed_domains exists once
there is more than one provider to bound.
…kens (#272)

* feat(auth): surface debuggable reasons for rejected issuer/session tokens

External JWT failures (trusted issuer and Lunogram sessions) all collapsed
into a single bare "unauthorized", so an integrator could not tell a
malformed token (e.g. a missing `exp` claim) from a wrong signing key.

Surface a precise reason — but only once the token has proven to be
authentically ours, so we never leak whether an issuer or project exists:

- Trusted issuer: a reason is returned only after the token's `iss`
  resolves to a configured issuer. Failures before that (empty/unparseable
  token, unknown issuer) stay a generic ErrUnauthorized.
- Session: a reason is returned only after the ES256 signature verifies
  (golang-jwt validates claims strictly after the signature). Signature,
  signing-method, and format failures stay ErrUnauthorized so the auth
  chain still falls through to the trusted-issuer handler.

The HTTP status is unchanged (still 401 via SecurityRequirementsError);
only the problem detail gains a specific, fixable message such as
`token is missing the required "exp" claim` or `token has expired`.

* fix(auth): keep rejections generic until a token proves authentic

Resolving a trusted issuer only proves the token's self-asserted `iss`
names a configured issuer: `iss` is read with ParseUnverified, so anyone
can forge it. Describing the failure at that point let an unauthenticated
caller tell a configured issuer from an unknown one, the very
issuer-existence oracle this change set out to avoid.

Gate the trusted-issuer reason on jwt.ErrTokenInvalidClaims, which the
parser reaches only after the signature verifies against the issuer's
keys, mirroring what the session path already does. Signature, key and
format failures stay a bare ErrUnauthorized.

describeTokenError loses its signature branch: no caller can reach it now,
and keeping a helper able to emit that message invites a future caller to
leak it.

Restore the missing-`iss` session case dropped in the previous commit; it
covers requiredClaimReason naming the reported claim instead of falling
back to its exp-centric message.
…e backend (#285)

The management backend serves only what's in the OpenAPI spec (the oapi
router plus a request-validator middleware reject off-spec paths). Several
endpoints still called through the legacy axios `api.ts` client have no
matching spec path, so they 404 against the current backend. This removes
them and the now-orphaned UI that called them, as a first step toward
retiring `api.ts` entirely.

Removed from api.ts (no callers; not in spec):
- data.userPaths / data.rebuild  (data/paths/users, data/paths/sync)
- resources.*                     (resources)
- tags.*                          (tags, tags/used, tags/assign)
- lists.recount                   (lists/{id}/recount)
- users.lists                     (subjects/users/{id}/lists)
- organizations.members.*         (subjects/organizations/{id}/members)
- journeys.steps.searchUsers      (journeys/{id}/steps/{id}/users)
- journeys.entrances.*            (journeys/{id}/entrances, journeys/entrances/{id})
- journeys.users.skipDelay / removeFromJourney  (steps/{id}/resume, step/{id})

UI removed (reached only via the above, all backed by dead endpoints):
- EntranceDetails + JourneyUserEntrances pages and their orphan routes
- JourneyStepUsers panel and the step-sidebar "view users" click-through
  (the step stats card itself is kept, now non-interactive)

Kept: journeys.users.getState (in spec, used by the editor), path
suggestions, and locales.getByKey (still in use; to be migrated separately).

tsc + eslint clean, journey unit tests pass, production build succeeds.
…ary (#323)

start_at was exactly two 7-day intervals back, so the occurrence the
store computes lands on the instant the test captured. next_schedule_
occurrence returns the first occurrence strictly after the DATABASE's
clock, and the assertion compares against this process's -- so a
database a millisecond behind returns that instant rather than the one
after it, already past by the time it is read. The margin between the
two clocks was zero by construction.

Ten days against a seven-day interval puts the occurrence four days out
and the one before it three days back, which survives a full day of skew
either way. Verified against next_schedule_occurrence directly: the old
anchor flips at 1ms of lag, the new one holds at 86400s.

Seen as intermittent failures of TestUpsertUserScheduledRecurring and
TestUpsertOrganizationScheduledRecurring, which is the same pair once at
the store level and once through the controller.
* ci: pin the test runner to ubuntu-24.04

On the ubuntu-26.04 image that ubuntu-latest now resolves to, the runner is shut down mid-test (exit 143). Every test job on 24.04 passes. Same change as in #339, split out so main and other branches get it now.

* test(pubsub): bootstrap jetstream once per test binary

Every parallel controller test re-created the same default-namespace streams and consumers on the shared NATS container. Under -race with -p 4 one of those JetStream calls occasionally exceeded its 5s default timeout, failing setup with "context deadline exceeded" (TestImportUsers, TestListOrganizationSchemasWithMultipleTypes).
WebhookRequest.Body was a json.RawMessage, so the host's json.Marshal
compacted it and HTML-escaped & < >. Signatures computed over the raw
body (AhaSend, Resend) then fail for any payload holding those
characters, and form-encoded bodies (Twilio) failed to marshal at all.
Body is now []byte, base64-encoded on the wire.
* docs: add AGENTS.md for coding agents

Entry point covering the repository map, security and data guardrails, generated code, console conventions, validation, and PR expectations.

* docs: base AGENTS.md on the Brainpod agent guide

Mirror Brainpod's sections and working rules, adapted to Lunogram's components, guardrails, and tooling.

* docs(agents): address review findings in AGENTS.md

- Require numeric migration versions above the schema's highest; golang-migrate skips lower ones
- Treat an explicit fix instruction as review-batch approval; stop when no user can respond
- Document replacing screenshots via --body-file; --attach shipped in gh 2.99
- Add module, docs, and TinyGo prerequisites to Validation
- Clarify oapiClient call sites and commit scopes
Add GET /api/admin/auth/key, which returns the calling API key's id, name,
project, organization and role. Every other management endpoint either
names the project in its URL or is reserved for admins, so a caller
holding only a key had no way to discover which project to address.

The key learns only about itself, so no permission check is needed beyond
authentication. Admins and other actors are refused with a 403. The role
is read back from the auth method rather than the actor, which does not
carry it; a key revoked since the auth cache was filled gets a 404.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Jeroen Rinzema <jeroen@rinzema.dev>
@jeroenrinzema

Copy link
Copy Markdown
Contributor Author

Superseded: main conflicts with the rebased commits on release/v0.1.0; opening from a branch that merges them first.

@jeroenrinzema jeroenrinzema mentioned this pull request Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants