Skip to content

Recovery codes and seed-preserving password reset - #1470

Merged
AnthonyRonning merged 14 commits into
masterfrom
feat/recovery-credentials-integrated
Nov 11, 2026
Merged

AnthonyRonning merged 14 commits into
masterfrom
feat/recovery-credentials-integrated

Conversation

@w3irdrobot

@w3irdrobot w3irdrobot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds opt-in recovery codes so users can reset their password while preserving their account seed and encrypted data. Users without a usable code can explicitly choose the existing destructive reset behavior.

Consolidates and supersedes #904 (backend) and #1435 (SDKs), imported as separate squash commits. The branch is rebased on master at a1839576, including the shared password policy from #1477 and the reset limiter from #1546. Backend, SDKs, Research integration and lifecycle emails can be reviewed together here; the original PRs retain their discussions.

Changes

  • Limiter integration after rebase: valid user reset proofs check the shared budget without spending it; failed proofs with a matching client secret share the limit across legacy confirmation and V2 options/completion. Exhausted requests return the existing generic 429 and retry headers. A credential change during recovery-management password step-up returns a generic 401. The smoke verifies the five-email cap, then seeds local proof fixtures for later recovery scenarios. The three client-input/migration-helper follow-ups from Follow up on recovery reset inputs and migration redo #1548 are included as a separate commit.
  • Backend: add recovery enrollment, replacement, disabling, status/use tracking and V2 reset-options/completion endpoints. Management requires an email/password account, an authenticated seed context and password step-up. Transactional checks protect credential changes, replacement, disabling and competing resets. Preserving reset retains the seed and recovery code; destructive reset clears encrypted data, removes recovery enrollment and disconnects linked sign-in providers. Legacy reset stays destructive and rejects recovery material.
  • SDKs: expose all six recovery/reset endpoints in TypeScript/React and Rust, install the new authenticated session after reset, retain server error statuses and fence token installation against account changes. Secret-bearing Rust types redact debug output. Status uses issued_at for the active code's issuance, including replacement. Research consumes the in-tree SDKs; this PR does not publish them.
  • Management rollout: the frontend recovery flag gates the Security settings section. Backend endpoints and the logged-out reset flow remain available independently. A late flag-off response cannot discard a code already being issued or confirmed.
  • Saving and confirmation: show each issued code once, with copy, browser download and a native desktop save dialog. Mobile apps hide unsupported file export. Users must paste back the saved code before Done; a typo or a different valid code retains the issued code and navigation lock. Confirmation accepts the saved text file's contents and has a show/hide toggle. State remains account-scoped and in memory. Settings explain that recovery requires access to the account email as well as the code.
  • Reset flow: accept 8–32-character alphanumeric email codes (generation remains eight characters); verify the emailed proof before revealing choices, prefer preservation for enrolled users, require explicit consent for destructive reset and preserve the success screen through sign-in. Add recovery-code show/hide. Research and the backend enforce the same 8–64 Unicode-character password range; local password errors retain the proof and inputs. Failures never silently select destructive reset.
  • Input ownership: Research validates every bounded recovery-code candidate in pasted prose/files, deduplicates canonical matches and accepts exactly one distinct valid code. Ambiguous pastes show an inline error and retain the proof and typed text. The TypeScript SDK exports the grammar and validates standalone syntax, padding and the versioned SHA-256 checksum before transport, throwing RecoveryCodeFormatError locally. The backend keeps character normalization, its byte cap, literal prefix/exact lengths, non-ASCII rejection, checksum and padding checks. Local code errors retain verified proof; a real server 400 clears the verified form.
  • Emails and cleanup: reuse Maple templates and other-project fallbacks for lifecycle and reset notifications, without emailing recovery codes. An unexpected recovery-use notification directs the user to reset with their code and email access, replace the code, then contact support if access cannot be regained. Maple support/Reply-To use support@maple.ai; sender defaults and verification URLs use the updated domain without rewriting stored sender settings. Remove the infallible generator's Result, the unreachable debug panic, and the smoke-module alias. Recovery route races now run on separate OS threads so synchronous Diesel work can overlap.

