Skip to content

fix: restore auth protection for protected routes - #826

Merged
ritik4ever merged 1 commit into
ritik4ever:mainfrom
Ayilojay:fix/issue-597-auth-protected-routes
Jul 31, 2026
Merged

fix: restore auth protection for protected routes#826
ritik4ever merged 1 commit into
ritik4ever:mainfrom
Ayilojay:fix/issue-597-auth-protected-routes

Conversation

@Ayilojay

@Ayilojay Ayilojay commented Jul 29, 2026

Copy link
Copy Markdown

What changed

Testing done

Related issues

Closes #

Checklist

Summary by CodeRabbit

  • New Features

    • Added minimum and maximum amount filters when browsing recipient streams.
    • Added an endpoint to request SEP-10 authentication challenges.
    • Authentication errors now provide more specific feedback.
  • Bug Fixes

    • Corrected vesting progress calculations for paused streams.
    • Requests without a body no longer require a JSON content type.
    • Improved compatibility with legacy environment variable names.
    • Database setup now applies pending migrations automatically.

@vercel

vercel Bot commented Jul 29, 2026

Copy link
Copy Markdown

@Ayilojay is attempting to deploy a commit to the ritik4ever's projects Team on Vercel.

A member of the Team first needs to authorize it.

@drips-wave

drips-wave Bot commented Jul 29, 2026

Copy link
Copy Markdown

@Ayilojay 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! 🚀

Learn more about application limits

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The backend now supports legacy environment-variable mappings, amount filtering for recipient streams, SEP-10 challenge issuance, body-aware JSON validation, migration execution during database startup, and corrected paused-stream vesting calculations.

Changes

Backend runtime and API behavior

Layer / File(s) Summary
Environment compatibility and parsed configuration
backend/src/config/validateEnv.ts
Legacy environment variables are mapped before schema validation, and parsed values are reused for subsequent validation and configuration construction.
Recipient stream filtering
backend/src/index.ts
Recipient stream queries retain existing predicates and now support minAmount and maxAmount constraints on totalAmount.
SEP-10 authentication endpoints
backend/src/index.ts
Adds a rate-limited challenge endpoint and returns thrown authentication errors from the token endpoint when available.
Request validation and migration startup
backend/src/middleware/contentType.ts, backend/src/services/db.ts
JSON content validation applies only to body-bearing POST/PATCH requests, and database initialization runs migrations before returning.
Paused-stream vesting calculation
backend/src/services/streamStore.ts
Paused elapsed time is clamped before progress ratio and elapsed seconds are calculated.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant AuthChallengeEndpoint
  participant ChallengeTransactionGenerator
  Client->>AuthChallengeEndpoint: GET /api/auth/challenge with accountId
  AuthChallengeEndpoint->>ChallengeTransactionGenerator: generate challenge transaction
  ChallengeTransactionGenerator-->>AuthChallengeEndpoint: transaction
  AuthChallengeEndpoint-->>Client: transaction and network passphrase
Loading

Possibly related PRs

Suggested reviewers: osagiecynthia, emeditweb

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Several unrelated changes were added, including env mappings, stream filters, content-type middleware, DB migrations, and vesting math. Split those unrelated changes into separate PRs or remove them unless they are required for issue #597.
Linked Issues check ❓ Inconclusive The summary shows auth endpoints, but not enough detail to verify JWT issuance, route protection, or nonce expiry. Provide the auth diff/tests confirming signature verification, JWT issuance, 60s nonce expiry, and middleware on POST /api/streams and /api/streams/:id/cancel.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and clearly refers to the auth-protection change.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Warning

⚠️ This pull request shows signs of AI-generated slop (description_diff_mismatch). It has been flagged by CodeRabbit slop detection and should be reviewed carefully.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/src/config/validateEnv.ts`:
- Around line 112-120: Use one canonical value for each Stellar setting: in
backend/src/config/validateEnv.ts lines 112-120, derive contract, RPC, and
network values after parsing, then validate and return only those canonical
values so either legacy or new environment variables work consistently; update
backend/src/index.ts line 1193 to use the canonical configured network for the
challenge response instead of reading only NETWORK_PASSPHRASE.

In `@backend/src/index.ts`:
- Around line 1182-1189: Update the `/api/auth/challenge` handler to validate
the request query through the shared Stellar-account Zod schema from
`validation/schemas.ts` before calling `generateChallenge()`. Use the schema’s
parsed accountId for downstream processing, and return the existing 400
validation response when parsing fails instead of allowing invalid values to
reach the service.

In `@backend/src/services/db.ts`:
- Line 329: Update initDb() to invoke the existing migrate() entry point instead
of calling runMigrations(db) directly. Ensure SQLite initialization and upgrades
remain within migrate(), while the Postgres branch uses a migration path that
explicitly accepts PostgresDatabase.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f2c21fdd-ba6d-4839-ad3a-3d10ad346b83

📥 Commits

Reviewing files that changed from the base of the PR and between b3d32c1 and 423d4b6.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • backend/src/config/validateEnv.ts
  • backend/src/index.ts
  • backend/src/middleware/contentType.ts
  • backend/src/services/db.ts
  • backend/src/services/streamStore.ts
💤 Files with no reviewable changes (1)
  • backend/src/services/streamStore.ts

Comment on lines +112 to +120
// Support backwards compatibility: map old variables to new ones if new ones are not set
if (!process.env.STELLAR_CONTRACT_ID && process.env.CONTRACT_ID) {
process.env.STELLAR_CONTRACT_ID = process.env.CONTRACT_ID;
}
if (!process.env.SOROBAN_RPC_URL && process.env.RPC_URL) {
process.env.SOROBAN_RPC_URL = process.env.RPC_URL;
}
if (!process.env.STELLAR_NETWORK && process.env.NETWORK_PASSPHRASE) {
process.env.STELLAR_NETWORK = process.env.NETWORK_PASSPHRASE;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use one canonical value for each Stellar setting.

Mapping CONTRACT_ID only into STELLAR_CONTRACT_ID leaves env.CONTRACT_ID unset, so STELLAR_CONTRACT_ID-only deployments still fail the required-config check. The same split causes SOROBAN_RPC_URL/STELLAR_NETWORK to be ignored in validation or returned config, and the challenge response can advertise testnet when only STELLAR_NETWORK is configured.

  • backend/src/config/validateEnv.ts#L112-L120: derive canonical contract, RPC, and network values after parsing; validate and return those values exclusively.
  • backend/src/index.ts#L1193-L1193: return the canonical configured network rather than reading only NETWORK_PASSPHRASE.
📍 Affects 2 files
  • backend/src/config/validateEnv.ts#L112-L120 (this comment)
  • backend/src/index.ts#L1193-L1193
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/config/validateEnv.ts` around lines 112 - 120, Use one canonical
value for each Stellar setting: in backend/src/config/validateEnv.ts lines
112-120, derive contract, RPC, and network values after parsing, then validate
and return only those canonical values so either legacy or new environment
variables work consistently; update backend/src/index.ts line 1193 to use the
canonical configured network for the challenge response instead of reading only
NETWORK_PASSPHRASE.

