feat(create): enforce authorization and validation boundary for commitment wizard and draft recovery - #1851
Open
Joseph-1-Duro wants to merge 1 commit into
Conversation
…tment wizard and draft recovery - Define explicit invariants in src/lib/validation/createCommitment.ts and src/lib/validation/walletBoundary.ts (SourceId, Amount, Asset, DraftState, IdempotencyKey, wallet/network gates) - Harden useDraftPersistence: strict zod (step 1..3, duration 1..365, maxLoss 0..100), pruneExpiredDrafts, isValidDraftId guard, wallet-scoped visible drafts, tamper discard and flush handling - Harden usePrefillFromCommitment: sourceId regex validation, AbortController, safeParse response, sanitize amount/asset/duration, clamp with finite checks - Fix create wizard (src/app/create/page.tsx): wallet/network/auth gates with banners, strict parseAmountStrict, asset allowlist, draft resume re-validation with tamper/ownership errors, idempotent submit (Idempotency-Key, CSRF, Bearer), malformed response handling, explorer network via getExplorerNetworkFromPassphrase, replay/retry handling - Fix integration with ResumeDraftPrompt (drafts[]/onResume(draftId)/onDeleteDraft) and backend POST /api/commitments (idempotency replay protection, requireAuth ownership check, strict numeric validation) - Implement validateSupportedAsset/validateStellarAddress checks - Add stubs for missing components and focused tests covering success/failure/boundary/retry/permission - Refs Commitlabs-Org#1831 Validation: - NVM 20.19.5, pnpm test -- --run (57 passed, 644 total, 1 pre-existing mockDb failure)
|
@Joseph-1-Duro is attempting to deploy a commit to the 1nonly's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
@Joseph-1-Duro Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1750
Objective
Enforces a clear authorization and validation boundary before sensitive UI actions or API calls for
src/app/create/page.tsxandsrc/components/create/ResumeDraftPrompt.tsx.Fixes production-quality risk where multi-step creation must preserve validated input, recover interrupted drafts, and avoid stale/duplicate submissions.
Refs #1831
Invariants (state / data / authorization / failure)
step∈[1,3], linear1→2→3, draftversion,createdAt/updatedAtwith 7d TTL, prune on load/write.type∈{safe,balanced,aggressive},asset∈{XLM,USDC},amountstrict decimal^\d+(\.\d{1,7})?$, finite>0 ≤1_000_000,durationDaysint1..365,maxLossPercent0..100(maxLossBps0..10000),sourceId^[A-Za-z0-9_-]{1,64}$, idempotency key^[A-Za-z0-9_-]{8,64}$.connected && address && authenticated,walletNetwork === NEXT_PUBLIC_NETWORK_PASSPHRASE(wrong-network block), draftwalletAddress === currentAddress(legacy drafts allowed but ownership re-checked on resume),POST /api/commitmentsrequiresverifyAuth || requireAuthandownerAddress === authAddress(403 otherwise), not inferred from client state.wallet-disconnected-banner+ disable submit, wrong-network →wrong-network-banner, tampered/expired draft → discard +field-error-banner+ clear, malformed prefill → safenullfallback, malformed create response → throw + retryable error, replay → idempotencySTARTED⇒409,COMPLETED⇒200 cached, rate-limit429, CSRF origin check preserved.Boundary Validation
sourceIdregex +encodeURIComponent, response viaCommitmentResponseSchema.safeParse, identity fields dropped.useWallet()gating viacheckWalletBoundary(src/lib/validation/walletBoundary.ts).parseAmountStrict,AssetSchema, clampedduration/maxLosswith finite checks.CommitmentResponseSchema/CreateResponseSchemasafeParse, missing/invalidcommitmentId→ error, not blind trust.Scenarios Covered
__proto__), wrong-network, disconnected-wallet (banner + block submit), malformed-response (invalid JSON, missing fields), permission (owner mismatch 403, unauthenticated), retry (idempotency fail → allow retry, STARTED → 409, network abort).Tests
pnpm test -- --run— 644 passed, 1 pre-existing failure (src/app/api/analytics/protocol/route.test.tsmissingmockDb).New focused tests (61):
src/lib/validation/createCommitment.test.ts— SourceId/Amount/Asset/DraftState/Idempotency boundarysrc/lib/validation/walletBoundary.test.ts— DISCONNECTED/WRONG_NETWORK/UNAUTHENTICATEDsrc/hooks/__tests__/useDraftPersistence.boundary.test.ts— TTL, tamper, pollution, expired, validsrc/app/api/commitments/route.createBoundary.test.ts— 200, 400 (NaN/Infinity/ETH/9999), 403 ownership, 409 replay, invalid key, fail-retry, malformed JSONsrc/app/create/createBoundary.test.tsx— disconnected/wrong-network banners, tampered draft blocked, duplicate submit guardValidation commands:
Design Tradeoffs & Limitations
localStorageis untrusted convenience — server is source of truth. No HMAC secret, so tamper detection is schema-based discard + prune, not cryptographic binding. Documented.walletAddress(legacy anon drafts visible). Alternative per-wallet keycommitlabs-create-drafts:${address}noted for stricter privacy.idempotencyService(24h TTL).Idempotency-Keyrequired format 8-64 alnum/_/-; missing key still allowed for backward compat but replay protection only with key.validateSupportedAsset(ETH rejected) — matches chain contract.getExplorerNetworkFromPassphrase(walletNetwork ?? expected)not hardcodedtestnet.CreateCommitmentStepReview/CommitmentCreatedModalto fix case-sensitive import not found (Commitmentcreatedmodal.tsxvs correct case) — minimal functional stubs.Remaining
No secrets, no unrelated refactors, no test removals.