Skip to content

feat(companies): make patches belong to users, not tokens - #148

Merged
allisonmahmood merged 2 commits into
mainfrom
auth/137-companies-users-machine-tokens
Sep 6, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
auth/137-companies-users-machine-tokens

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Patches belonged to the token that created them, with no user or company behind the credential. Replacing a key should not change who owns a patch.

Companies and users now own the data, while expiring, revocable machine tokens act for a user. The API and CLI use that identity, and development, tests and packed e2e share one seeded company, admin and machine token. Bootstrap and self-service credentials are removed; the docs and company-authority ADR describe the new model.

Stacked on #147 (auth/136-remove-operator-routes). This PR targets that branch, not main. Clerk login, browser pages and sharing enforcement remain in later tickets.

Closes #137.

Verification

  • pnpm test: 167 tests passed across 27 files.
  • pnpm lint, pnpm typecheck and packed CLI e2e passed.
  • Real pnpm dev identity and upload verified; published GET returned 200.
  • Developer Clerk-user override and default seed restoration verified.
  • Standards and spec review complete; the seed-override finding was fixed and confirmed resolved.

Implemented with GPT-6 Astra using the Oh My Pi harness.

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

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed e304811 against origin/auth/136-remove-operator-routes (6fceca5) using git diff origin/auth/136-remove-operator-routes...HEAD, with issue #137 as the spec. One pass, no subagents; merge blockers only.

Standards

No merge-blocking method or YAGNI findings.

Spec

No merge-blocking intent findings against #137. Clerk login, browser pages and sharing enforcement belong to later tickets, not this PR.

Verification: 67 tests passed across 10 focused files covering Companies, Users, MachineTokens, AuthApi, Patches/PatchesApi, CLI, API guard/server and developer-env behavior. The lockfile's package resolutions are unchanged; its semantic changes are confined to the affected workspace importers. Full-suite, lint, typecheck and packed-e2e verification were not rerun in this review.

Summary: Standards: 0 blockers, no worst issue. Spec: 0 blockers, no worst issue.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 148 vs #137

Reviewed e304811 against auth/136-remove-operator-routes (6fceca5), the stacked base on #147. Spec source is #137, with parent #135 §1–§6, §11, §12.

Eight parallel reviewers: Standards, Spec, issue-137 intent, implementation method, YAGNI, Companies/Users, Auth identity, and hit-every-surface. Standards and Spec stay separate on purpose.


Standards

ui-consistency: N/A (no product HTML/CSS). Effect services otherwise match .agents/skills/effect-service-conventions/SKILL.md: namespace barrels, inline Context.Service, make/layer, yield* deps, Schema.TaggedError + Effect.catchTags, no runPromise in domain make.

Documented-standard violations (hard)

1. POST /api/logout has no CLI surface
Standard: CLAUDE.md Hit every surface (wire contract + reverse states); ADR-0004 (whoami/upload/delete print the @patchy/api wire shape).

packages/api/src/api.ts and packages/auth/src/AuthApi.ts add logout; docs/API.md follows. packages/cli/src/commands.ts has no logout; README and skills/patchy/SKILL.md are silent. auth set has no revoke/forget counterpart.

Fix: add patchy logout (or auth logout) that POSTs /api/logout, drops the stored key, and prints LoggedOut under --json.

2. Auth no longer reports analytics; token.minted is leftover
Standard: CONTEXT-MAP.md (“Auth, Patches → SQL, Analytics: both … report business events”); Analytics CONTEXT.md (“a token minted”); Hit every surface (vocabulary).

Mint removal left AuthApi with no Analytics calls. packages/analytics/src/Analytics.ts still unions "token.minted" and still describes CLI/server mint. No emitter remains.

Fix: drop token.minted and mint wording, or emit a real auth event (logout) so the map stays true.

Judgement-call smells (never hard; repo standards override)

Feature Envy — packages/companies/src/Users.ts updates Auth’s machine_tokens inside Users.deactivate even though MachineTokens.revoke exists. Partially licensed by CONTEXT-MAP (“services own deactivation”) and the same-transaction comment:

UPDATE machine_tokens SET revoked_at = to_timestamp(...)
WHERE user_id = ${input.userId} AND revoked_at IS NULL

Duplicated Code — user column list copied in Companies.ts and Users.ts.

Speculative Generality

  • apps/server/src/ApiGuard.ts empty UNAUTHENTICATED_PATHS “until device login lands”
  • packages/auth/src/migrations.ts device_logins table with no service
  • Invite.clerkInvitationId always inserted null
  • Companies.layer / Users.layer never composed in apps/server/src/Server.ts (tests only; CONTEXT.md owns the operations)

Spec

