Repository navigation
refactor(auth): mint manager sessions in one place, off payload.login - #846
Conversation
#664 removes password login, and `payload.login` then throws `Forbidden` on its first line. Everything that only wants a session needs somewhere else to get one before that lands. `mintManagerSessionToken` is the tail of Payload's own `resetPassword` operation, rebuilt from the two exports it uses — `getFieldsToSign` and `jwtSign`. `addSessionToUser` is internal, so the session row is written here instead, and it is the part that is easy to leave out: `Managers` inherits `useSessions: true`, so the JWT strategy returns no user when the token's `sid` is missing from `sessions`. A token minted without the row is well-formed and authenticates nothing. The row is written with `payload.update` carrying only `sessions`, not a whole-document `db.updateOne`. `roles` is localized, and a document read at one locale written back whole would flatten it to that locale. Co-authored-by: Claude <[email protected]>
Six call sites authenticated as a manager by calling `payload.login` with `password123`. They want a session, not a password check, so they move to `mintManagerSessionToken` now, while passwords still work — the cut-over in #664 then changes no test. `createRestClientAs` drops its `password` parameter; no caller passed one. Two JSDoc blocks cited `payload.login`'s `UnverifiedEmail` as the reason they set `_verified`. The step is unchanged and the reason is now the JWT strategy's own `_verified` gate, so both are restated. The `Login-lockout reset (unlock)` suite keeps `payload.login`, and so does `manager-verification`. Password login is the mechanism under test in both — `createLockedManager` logs in five times with a wrong password on purpose, to exhaust `maxLoginAttempts`. Co-authored-by: Claude <[email protected]>
Both type casts in `getFieldsToSign`'s arguments were unnecessary — `SanitizedCollectionConfig` is assignable to `CollectionConfig`, and the user literal to `PayloadRequest['user']` — so they silenced nothing. The manager read is `joins: false`. `Managers` declares three join fields, and an unset `joins` enables every one of them for a document nothing else reads. It keeps no `select`, because `getFieldsToSign` reads whichever fields carry `saveToJWT` and a field list would silently drop the first one anybody adds. The update is `depth: 0`; its result is discarded, and `defaultDepth` is 2. The spec drops its own per-locale `roles` case, which duplicated `role-based-access.int.spec.ts`, and decodes the token with `jose`'s `decodeJwt` rather than splitting it by hand. Co-authored-by: Claude <[email protected]>
`toBeCloseTo(exp, 0)` allows 0.5s. The row's `expiresAt` keeps milliseconds and `jwtSign` truncates `exp` to whole seconds, so the two differ by the millisecond component of the mint — over 0.5 for half of all runs. Reproduced red, then green, on the unmodified spec. The bound is now an explicit 2s, which still catches an `expiresAt` computed in seconds rather than milliseconds — the defect the assertion exists for is two hours wide, not half a second. Also corrects the `sessions`-only write comment: what a whole-document write would flatten is *this* document, read at one locale. Payload's own `db.updateOne` path is fed an all-locales row and flattens nothing. Co-authored-by: Claude <[email protected]>
`tests/AGENTS.md` told a reader that `createRestClient` logs the suite admin in and that `payload.login` refuses an unverified manager. Both are now the session minter and the JWT strategy's own `_verified` gate. `src/AGENTS.md` gains a line for `src/plugins/login/`, which has no barrel and no registration until #837 — the folder otherwise reads as a plugin that forgot both. Co-authored-by: Claude <[email protected]>
|
🚅 Deployed to the SahajCloud-pr-846 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
Exactly #836's size: one helper, six call sites, no production behaviour. The right two payload.login suites are left alone, and no cross-repo surface is touched. The gates the body defers are not holes: the strategy enforces _verified, #840 deletes lockUntil, #837 refuses inactive.
The cost is the src/AGENTS.md carve-out: a plugins/ folder that is not a plugin. src/lib/livePreview/token.ts is the precedent. Accepted, since #836 names the path.
No blockers. Two consider findings.
⚠ Move #836's #840 warning onto #840 before this closes. #840's "What comes out" still omits role-based-access's Login-lockout reset (unlock) suite.
Checked
#836/#837/#840, session.ts, restRequest.ts, localizedRolesAuth.ts, role-based-access :855-890, :2367-2481. jwtSign appears only in session.ts, payload.login only in the two named suites, 'managers' inline at 17 sites. No node_modules, so Payload internals rest on the specs' green runs.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
`'managers'` is written inline at 17 sites under `src/`, and nothing there reads a slug constant. One constant covering four uses in a single file reads as the start of a convention the repo does not have. Landing a shared constant all 17 sites read is its own change, outside #836. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XtrBXXfZmB46mUpKLJXYMv
The `expiresAt` filter had no spec: every caller mints for a manager created moments earlier, so no row was ever old enough to drop, and the module's only unreachable line was also its only untested one. Seeding an expired row makes it reachable. Verified by replacing the filter with `user.sessions ?? []` — only the new case turned red. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XtrBXXfZmB46mUpKLJXYMv
|
Both review threads adopted, one commit each. Head is
Lean gate green. Still open from the review: move #836's #840 warning onto #840. Not filed by this run. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
No commit this round. The one open thread is answered, and left open for you.
Head is unchanged at 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
No commit this round. The one open thread is answered and resolved.
Head is unchanged at Still open from the adversarial review, and filed by no run yet: move #836's #840 warning onto #840. role-based-access's 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
mintManagerSessionToken— the one place a manager session is minted, with no password.Managers.authis untouched andpayload.loginstill works.Changes
src/plugins/login/session.ts— new. Payload's ownresetPasswordtail, rebuilt fromgetFieldsToSign+jwtSign, plus the session rowaddSessionToUserwould have written.tests/utils/restRequest.ts—createRestClientAsdrops itspasswordparameter and mints instead. No spec that calls it is edited.tests/int/role-based-access.int.spec.ts— two directpayload.logincalls onto the helper.tests/int/login-session.int.spec.ts— new, covers the helper directly.Preview
mainTest results
typecheck,typecheck:tests, 2163 unit testslogin-session,role-based-access,user-submissions-review,error-disclosure,error-disclosure-debug,available-locales,frames-by-narrator. Fullpnpm test:intalso run green (83 files, 1367 tests). Re-run after mergingorigin/main:login-session,role-based-access,clients-access— 94 passed.login-sessionandrole-based-access— 73 passed.Manual verification
PREVIEW_ADMIN_PASSWORD. Password login is untouched by this PR and must still work.Notes for reviewer
The open question in the ticket resolved as "ship it".
session.tshas no production caller for one merge — tests are its only consumer, and it is imported by path because the barrel and thePluginfactory come with #837.Two gates this helper deliberately does not have, both for #837's consume route to own once there is a production caller:
lockUntil(enforced only byloginOperation, never by the JWT strategy) andtype: 'inactive'. Neither is exploitable today — every importer is a test, and a caller already holding thePayloadinstance has strictly more power than the token it would mint. Worth pinning on #837 before the route lands.securityReview.triggerPatternin.claude/workflow.jsondoes not matchsrc/plugins/login/. The security sweep was run anyway and found nothing. The pattern should gain that path when #837 makes the folder a real plugin.Adopted from the adversarial review, one commit each:
MANAGERSslug constant is the repo's first, for four uses in one file.aa5d2d1inlines'managers', matching the 17 sites already written that way. A shared constant all 17 read is its own change.0e19db0seeds an expired row instead of dropping the filter. The filter is what keepssessionsfrom growing by a row per sign-in, and feat(auth): the login plugin, with magic-link request and consume endpoints #837's route is where repeats start.Dismissed review findings:
src/collections/Managers/auth/, or land the plugin barrel now. The ticket specifiessrc/plugins/login/session.tsas the first file of the login plugin and defers the barrel to feat(auth): the login plugin, with magic-link request and consume endpoints #837.src/AGENTS.mdgains a line saying so, rather than the folder silently reading as a plugin that forgot to register._verified: trueintestData.createManagerand delete the five overrides. A real cleanup, but it editsmanager-verification.int.spec.ts, which this ticket leaves alone, and the acceptance criteria say no spec callingcreateRestClientAsis edited. Worth its own ticket — that fixture also still hardcodespassword: 'password123', which feat(auth): passwordless email-link login and manager invitations #664 will strand.payload.db.updateOnelikeaddSessionToUserdoes, to skip hooks and validation. Payload feeds that path a raw all-locales row fromdb.findOne; this helper holds a local-API document read at one locale, so the same call would flatten localizedroles.Managersdeclares no collection hooks, so the cost is validation of an already-stored document. Revisit with areqparameter in feat(auth): the login plugin, with magic-link request and consume endpoints #837.reqso a caller can join its transaction. Nothing here has one. feat(auth): the login plugin, with magic-link request and consume endpoints #837's route will.Detail
Why the session row is the load-bearing part.
ManagersinheritsuseSessions: true, andJWTAuthenticationreturns{ user: null }when the token'ssidis not in the user'ssessionsarray. A token minted without the row is well-formed and authenticates nothing — silently, because the strategy then falls through toautoLogin.managers_sessions.expires_atisNOT NULL, so an omittedexpiresAtfails the insert rather than minting a token that outlives its row.Each assertion was verified by reintroducing the defect. Removing the session write, dropping the
sidclaim, and computingexpiresAtin seconds instead of milliseconds each turned the new spec red; restoring each turned it green. The expired-row case was added the same way — replacing the prune with[...(user.sessions ?? []), session]failed that case and no other.One assertion was flaky as first written and is fixed in its own commit.
toBeCloseTo(exp, 0)allows 0.5s, butexpiresAtkeeps milliseconds whilejwtSigntruncatesexpto whole seconds — so it failed whenever the mint landed past the half-second, about half of all runs. Reproduced red then green on the unmodified spec. The bound is an explicit 2s now, which still catches the two-hour-wide defect it exists for. Five consecutive green runs since.Read shape. The manager read is
depth: 0, joins: false—Managersdeclares three join fields (managedPages,managedRegions,managedEvents) and an unsetjoinsenables every one of them for a document nothing else reads. It keeps noselect, becausegetFieldsToSignreads whichever fields carrysaveToJWT; a field list would silently drop the first one anybody adds. The update isdepth: 0because its result is discarded anddefaultDepthis 2.Two JSDoc reasons went stale while their steps stayed.
restRequest.tsandrole-based-access.int.spec.tsboth set_verifiedand both citedpayload.login'sUnverifiedEmailas why. The step is unchanged; the refusal now comes from the JWT strategy's own_verifiedgate. Both are restated, and the 403-before-query warning above the first is kept.Two suites keep
payload.login:manager-verification.int.spec.ts, and role-based-access'sLogin-lockout reset (unlock). Password login is the mechanism under test in both —createLockedManagerlogs in five times with a wrong password on purpose, to exhaustmaxLoginAttemptsand assertlockUntil. ⚠ #840 removesmaxLoginAttemptsandlockTimewithout naming that suite, so itslockUntilassertion will fail. Flagged on the ticket, not filed.origin/mainmoved during the run (#844 landed). It is merged in, and the lean gate pluslogin-session,role-based-accessandclients-accesswere re-run green on the merge result.Closes #836
🤖 Written by the sydevs autonomous loop — see what this is