Skip to content

feat(auth): packages/auth on Effect - #85

Merged
allisonmahmood merged 2 commits into
mainfrom
feat/auth-package
Aug 29, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
feat/auth-package

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Tokens, principals, self-service minting with its quota, revocation and bearer parsing were spread across packages/db (internal-principals.ts, mint-quota.ts, the Postgres driver) and apps/server/src/app.ts, so the auth capability had no home the port could build on.

They are now one Effect capability package, @patchy/auth: a Tokens service over @effect/sql-pg (row decoding through SqlSchema in one module, sql.withTransaction for the mint, the quota counted inside it), the accounts / api_tokens / token_mints baseline as migrations 1–2, the server side of the Authorization middleware, and the auth HttpApi group built with HttpApiBuilder.group. Minting reports through @patchy/analytics and spends its per-minute limit through @patchy/limits. Tests run on it.layer over a migrated database and HttpApiTest.groups(PatchyApi, ["auth"]) with good/bad bearer client layers, the 401 body asserted; the auth cases left app.postgres.test.ts and the db contract suite. Terms moved to packages/auth/CONTEXT.md; language-service warnings are errors for the package.

Interim seam: the Fastify app serves the group's four routes by handing the request to the auth handlers through the runtime, and authenticates every protected request through Tokens. The JSON driver keeps its token store behind the same Tokens interface (jsonTokensLayer) until the patches port deletes it, so the packed-CLI e2e still runs against the Fastify server on the JSON driver. The draft migrations renumber to 3 onward. last_used_at and accounts.self_service_minted_at are not in the rewritten baseline: nothing read them, and the mint record carries the provenance.

Stacked on #84 (feat/analytics-limits).

Closes #74

Built by Claude Fable 5 via Claude Code.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:l 501-1,000 changed lines labels Aug 29, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Two-axis review of feat/auth-package against feat/analytics-limits (c9c05c4...d047ee9), plus the extra axes asked for: issue #74 intent vs what landed, the method, and YAGNI. UI consistency does not apply (no served HTML/CSS).

Standards

Auth’s own modules follow the Effect service spec: subpath namespaces, inline Context.Service interfaces, yield* deps, Schema.TaggedError (this RC has no TaggedErrorClass; matches analytics and AGENTS.md), Effect.catchTags including single tags, it.layer / it.effect / HttpApiTest.groups / TestClock, no mocks, no "effect" barrel imports, no standalone FooShape. runPromise / ManagedRuntime sit at start.ts, runtime.ts adapters, migrate.ts, and test harnesses — legitimate seams.

Hard

  1. jsonTokensLayer renames layer — packages/db/src/json-tokens.ts:14; barrel packages/db/src/index.ts:5 export * from "./json-tokens.js".
    Standard: .agents/skills/effect-service-conventions/SKILL.md Imports and module namespaces — a concrete implementation module already named for the implementation uses plain make / layer; barrels export * as JsonTokens; do not rename layer to fake a namespace.
    Fix: export const layer = (db) => …; export * as JsonTokens from "./json-tokens.js"; callers JsonTokens.layer(db).

Judgement

  1. Layer.succeed over a Promise store — json-tokens.ts:15-69. Methods wrap Effect.promise(() => db.…), and the mint quota uses JsonFilePatchyDb’s clock, not Clock.
    Standard: Dependency acquisition — don’t hide imperative APIs in Layer.succeed.
    Override: this is the documented JSON seam the patches port deletes. Do not invent a JsonDb service. Optional: count the window with yield* Clock.currentTimeMillis so TestClock works on JSON too.

  2. AuthApiHandler has no make; runtime.ts mixes a service with Promise adapters — apps/server/src/runtime.ts:27-54 vs 61-122.
    Standard: Service definition (make then layer). Smell: Divergent Change.
    Fix: extract make = Effect.map(HttpRouter.toHttpEffect(AuthApi.routes), Effect.orDie). Leave the Fastify adapters; they are the seam.

  3. Two authentications per auth-group request — Fastify authenticateApiRequest (app.ts:834-843) then serveAuthApi → Authorization.bearer (Authorization.ts:19-21).
    Smell: Duplicated Code. Expected until serving mounts the API; not a redesign ask.

Spec

Against issue #74. “One file each” is a legitimate reading of one file per service: Tokens owns mint+quota+lookup+revoke; Bearer.ts is a pure helper; Authorization.ts is the middleware. The Fastify seam was asked. AuthOnlyApi / refuse are seam machinery, not product creep.