(a) Missing or partial

PATCHY_PUBLIC_BASE_URL default still in code. Spec §4 Config deletes “the PATCHY_PUBLIC_BASE_URL default” with the bootstrap/self-service settings. packages/patches/src/PatchesConfig.ts still Config.withDefault("http://localhost:3000"). Ticket 137 implements §1–§6. (Refusing boot without Clerk keys is §7 / later; this leftover default is still a §4 miss.)

Nothing else in-scope is missing. Viewer, InviteMail, device-login routes, upload/share scope, Session/@patchy/auth/testing belong to later tickets.

(b) Scope creep

None material. Extra reserved handles match §3 (“plus a short list of obvious words the build fixes as one constant”). Invite consume/revoke/list and Users.list are the data-model surface the uniqueness/last-admin tests need. device_logins DDL with no DeviceLogins service is §3’s rewritten auth baseline.

(c) Implemented but wrong

None found against the ticket checklist.

  • §3 tables: 0001_companies_baseline / 0002_auth_baseline / 0003_patches_baseline; TEXT+CHECK on role, state, scope; ids cmp_/usr_/inv_/tok_; live-invite partial unique index; no accounts/api_tokens/token_mints; pinned_at gone; created_by_machine_token_id NOT NULL.
  • Companies/Users: handle rule + RESERVED_HANDLES; findByClerkId, findByEmail, refreshClaims, setRole, deactivate, reactivate; last-admin via company FOR UPDATE; deactivation revokes tokens in the same transaction; reactivation does not restore keys.
  • MachineTokens.authenticate: one join across machine_tokens/users/companies; unknown, revoked, past expires_at, idle >30 days, deactivated user all return null → the same 401; hourly last_used_at on the test clock.
  • Wire: GET /api/me is the §5 Identity (no kind); POST /api/logout is { ok: true, alreadyRevoked }; guard unauthenticated path list is empty.
  • CLI whoami: User / Company: Patchy Dev (patchy-dev) / Role / Machine; --json is Identity. No-key upload/delete name patchy auth set --api-url <url>.
  • DEV_SEED: Patchy Dev / usr_dev / Clerk user_dev / patchy-dev-token. No leftover acct_, api_tokens, dev-token, or PATCHY_BOOTSTRAP_API_TOKEN.
  • Invites unique per company+email among live rows; two handle creates leave one company — index + tests.
  • ADR-0007: Patchy table, not Clerk Organizations; 20-member cap / B2B add-on; exactly-one-company and last-admin stay Patchy’s; Organizations return with SSO.
  • Glossaries: six mint-era Auth terms gone; Handle/Deactivation/Reactivation; Owner/Version/quota/retention freeze sentence; Auto-mint/Mint announcement gone; publishing key is the machine token; map Auth→Companies and ADR-0007.

Intent vs what landed

#137’s intent is a product substitution, not a table dump: stop treating a token as a principal. A patch belongs to a user in a company. A machine token is the credential that acts for them. Replacing a key must not change ownership. Self-service minting and the bootstrap token go now so nobody invents a replacement credential. Until patchy login, auth set and the seeded patchy-dev-token carry every caller. One seed so pnpm dev, vitest, and packed e2e publish as the same person.

That substitution is in the running system. Ownership checks owner_user_id. Quota is PATCHY_LIVE_PATCHES_PER_USER and survives a second machine of the same user. Versions name created_by_machine_token_id. whoami prints user, company, role, machine. Mint routes, --anonymous, and bootstrap config are gone. ADR-0007 records Patchy holding the company.