Comment thread backend/src/index.ts
Comment on lines +1182 to +1189
app.get("/api/auth/challenge", authChallengeLimiter, (req: Request, res: Response) => {
const accountId = req.query.accountId;
if (typeof accountId !== "string" || !accountId.trim()) {
sendApiError(req, res, 400, "accountId query parameter is required.", {
code: "VALIDATION_ERROR",
});
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Validate accountId with the shared Stellar-account Zod schema.

Any non-empty value reaches generateChallenge(), where an invalid operation source can throw and become a 500. Parse req.query with a schema in backend/src/validation/schemas.ts and return 400 on validation failure.

As per coding guidelines, “validate requests with Zod schemas from backend/src/validation/schemas.ts before passing data to services.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/index.ts` around lines 1182 - 1189, Update the
`/api/auth/challenge` handler to validate the request query through the shared
Stellar-account Zod schema from `validation/schemas.ts` before calling
`generateChallenge()`. Use the schema’s parsed accountId for downstream
processing, and return the existing 400 validation response when parsing fails
instead of allowing invalid values to reach the service.

Source: Coding guidelines




runMigrations(db);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

ast-grep outline backend/src/services/db.ts --items all --type function
rg -n -C 8 '\bmigrate\s*\(|\baddColumnIfMissing\s*\(|\brunMigrations\s*\(' backend/src/services/db.ts
rg -n -C 8 'PostgresDatabase|runMigrations' backend/src

Repository: ritik4ever/stellar-stream

Length of output: 12242


🏁 Script executed:

#!/bin/bash
set -eu

printf '--- db.ts relevant sections ---\n'
sed -n '1,120p' backend/src/services/db.ts
printf '\n'
sed -n '120,240p' backend/src/services/db.ts
printf '\n'
sed -n '240,340p' backend/src/services/db.ts

printf '\n--- migrations.ts relevant sections ---\n'
sed -n '1,180p' backend/src/services/migrations.ts

printf '\n--- package/imports mentioning postgres driver ---\n'
rg -n '"better-sqlite3"|"pg"|"postgres"|"postgres-js"|postgres|PostgresDatabase|postgres' package.json backend/src

Repository: ritik4ever/stellar-stream

Length of output: 254


🏁 Script executed:

#!/bin/bash
set -eu

echo '--- db.ts relevant sections ---'
sed -n '1,120p' backend/src/services/db.ts
echo
sed -n '120,240p' backend/src/services/db.ts
echo
sed -n '240,340p' backend/src/services/db.ts

echo
echo '--- migrations.ts relevant sections ---'
sed -n '1,180p' backend/src/services/migrations.ts

echo
echo '--- package/imports mentioning postgres driver ---'
rg -n '"better-sqlite3"|"pg"|"postgres"|"postgres-js"|postgres|PostgresDatabase|postgres' package.json backend/src

Repository: ritik4ever/stellar-stream

Length of output: 15024


Keep migration execution within migrate() and the correct backend path.

initDb() now calls runMigrations(db) after both SQLite and Postgres initialization. Route this through the existing migrate() entry point so SQLite schema initialization and upgrades stay in the required backward-compatible path, and keep Postgres migrations on a path that explicitly supports PostgresDatabase; otherwise startup may fail or schema upgrades may bypass the enforced migration boundary.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/services/db.ts` at line 329, Update initDb() to invoke the
existing migrate() entry point instead of calling runMigrations(db) directly.
Ensure SQLite initialization and upgrades remain within migrate(), while the
Postgres branch uses a migration path that explicitly accepts PostgresDatabase.

Source: Coding guidelines

@ritik4ever
ritik4ever merged commit f5e463c into ritik4ever:main Jul 31, 2026
1 of 2 checks passed
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.

[FEATURE] Implement wallet-authenticated write endpoints using Stellar challenge-response

2 participants