Skip to content

Implement SEP-10 authentication middleware#175

Merged
ogazboiz merged 12 commits intoLabsCrypt:mainfrom
Armolas:backend/auth-middleware
Feb 26, 2026
Merged

Implement SEP-10 authentication middleware#175
ogazboiz merged 12 commits intoLabsCrypt:mainfrom
Armolas:backend/auth-middleware

Conversation

@Armolas
Copy link
Copy Markdown
Contributor

@Armolas Armolas commented Feb 25, 2026

Description

Implements Stellar-based authentication middleware using signed transactions (SEP-10 pattern) to verify wallet ownership and secure API endpoints. The middleware extracts Bearer tokens from request headers, verifies Stellar signatures using stellar-sdk, and attaches authenticated user information to requests.

Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📚 Documentation update
  • 🔧 Refactoring (no functional changes)
  • ⚡ Performance improvement
  • 🧪 Test addition or update

Related Issues

Closes #74

Changes Made

New Files

  • src/middleware/auth.middleware.ts - Core authentication middleware with signature verification logic
    • authMiddleware - Requires valid authentication (returns 401 if missing/invalid)
    • optionalAuthMiddleware - Allows requests with or without authentication
  • src/types/auth.types.ts - TypeScript type definitions for authentication
    • AuthUser interface - Authenticated user shape
    • AuthenticatedRequest interface - Express request with user attached
  • docs/AUTHENTICATION.md - Comprehensive authentication documentation with examples

Modified Files

  • src/routes/v1/user.routes.ts - Added protected GET /v1/users/me endpoint as example
  • src/controllers/user.controller.ts - Added getCurrentUser controller
    • Returns user from database if exists
    • Returns in-memory user object if database record missing (database independence)
  • src/config/swagger.ts - Added BearerAuth security scheme to OpenAPI spec
  • package.json - Added @stellar/stellar-sdk dependency for signature verification

Key Implementation Details

Extract token from Bearer header - Validates Authorization: Bearer <xdr> format
Verify signature against public key - Uses stellar-sdk to cryptographically verify transaction signatures
Attach req.user object - Adds { publicKey, id? } to request for downstream use
Database independence - Creates in-memory user if DB lookup fails (never blocks on missing DB record)

Additional Features

  • Network support (testnet/mainnet) via STELLAR_NETWORK environment variable
  • Transaction time bounds validation to prevent replay attacks
  • Comprehensive error messages for debugging authentication issues
  • Logger integration for security audit trail

Testing

Test Coverage

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed

Test Steps

Manual Testing Performed:

  1. Valid Authentication

    • Created Stellar signed transaction with test keypair
    • Encoded transaction to XDR format
    • Sent request to GET /v1/users/me with Authorization: Bearer <xdr>
    • Verified 200 response with user data
  2. Missing Token

    • Sent request without Authorization header
    • Verified 401 response with appropriate error message
  3. Invalid Signature

    • Modified XDR signature to be invalid
    • Verified 401 response indicating invalid signature
  4. Database Independence

    • Authenticated with valid signature for non-existent user
    • Verified 200 response with in-memory user object
  5. Network Configuration

    • Tested with STELLAR_NETWORK=testnet
    • Verified testnet network passphrase used for validation

To Test This PR:

  1. Start the backend server: npm run dev
  2. Create a Stellar signed transaction (see AUTHENTICATION.md for example)
  3. Send authenticated request:
    curl -X GET http://localhost:3001/v1/users/me \
      -H "Authorization: Bearer <your_signed_transaction_xdr>"
  4. Verify successful authentication and user data response

Breaking Changes

None - This is a new feature that adds authentication capabilities without modifying existing endpoints.

Screenshots/Demo

N/A - Backend API feature

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published
  • I have checked for breaking changes and documented them if applicable

Additional Notes

Security Considerations

  • All signature verification is done server-side using cryptographic validation
  • No sensitive credentials stored on server
  • Time-bound transactions prevent replay attacks when implemented by clients
  • Logger captures authentication attempts for security auditing

Documentation

Complete usage guide available in docs/AUTHENTICATION.md including:

  • Detailed implementation guide
  • Client-side transaction signing examples
  • Error response documentation
  • TypeScript type references
  • SEP-10 specification links

Future Work

  • Add unit tests for middleware functions
  • Add integration tests for protected endpoints
  • Consider implementing SEP-10 challenge/response flow for enhanced security
  • Add rate limiting specific to authentication endpoints

@Armolas Armolas force-pushed the backend/auth-middleware branch from 12854e8 to c65f1e6 Compare February 25, 2026 10:46
Copy link
Copy Markdown
Contributor

@ogazboiz ogazboiz left a comment

Choose a reason for hiding this comment

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

hey! thanks for the solid implementation of the SEP-10 auth middleware. the documentation looks great and the logic seems sound for a first pass.