Drift is sequencing, not a different model. Slightly ahead: invite consume/revoke and claim refresh already exist for the pages ticket. Slightly behind, and named as such: scope is written 'company' and read by nothing; serving still treats /d/* as public hosting until the door; Companies/Users are not in Server.layer because nothing HTTP consumes them yet.

The remaining lie is serving. Writes already mean “this user, via this machine.” Later tickets can mint onto device_logins, mount Companies/Users, and start reading scope without unwinding a token-as-principal.


Method

The live request path is the small model. Authenticate is one SQL join. Postgres decides every refusal. json_build_object returns the wire Identity. Bearer middleware provides CurrentIdentity; Patches never imports Auth. Two columns, two meanings: owner_user_id is who may write, created_by_machine_token_id is provenance. Rewriting the three baselines is the right cut with no production data; additive migrations would have kept accounts / api_tokens / token_mints in a ledger nobody should replay.

The seed is the same idea: one transaction that produces a working credential, cloned by runner, vitest template, and packed e2e. Testing.layer() takes no argument. CLI minting is deleted, not gated.

packages/companies is where the method stops being small. The package is earned as a home for tables. The two services are not earned by a second production consumer — Server never provides their layers; their only callers are their tests. #137 asked for that domain now so the pages ticket inherits it. The implementer at least did not pretend: unused services stay off the composition root.

Users.deactivate updating machine_tokens is the smallest leak that keeps last-admin and token death atomic. A revokeForUser on Auth would invert Auth → Companies. A server orchestrator would be a third thing with one caller. Later tickets should not grow more SQL across that line.

A different method that still hit 137 could not skip the package or the unused services. Additive migrations, a TypeScript identity assembler, or a deactivation orchestrator would have made the behavior more surprising, not less.


YAGNI

The cut is mostly the right one. Three rewritten baselines; minting deleted rather than gated; one seed; empty unauthenticated path list; scope written and unread. InviteMail, Session, DeviceLogins, Clerk, pages, and sharing stay out.

Must-cut: two tests in packages/companies/src/Users.test.ts install PL/pgSQL triggers (audit_claim_refresh, refuse_atomic_revocation). Spec tests assert the rows a transaction left, never SQL internals. The WHERE already is the write-only-on-change proof; a failed UPDATE already rolls back. Keep the row assertions; cut the functions, triggers, and the narrative comments that justify them.

Judgement, not blockers

Nits from the service and surface reads

  • Company / Invite / User leak Schema.Date instead of mapping ISO like Patches (pending pg-client change).
  • CompanyNotFound has no test.
  • alreadyRevoked: true is covered on MachineTokens.revoke, not on the HTTP group.
  • CLI README still says only upload and whoami fail closed; delete now uses the same requiredToken path.
  • packages/serving/src/TrustedProxies.ts still comments “the mint limit and quota”.
  • Auth glossary Your machines still says “the self-service side of revocation”.
  • ADR-0003’s Contexts header still omits Companies, while the body now gives it baseline 1.

POST /api/logout without patchy logout is a real reverse-state gap on the Standards axis. #137’s CLI bullet did not ask for it; #142 is the login/logout CLI ticket. Do not invent a half-command here if that ticket is next — but do not leave the wire as a one-way door forever.


Standards: 2 hard findings, 4 judgement smells. Worst on this axis: leftover token.minted after Auth stopped emitting, plus logout with no CLI reverse.
Spec: 1 missing (the PATCHY_PUBLIC_BASE_URL localhost default from §4). Worst on this axis: that leftover default. The #137 checklist itself landed.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Review disposition

Reviewed both agent comments against #137, parent #135 and the source. Fixes are committed and pushed in e802c3f (fix(server): require an explicit public base URL).

Fixed

  • Public-origin default: removed the localhost fallback as Auth: Clerk, companies and machine tokens on tier 0 #135 §4 requires. Added a whole-server startup regression: missing PATCHY_PUBLIC_BASE_URL must fail with a ConfigError naming that variable. Server test fixtures now supply an explicit origin, and DEVELOPMENT documents the requirement.
  • Analytics documentation: corrected the context map, Analytics glossary and event comment: Patches emits today; Auth currently emits nothing. Removed the obsolete CLI/server-mint narrative. Kept token.minted because Auth: Clerk, companies and machine tokens on tier 0 #135 §9 explicitly says it stays and will be emitted by the device-login poll; adding an unsolicited logout event or deleting that vocabulary would contradict the spec.
  • CLI README: added delete to the commands that fail closed on unreadable/invalid credential state.
  • TrustedProxies comment: removed the deleted mint limit/quota; attribution still covers the protected-API limit and version source address.
  • Auth glossary: replaced “self-service side of revocation” with the user's control over which machines may act for them.
  • ADR-0003: included Companies in the contexts header, matching its migration ownership.

Kept, with reasons

Finding Disposition
No CLI logout Intentional sequencing: #142 owns login/logout, local-first deletion, courtesy-call failures and environment/dev-seed warnings. Its JSON is { ok, instanceUrl, revoked, warnings }, not the proposed raw LoggedOut response. #137 explicitly adds only the server self-revoke route. No half-command added here.
Users.deactivate writes machine_tokens Keeps user deactivation and all key revocations in the same transaction, including last-admin protection. Calling Auth from Companies would reverse the dependency and introduce a cycle.
Repeated user column projection Kept the two small query-local projections; both decode through the same User schema. A shared SQL-fragment export would expose persistence plumbing without changing behavior.
Empty unauthenticated-path list Explicitly required by #137 until device-login routes land.
device_logins DDL without a service Explicitly required by #137's rewritten auth baseline; the service belongs to #141.
Null clerk_invitation_id Required baseline field; #137 requests invite rows without mail. Clerk invitation delivery belongs to #146.
Companies/Users not composed into Server Their services are required now, but there is no HTTP consumer yet. Mounting unused layers would add work without a surface.
Trigger-based claim-refresh test Retained: it observes audit rows, not SQL text or query structure, and detects writes when unchanged claims must cause none (§3). Comparing user values alone cannot detect an unnecessary UPDATE.
Trigger-based revocation failure test Retained: a real database failure verifies that deactivation leaves the user active and the token live. Dropping withTransaction would fail this test; an individual failed UPDATE does not prove earlier updates rolled back. No mocked business logic.
Users.list Small company-scoped read used by the existing transaction/concurrency tests; no new abstraction or endpoint added.
InvalidHandle.length Safe structured diagnostic context, without retaining the raw invalid input. A field need not appear in the human message to be useful error metadata.
Repeated seeded Identity expectations Kept explicit expected documents at the wire/CLI boundaries rather than adding a production seed helper solely for test assertions.
Internal Schema.Date fields Match today's Postgres driver and the documented pattern in packages/sql/README.md; these service results are not a new timestamp wire contract. The anticipated driver change is not part of #137.
No dedicated CompanyNotFound test No incorrect behavior found: an absent company is refused before invite insertion. Did not add a tag-only test merely to raise coverage.
No HTTP alreadyRevoked: true test Existing service concurrency test verifies one false/one true and the original revocation stamp. HTTP coverage verifies self-revoke, subsequent 401 and another machine remaining valid. Replaying a dead bearer should return 401, not force the race-only branch through a fake handler.

Clerk pages, login, sharing enforcement and the HEAD fix remain in their named later tickets; none is silently added to this data-model PR. The first agent review reported no blockers and needs no separate change.

Verification

  • Startup regression failed before the fix because the server booted without a public base URL; passed after the fix.
  • Focused server/guard/patch API/serving suites: 19 passed across 4 files.
  • pnpm test: 168 passed across 27 files, including the retained company/user and machine-token regressions.
  • pnpm lint and pnpm typecheck: passed.
  • pnpm test:packed-cli-e2e: passed against a real isolated server, including identity, create/update, served versions, fail-closed credentials and owner deletion.
  • Worktree clean after commit and push. No production or daily-driver instance touched.

Merge readiness

  • Latest head: e802c3f.
  • All six GitHub checks passed on this head: test (22), test (24), lint (format/lint/typecheck), cli-smoke, dependency-review, and label. CI run; labels run.
  • GitHub reports MERGEABLE / CLEAN. There are no review threads or change-request reviews; both review comments have a disposition above, and neither has new findings since the push.
  • GitHub reports no required checks and no applicable rulesets for the stacked base; all configured checks passed nonetheless. This is not a claim that branch protection requires them.
  • No unresolved blocker for merging into the declared base, auth/136-remove-operator-routes. chore(patches): remove operator routes and pins #147 remains open: this is readiness against that stacked branch, not permission to merge directly into main. No merge performed.

@vsrikar08

vsrikar08 commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

only caveat is something to check for if tokens are compromised but tbh we don't really need that rn. Also see if you can have a warning for expiring tokens (say, if it expires within a day or something)

Also thing to note: Admins should be able to delete employee shit. But tbh that's out of scope, and we can't be complicated. Still good to keep in mind, though.
Also, I'm probably aware that this is a different pr but the tokens should be tied to the company so they can view pages or some other way. Again, it's probably a different pr but yeah, just wanna put it in here.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

@vsrikar08 Following up on your review:

  • Compromised credentials already have a revocation path in the completed stack: revoke one or all machines, or deactivate the user. Additional compromise detection and advance expiry warnings are outside this PR.
  • Company admins managing or reassigning employees' patches remains future work; no extra patch-write permissions requested here.
  • Machine tokens already resolve to a user and their company. Reading company pages currently uses that user's signed-in browser session; machine-token access to the page routes is deliberately not supported.

None of these points requires an additional change to this PR.

Base automatically changed from auth/136-remove-operator-routes to main September 6, 2026 12:44
Implement #137: company membership, user-owned machine credentials, patch ownership, and a shared development seed. Remove bootstrap and self-service credentials across the API, CLI, tests, and documentation.
@allisonmahmood
allisonmahmood force-pushed the auth/137-companies-users-machine-tokens branch from e802c3f to ffe36ca Compare September 6, 2026 12:44
@allisonmahmood
allisonmahmood merged commit e200969 into main Sep 6, 2026
6 checks passed
@allisonmahmood
allisonmahmood deleted the auth/137-companies-users-machine-tokens branch September 6, 2026 12:47
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:cli Touches the cli area 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(companies): companies, users and the machine token replace accounts and API tokens

2 participants