(a) Requirements missing or partial

“No auth logic remains in packages/db.” Postgres token methods are gone. JSON still is the token store: json-db.ts:152-279 still authenticates, mints, counts quota, and revokes; json-tokens.ts:14 is a Tokens layer over that. The PR body names this as the packed-CLI interim until the patches port deletes the driver — so this is done differently, not a silent miss, but the letter of Done-when is not met.

Auth-group handlers did leave app.ts (app.ts:188-227 → serveAuthApi). Bearer.parse + Tokens.hasScope remain for unported patch routes. That matches the asked Fastify seam.

HttpApiTest is in place (AuthApi.test.ts: HttpApiTest.groups(PatchyApi, ["auth"]), bearer("dev-token") / bearer("nope"), 401 body asserted). Postgres auth-only cases were split out of app.postgres.test.ts. Packed-CLI e2e was not re-run in this review; the JSON wiring looks sufficient (openPatchyDb → jsonTokensLayer).

(b) Behaviour the spec did not ask for

last_used_at / accounts.self_service_minted_at dropped from rewritten migrations 1–2 (packages/auth/src/migrations.ts:20-34). Spec asked to rewrite the baseline, not to drop columns. The PR body argues nothing read them; that is a product cut, not a listed #74 requirement.

(c) Looks implemented, looks wrong

Dropping those columns is inconsistent across drivers: JSON still writes lastUsedAt on every authenticate (json-db.ts:161) and selfServiceMintedAt on mint (json-db.ts:223). postgres-db.ts:99-104 still talks about last_used_at and token_mints.created_at as this driver’s stamps; Postgres no longer owns either.

Bearer parsing vs middleware. Spec puts parsing in auth. Authorization.ts:17 authenticates HttpApiSecurity.bearer’s credential and never calls Bearer.parse. Fastify still uses the custom parser; the group’s middleware (the serving replacement) does not.

Effect’s decoder (getAuthorizationCredential) requires a space after Bearer (RFC 9110 1*SP) and keeps trailing whitespace. Bearer.parse allows spaces or tabs and strips trailing whitespace — which is the contract in packages/auth/CONTEXT.md. So Authorization: Bearer\ttoken or Bearer token authenticates on Fastify-guarded routes (upload, and the prefix guard on /api/me) then 401s inside serveAuthApi. The CLI’s Bearer ${token} is fine; the documented contract is not. Dual lookup also means a revoke between the two reads can 401 after the protected-API bucket was already spent.

Method

The ticket asked for a capability package, Effect services, SqlSchema in one module, HttpApiBuilder.group, Authorization.of({ bearer }), sql.withTransaction for mint, analytics + limits from those packages, a Fastify runPromise seam, and it.layer + HttpApiTest.groups with two bearer client layers. That is what was built.

Choice Verdict
One Tokens service, not one service per verb Sound. Mint quota is a count inside sql.withTransaction; a Quota service would split one atomic write.
Fastify seam in runtime.ts Acceptable interim. One process-owned ManagedRuntime; runPromise / runFork only there and in start.ts. Not a new framework. serveAuthApi rebuilds a Fetch Request from an already-parsed Fastify body.
jsonTokensLayer inside packages/db Acceptable interim. Unported db consumes ported Tokens. Putting the adapter in auth would invert the dependency. The letter of “no auth logic in db” is bent until the driver dies.
Migrations 1–2 / drafts 3+ Sound. Global sequence, plain DDL, no IF NOT EXISTS.
AuthConfig Sound. Effect Config per capability; bootstrap is Redacted. Duplicates packages/config until that package is deleted.
Domain MintQuotaExceeded → wire body; SqlError: Effect.die Sound. Matches “map domain errors at the handler; don’t let an untyped failure pick a status.”
Bootstrap seeding in Tokens.make Acceptable interim. Idempotent; start.ts forces runtime.context() so it happens at boot. JSON still seeds in initialize.
vs analytics/limits Sound. Same grain; HttpApiBuilder / SqlSchema / HttpApiTest are what this ticket added.

Worst method risk: dual Fastify+Effect dispatch for the auth group. HttpApiTest never goes through serveAuthApi; live 401s on /api/me and token routes are Fastify’s first. Serving will unmask whether Authorization.bearer actually holds on the socket. The tab/trailing-space parser split is the concrete form of that risk today.

YAGNI