however, the CI checks are currently failing on several fronts (Backend, Frontend, and Dependency Scan). could you take a look at the logs in the "Checks" tab and see what's causing the break?

also, it looks like there might be some unrelated changes or conflicts in the package-lock.json. it would be great if you could clean that up while you're at it!

let us know once CI is green and we'll do a final review.

- Add authMiddleware to verify Stellar signed messages
- Extract Bearer token from Authorization header
- Verify signature against public key using stellar-sdk
- Attach req.user object to authenticated requests
- Support both testnet and mainnet configurations
- Add optionalAuthMiddleware for endpoints with optional auth
- Create /v1/users/me protected endpoint as example
- Return in-memory user if database record doesn't exist
- Add BearerAuth security scheme to Swagger
- Create comprehensive AUTHENTICATION.md documentation

Implements issue LabsCrypt#74 acceptance criteria:
✅ Extract token from Bearer header
✅ Verify signature against public key
✅ Attach req.user object to request
✅ Independent of database (creates in-memory user if missing)
- Fix type error in auth.middleware.ts (Bearer token extraction)
- Fix Prisma import in error.middleware.ts (use generated client)
- Fix ZodError.errors to ZodError.issues
- Fix req.params type safety in user.controller.ts
- Add missing vitest and supertest dependencies
- Fix sandbox.ts: Use conditional property assignment for optional databaseUrl
- Fix stream.controller.ts: Add explicit type assertion for req.params
- Fix sandbox.middleware.ts: Fix void return type by splitting return statements
- Fix prisma-sandbox.ts: Remove unsupported datasources config (Prisma 7)

All TypeScript errors resolved - build passes successfully.
Regenerated package-lock.json cleanly from upstream/main to remove
merge conflicts and unrelated dependency changes.

Only includes Stellar SDK dependencies needed for auth middleware:
- @stellar/stellar-sdk
- stellar-sdk (legacy)
- vitest and supertest (test dependencies)
@Armolas Armolas force-pushed the backend/auth-middleware branch from 17abc35 to 3b6a279 Compare February 25, 2026 16:31
The project uses npm workspaces with a single root package-lock.json,
but the CI was looking for workspace-specific package-lock.json files
that don't exist (frontend/package-lock.json, backend/package-lock.json).

Changes:
- Remove cache-dependency-path (uses root package-lock.json by default)
- Run 'npm ci' from root (installs all workspaces)
- Keep working-directory for build/lint/test commands

This fixes the 'Some specified paths were not resolved' cache error.
Add --include=optional flag to npm ci to ensure rollup's
platform-specific binaries are installed correctly on Linux.

This fixes the 'Cannot find module @rollup/rollup-linux-x64-gnu' error
that occurs when vitest tries to run tests.
Frontend build was failing with missing lightningcss native binaries.
Adding --include=optional ensures platform-specific optional dependencies
like @next/swc-linux-x64-gnu and lightningcss.linux-x64-gnu.node are
properly installed on CI runners.
- Install lightningcss platform-specific binaries (darwin-arm64, linux-x64-gnu)
- Fix dashboard-view.tsx: Replace getMockDashboardStats with fetchDashboardData
- Add proper state management for dashboard data loading
- Fix dashboard.ts: Import WalletId type and update mock data structure
- Update DashboardSnapshot to use outgoingStreams/incomingStreams
Resolve conflicts by:
- Keeping SEP-10 auth middleware implementation
- Keeping updated Stellar SDK v14.5.0 for auth support
- Merging both getUserEvents (from upstream) and getCurrentUser (from auth)
- Accepting upstream frontend changes (stream details, cancel, top-up flows)
- Accepting upstream backend changes (Soroban event worker, activity history)
Copy link
Copy Markdown
Contributor

@ogazboiz ogazboiz left a comment

Choose a reason for hiding this comment

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

hey, thanks for the contribution!

just had a look at this — the backend and frontend CI checks are currently failing and there are merge conflicts with main.

could you pull the latest changes, resolve the conflicts, and take a look at the workflow logs under the "Checks" tab to fix the failing steps?

once that's sorted let us know and we'll take another look — happy to help if you get stuck! if you want to contribute more or follow up if issues are open, join us on Telegram: https://t.me/+DOylgFv1jyJlNzM0

- Fix stream.controller.ts: Use proper parameter validation from upstream
- Fix user.controller.ts: Add type assertion for publicKey parameter
- Fix soroban-event-worker.ts: Use stellar-sdk v13 for RPC compatibility
- Auth middleware uses @stellar/stellar-sdk v14 for SEP-10 support
@ogazboiz ogazboiz merged commit 6068c0a into LabsCrypt:main Feb 26, 2026
1 of 3 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.

Backend: User Auth Middleware (SIWE)

2 participants