Local validation

  • Current rebase: Research formatting/typecheck/lint, 1,165 tests passed and PR web build; 13 existing fast-refresh warnings. Repository flake checks passed.
  • WebKit component smoke: 32-character email code, ambiguity alert with proof/input retention, invalid-candidate skipping and canonical deduplication. Uses a fixture API.
  • Fresh Local/MDE SDK smoke passed against the real encrypted backend: password signup/authenticated identity, recovery enrollment, checksum validation of issued codes, rotation, disabling and logout. No model-inference or real inbox delivery is claimed.
  • Backend and SDK source are byte-for-byte unchanged from d3a4bf0d. That verified baseline passed strict Clippy, 1,193 unit tests (106 ignored), 102 guarded database tests including 44 recovery tests, and encrypted recovery HTTP smoke including the reset-email cap. Both recovery migrations were rolled back and reapplied with the corrected helper.
  • The unchanged SDK baseline passed TypeScript package/consumer checks (333 tests, 3 hosted skips) and Rust formatting/strict Clippy/docs/package checks (134 tests, 1 ignored). No SDK was published.

Earlier evidence at 4f0f454c: 17 TypeScript API integration tests, Rust account-management integration (7 passed, 3 ignored), Research Rust (93 passed, 1 model-backed OCR test ignored), and Linux desktop fixture checks for native Save/Cancel, exact saved text/mode 0600, checksum-error retention, whole-file confirmation and show/hide. These are historical checks, not new native-runtime proof for the rebased heads.

Earlier Chromium/Linux Tauri MDE checks at 82f4b8f3 exercised real local account/reset proofs, clipboard readback, reload/relaunch, preserving and destructive reset, and lifecycle mail capture. Encrypted conversation metadata and saved instructions survived preservation and were removed by destructive reset. Those are historical full-app checks.

Rollout and remaining evidence

  • macOS and phone reset-flow runs requested in review remain outstanding. Windows GUI, packaged installer/updater behavior and deployed Nitro behavior are also unverified. No model-inference/generated-message round trip or real inbox deliverability is claimed.
  • Run both 2026-10-28-000000_recovery_credential_kind and 2026-11-02-000000_recovery_wrap_use_tracking before starting the new enclave, since seed-wrap reads select the new columns. No deployment or shared migration is performed by this PR.
  • Durable reset-code guess budgets and per-account reset-email caps are tracked separately in Add database-backed limits for password-reset guesses and emails #1486, including platform/developer resets.

For MDE testing, keep the local backend running and force the management flag from the Maple checkout when launching the desktop:

VITE_FORCE_FEATURE_FLAGS=recovery nix develop --no-update-lock-file -c just desktop-dev

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Maple development preview: https://7e7ca68d.maple-ca8.pages.dev

Commit: 1a23f43d04cee7b2cf6e8301aa8cba5003b005ad

Uses development API, billing, flags and PCR configuration. Cloudflare Access applies.

@w3irdrobot
w3irdrobot marked this pull request as ready for review November 6, 2026 02:10
w3irdrobot added a commit that referenced this pull request Nov 6, 2026
…nt password boundaries

The backend accepted any password string - including the empty string -
at every user-account password boundary. Platform routes already
validated 8-64 via the validator crate, but /register,
/password-reset/confirm and /protected/change_password did not.

Add a shared password policy (8-64 Unicode characters, counted per
character like the Agent client) and enforce it before any database or
seed-wrap effect at those three boundaries. Login is intentionally not
length-validated: a wrong-length attempt is an authentication failure,
and existing accounts (including short-password ones) keep working.

Rejects return 400 with a specific message (PasswordTooShort /
PasswordTooLong) so clients can surface the reason. A rejected reset
does not consume the one-shot reset request; a rejected password change
leaves the current credential intact.