The domain got smaller. The seam paid Effect rent. Most of that rent is the port’s required shape, not invention.

  • Collapsing mint+quota+authenticate+revoke into Tokens is the small model. Splitting further is machinery with no second consumer.
  • AuthOnlyApi is one line so HttpApiBuilder.layer can serve a group while PatchyApi still has unimplemented patches. It dies with the Fastify seam. Not a second contract.
  • refuse + SchemaAST.resolveAt("httpApiStatus") exists because Forbidden and NotFound share { ok, error } on the wire; the named schema is the only thing that picks the status. Old Fastify did the same via sendWire.
  • Dropping unread last_used_at / self_service_minted_at from the Postgres baseline is YAGNI-correct. Leaving JSON still writing them is the leftover, not the drop.
  • Comments: rolling-day vs calendar, IS NOT DISTINCT FROM null IPs, the revoke CTE, mint-guard order are real invariants. A few file-level essays restate CONTEXT.md. Same house style as analytics/limits; thin later, don’t block.

YAGNI pass. Worst excess is narrative comments, not extra services.


Standards: 1 hard, 3 judgement. Worst in-axis: jsonTokensLayer renaming layer.
Spec: 1 partial, 1 unasked, 2 implementation-wrong. Worst in-axis: Bearer.parse vs HttpApiSecurity.bearer on the auth-group seam.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Went through the review. Pushed the fixes as one follow-up commit; lint, typecheck and the full suite (455) are green.

Fixed

  • jsonTokensLayer renamed layer (Standards, hard) — now JsonTokens.layer(db), barrel export * as JsonTokens; callers in factory.ts and apps/server/src/testing.ts updated.
  • AuthApiHandler without make — runtime.ts now has make = Effect.map(HttpRouter.toHttpEffect(AuthApi.routes), Effect.orDie) ahead of layer. The Promise adapters stay; they are the seam.
  • Bearer.parse vs HttpApiSecurity.bearer (Spec, the real one) — Authorization.bearer now reads HttpServerRequest.headers.authorization through Bearer.parse instead of the scheme-decoded credential, so the Fastify guard and the API group accept exactly the same forms (Bearer\t token \t authenticates in both). Added an HttpApiTest case sending that raw header. This also gives Bearer.parse its second consumer inside auth, which is where the spec put parsing.
  • Stale Postgres driver comment naming last_used_at / token_mints.created_at as its own stamps — rewritten.

Not changed, with reasons

  • Layer.succeed over the JSON store / JSON still writing lastUsedAt and selfServiceMintedAt — the JSON driver is deleted by the patches ticket (feat(patches): packages/patches with the sweep and the patch rename #76); its internals are not worth touching once. The adapter is documented as that seam.
  • Two authentications per auth-group request — expected until serving mounts the API and the Fastify guard goes; the second lookup is the group's own middleware, which is what survives. The revoke-between-reads window is a 401 after one protected-API debit, i.e. what a revoked token gets anyway.
  • Dropped last_used_at / accounts.self_service_minted_at — the baseline is rewritten by owner (spec §3, no production database), nothing read either column, and token_mints carries the provenance. If you want them back it is two lines in migration 1; say so and I will add them.
  • Comment volume — house style of the ported packages; will thin with serving if you want.

Ready to merge on green CI (base is #84).

Base automatically changed from feat/analytics-limits to main August 29, 2026 23:13
Tokens, principals, self-service minting with its quota, revocation and
bearer parsing were spread across packages/db and apps/server/src/app.ts.
They are now one Effect capability package, @patchy/auth: a Tokens service
over @effect/sql-pg with SqlSchema row decoding and sql.withTransaction for
the mint, the accounts/api_tokens/token_mints baseline as migrations 1-2,
the server side of the Authorization middleware, and the auth HttpApi group
built with HttpApiBuilder.group. Minting reports through @patchy/analytics
and spends its per-minute limit through @patchy/limits.

The Fastify app serves the group's four routes through the runtime seam and
authenticates every protected request through Tokens; the JSON driver stands
in for the Postgres tokens layer behind the same interface until the patches
port deletes it. The draft migrations renumber to 3 onward.
JsonTokens.layer replaces the renamed jsonTokensLayer export; the auth
handler in runtime.ts gets a make; the Authorization middleware reads the
header through Bearer.parse so the Fastify guard and the API group accept
the same forms (tabs, trailing whitespace); a stale clock note in the
Postgres driver stops naming columns it no longer owns.
@allisonmahmood
allisonmahmood merged commit 6c798c3 into main Aug 29, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the feat/auth-package branch August 29, 2026 23:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(auth): packages/auth on Effect

1 participant