Covered by unit tests plus disposable-database route tests proving
rejection without side effects on register and change_password. The
transport-v2 password-reset completion route lands with the recovery
credentials work (#1470) and will pick up the same policy there.
@w3irdrobot

Copy link
Copy Markdown
Contributor Author

Follow-up from #1477: once that PR merges, this branch should pick up the same server-side password policy for /password-reset/v2/complete.

The new shared policy lives in services/opensecret/src/web/password_policy.rs (8–64 Unicode characters). After rebasing this branch on master to pick up the module, the change is a one-liner at the top of password_reset_v2_complete, before proof verification consumes the one-shot reset request:

validate_password(&request.new_password)?;

(From<PasswordPolicyError> for ApiError is included in #1477, so the ? maps straight to a 400 with a specific message.) The route was confirmed vulnerable pre-fix — new_password: "" was accepted at completion — and #1477's branch has a ready-made disposable-DB route test for exactly this rejection that can come along with the hunk.

w3irdrobot added a commit that referenced this pull request Nov 6, 2026
…nt password boundaries

The backend accepted any password string - including the empty string -
at every user-account password boundary. Platform routes already
validated 8-64 via the validator crate, but /register,
/password-reset/confirm and /protected/change_password did not.

Add a shared password policy (8-64 Unicode characters, counted per
character like the Agent client) and enforce it before any database or
seed-wrap effect at those three boundaries. Login is intentionally not
length-validated: a wrong-length attempt is an authentication failure,
and existing accounts (including short-password ones) keep working.

Rejects return 400 with a specific message (PasswordTooShort /
PasswordTooLong) so clients can surface the reason. A rejected reset
does not consume the one-shot reset request; a rejected password change
leaves the current credential intact.

Covered by unit tests plus disposable-database route tests proving
rejection without side effects on register and change_password. The
transport-v2 password-reset completion route lands with the recovery
credentials work (#1470) and will pick up the same policy there.
@w3irdrobot
w3irdrobot force-pushed the feat/recovery-credentials-integrated branch from 91d4487 to 18ca345 Compare November 6, 2026 17:46

@AnthonyRonning AnthonyRonning left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is in good shape. The backend design, reset transactions and reset UI all look right to me. Most of the notes below are about the last step: making sure a user really ends up with a working code. This is from reading the code at 18ca3456; it hasn't been run.

Before merge

  • Feature flag. Add a key to FEATURE_FLAGS and gate the recovery section in SecuritySettings.tsx with useFeatureFlag. Frontend only: the endpoints stay live, and the reset flow stays unflagged because it runs logged out and enrolled users need it.
  • Native pass on the reset flow. It goes live for everyone on merge, so it needs one run on macOS and a phone first.

Before the flag goes on

  • "Save text file" probably doesn't work on macOS, iOS or Android. downloadCode is a plain <a download> blob. Tauri sets no download handler by default and we don't add one, so wry cancels it on WebKit (src/wkwebview/navigation.rs:68-73, wry 0.57), and neither wry nor our Android project handles downloads. click() doesn't throw, so nothing tells the user it failed, and they can still tick "I've saved this". This comes from the source, so please confirm on a Mac. Either make it work natively or hide it there and rely on Copy.

  • Confirm the code before Done. Consider having the user paste the code back. It needs no backend change, and it catches a failed save that would otherwise only surface when they need the code.

  • Check the checksum on the client. normalizeRecoveryCode only checks syntax, so one wrong character reaches the server. The server correctly leaves the request alone, but the generic 400 wipes the form and tells the user to request a new email. Verifying it locally and throwing RecoveryCodeFormatError would keep the form intact. It's the first 5 bytes of SHA-256 over the version byte and secret, and hashSecret already uses crypto.subtle. A show/hide toggle on the masked field would also help anyone typing from paper.

  • Rate limit the reset proof. Nothing limits email code guesses. This predates the PR, but verify_password_reset_proof now gives us one place to fix it. It has to live in the enclave, because the edge only sees /v2/request, we have no client IP, and the inference limiter is per process. My suggestion, both in Postgres:

    • Allow 5 wrong codes per request, counted against open requests matching the submitted secret, so an attacker can't burn the real user's request.
    • Cap reset requests at about 5 per account per hour. Past that, return the same generic response and send no email.

    A follow-up is fine if you'd rather keep this PR focused. The platform reset has the same gap.

Small

  • The reset form has no 64-character limit, so since #1477 a longer password gets the same form wipe and a misleading message.
  • The "recovery code used" email tells the reader to change their password, but if someone else used the code, they're locked out. It should send them to a reset with their code, then support.
  • The settings copy should say recovery also needs access to the account email.
  • enrolled_at really means last issued, so consider issued_at before the SDKs publish.
  • Nits: the #[path = "recovery_smoke.rs"] mod local_flow_smoke rename, the debug_assert!(false) arm in password_reset_v2_complete, RecoveryCode::generate returning a Result that's always Ok, and the tokio::join! race tests over sync diesel. The real threads in the DB tests are the better pattern.
  • MaplePrivacyLabs/code-docs#108 needs a refresh or closing. It still has the old baseline and test counts, and doesn't cover this PR.

Deploy note: run both migrations before the new enclave, because every seed-wrap read selects the new columns. The old binary is fine on the new schema.

@w3irdrobot

Copy link
Copy Markdown
Contributor Author

@AnthonyRonning Addressed the code feedback in 4f0f454c:

  • Added the frontend recovery flag for Security settings management. Endpoints and logged-out reset remain unflagged; a late flag-off response won't discard an issued code awaiting confirmation.
  • Desktop file saving now uses a native dialog, and mobile apps hide the unsupported Save button. Done requires pasting back the saved code; both confirmation and reset inputs have show/hide controls.
  • Added SDK checksum/padding validation before transport. Local code errors retain the verified proof and typed input. Reset password validation now matches the backend's 8–64 Unicode-character range.
  • Fixed the recovery-used email guidance and added the account-email access requirement to settings copy.
  • Renamed the unreleased status field to issued_at, removed the infallible generator's Result and unreachable debug panic, cleaned up the smoke module name, and moved the route race tests onto separate OS threads.

Opened #1486 for database-backed email-code guess budgets and reset-email caps, including platform resets. Refreshed the architecture notes' stale status and backend/client contracts while keeping the backend focus and preserving historical evidence.

Validation passed locally: frontend/web and native Rust lanes, both SDK/package lanes, 97 disposable-DB tests including the real-thread races, encrypted recovery HTTP smoke, TypeScript API and Rust account integration checks, and actual Linux desktop save/cancel/confirmation checks with a fixture API. The PR description has the exact counts and ignored-test boundaries.

The macOS and phone reset-flow runs you requested are still outstanding; we haven't treated Linux checks as a substitute. The migration-before-enclave ordering is recorded in the PR description.

@AnthonyRonning

AnthonyRonning commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Okay the flow seemed to work really well!

I wonder if we should go ahead and change the email reset code to be either a UUID or something longer. The 8 digit code for verification might have been okay at one point but I don't think I like the idea of it being brute forcable as we rely on it more. And DB-saved rate limits only go so far.

Edit: Or maybe they go far enough anyways. Just speaking out loud here. We can chat about it more if you have thought about this.

@AnthonyRonning AnthonyRonning left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final pass at 4f0f454c: no blockers. This was a security read of the backend, both SDKs and the Research client, and the disposable-database suite passes at this head (97 tests, 43 of them recovery). The recovery wrap follows the same credential-bound seed-wrap design as password and OAuth, and the submitted code is the only thing that opens it. Threat-model notes are on MaplePrivacyLabs/code-docs#108.

Thanks for the patience on this one, Alex.

Small things, none blocking the merge

  • The new reset flow pins the emailed code to exactly 8 characters. PasswordResetFlow.tsx:83 tests /^[A-Z0-9]{8}$/ and :218 sets maxLength={8}; the released form already has pattern="[A-Z0-9]{8}". Please relax the new check to a range (say 8 to 32 of [A-Z0-9]) before the next Research release, so the server could change the length later without waiting out old clients. No change to code generation.
  • Paste extraction only tries the first MPLRC1 match (recoveryCodeInput.ts). A notes file with an old code above the current one submits the old one. It is well formed, so the server consumes the reset request and the user has to ask for a new email. Pasting the same file fails the same way. Suggest checking every match: accept when exactly one distinct code passes the checksum, and ask for just the code when more than one does. Fine as a follow-up.
  • disposable_db_tests.sh --redo-latest N redoes the newest migration N times, not the last N. diesel migration redo -n "$redo_count" does what the script's comment describes. Both recovery migrations were cycled by hand with an enrolled row present and pass, so nothing is missing for this PR.

Reset code length

Following up on my comment above: I'd leave the code at 8 characters. With the limits in #1486 a guesser gets a few hundred tries a day against 36^8 codes, which is enough. The first bullet just keeps the option open.

Rollout order

Both migrations, then the enclave, then the Research release. The new reset screen calls only the V2 routes, so a client that ships before the enclave would break password reset. The phone reset-flow run is still open before the next mobile release. As in the earlier review, #1486 comes before the recovery flag goes on.

@AnthonyRonning

Copy link
Copy Markdown
Contributor

Could you rebase onto master? #1550 conflicts in PasswordResetConfirmForm.tsx; keep this PR's wrapper there. If it's easy, fold #1548 into the same push so the new reset screen also accepts 32-character codes. Then this is ready to merge.

…sets

Squashes the recovery backend, tests, lifecycle emails, and domain updates from #904 (eee44ac) onto current master. Retains both current client-app and recovery transport test modules.
Squashes #1435 (47aa287), including reset token-install fencing and redaction. Current master already contains the package version and consumer lockfile updates.
@AnthonyRonning
AnthonyRonning merged commit 9d05fef into master Nov 11, 2026
34 checks passed
@AnthonyRonning
AnthonyRonning deleted the feat/recovery-credentials-integrated branch November 11, 2026 23:29
@AnthonyRonning

Copy link
Copy Markdown
Contributor

I'm rolling this out now. I'm not sure why email settings were changed here, there's a handful of things that need to be cleaned up from this.

This branch was successfully deployed

1 active deployment
pages-pr-1470 — 1a23f43d Deployed Nov 11, 2026 by github-actions[bot]
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