From 6e4bed0717ad214352183a499dc961ef2039a365 Mon Sep 17 00:00:00 2001 From: ayobami Date: Sat, 21 Nov 2026 15:36:27 +0000 Subject: [PATCH 1/5] feat(backend): deliver webhook events the indexer already broadcasts dispatchWebhookEvent was exported and never called. Users could create a subscription and the test ping arrived, while no production stream event ever did: the worker broadcast SSE only, and the runway worker's comment promised "SSE and webhooks" while calling SSE alone (#1854). Both fan-outs now live in one method, so an event type cannot be added to one and forgotten in the other. Subscribers are the stream's recipient and sender; a failed delivery is logged and recorded as a delivery attempt, never rethrown, because a dead endpoint must not turn a processed chain event into a retry. The low-balance alert dispatches the same way. --- backend/src/workers/soroban-event-worker.ts | 53 ++++++++++++++++++--- backend/src/workers/stream-runway-worker.ts | 16 +++++++ 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/backend/src/workers/soroban-event-worker.ts b/backend/src/workers/soroban-event-worker.ts index bb75dcfb..e7fda276 100644 --- a/backend/src/workers/soroban-event-worker.ts +++ b/backend/src/workers/soroban-event-worker.ts @@ -3,6 +3,7 @@ import { rpc, xdr, StrKey } from "@stellar/stellar-sdk"; import { prisma } from "../lib/prisma.js"; import { INDEXER_STATE_ID, ensureIndexerState } from "../lib/indexer-state.js"; import { sseService } from "../services/sse.service.js"; +import { dispatchWebhookEvent } from "../services/webhook.service.js"; import { sentinelService } from "../services/sentinel.service.js"; import { publishIndexerLag, quarantineEvent } from "../services/indexerService.js"; import { applyToppedUpEvent } from "../services/top-up-writer.js"; @@ -661,6 +662,44 @@ export class SorobanEventWorker { } } + + /** + * Publish a stream event to SSE and, in the same breath, to webhook + * subscribers (#1854). + * + * The webhook dispatcher existed and was never called: users could create + * subscriptions and the test ping worked, while no production event ever + * reached them. Routing both fan-outs through here means a new event type + * cannot be added to one and forgotten in the other. + * + * The webhook leg is awaited but never throws: a subscription pointing at a + * dead endpoint must not turn a processed chain event into a retry, and the + * delivery record it writes is what surfaces the failure. + */ + private async publishStreamEvent( + streamId: bigint, + eventType: string, + payload: Record, + ): Promise { + sseService.broadcastToStream(String(streamId), eventType, payload); + + try { + const stream = await prisma.stream.findUnique({ + where: { streamId }, + select: { sender: true, recipient: true }, + }); + if (!stream) return; + + const addresses = [stream.recipient, stream.sender].filter(Boolean); + await dispatchWebhookEvent(eventType, payload, addresses); + } catch (error) { + logger.error( + `[Webhook] dispatch failed for ${eventType} #${streamId}:`, + error, + ); + } + } + private async handleFeeConfigUpdated( event: rpc.Api.EventResponse, ): Promise { @@ -893,7 +932,7 @@ export class SorobanEventWorker { } }); - sseService.broadcastToStream(String(streamId), "stream.created", { + await this.publishStreamEvent(streamId, "stream.created", { streamId, sender, recipient, @@ -949,7 +988,7 @@ export class SorobanEventWorker { }), ); - sseService.broadcastToStream(String(streamId), "stream.topped_up", { + await this.publishStreamEvent(streamId, "stream.topped_up", { streamId, amount, newDepositedAmount, @@ -1044,7 +1083,7 @@ export class SorobanEventWorker { }); }); - sseService.broadcastToStream(String(streamId), "stream.withdrawn", { + await this.publishStreamEvent(streamId, "stream.withdrawn", { streamId, recipient, amount, @@ -1140,7 +1179,7 @@ export class SorobanEventWorker { }); }); - sseService.broadcastToStream(String(streamId), "stream.cancelled", { + await this.publishStreamEvent(streamId, "stream.cancelled", { streamId, refundedAmount, amountWithdrawn, @@ -1213,7 +1252,7 @@ export class SorobanEventWorker { } }); - sseService.broadcastToStream(String(streamId), "stream.completed", { + await this.publishStreamEvent(streamId, "stream.completed", { streamId, recipient, totalWithdrawn, @@ -1354,7 +1393,7 @@ export class SorobanEventWorker { } }); - sseService.broadcastToStream(String(streamId), "stream.paused", { + await this.publishStreamEvent(streamId, "stream.paused", { streamId, sender, pausedAt, @@ -1446,7 +1485,7 @@ export class SorobanEventWorker { } }); - sseService.broadcastToStream(String(streamId), "stream.resumed", { + await this.publishStreamEvent(streamId, "stream.resumed", { streamId, sender, newEndTime: newEndTime.toString(), diff --git a/backend/src/workers/stream-runway-worker.ts b/backend/src/workers/stream-runway-worker.ts index a9451785..1d5129a7 100644 --- a/backend/src/workers/stream-runway-worker.ts +++ b/backend/src/workers/stream-runway-worker.ts @@ -7,6 +7,7 @@ import { prisma } from "../lib/prisma.js"; import logger from "../logger.js"; import { claimableAmountService } from "../services/claimable.service.js"; import { sseService } from "../services/sse.service.js"; +import { dispatchWebhookEvent } from "../services/webhook.service.js"; /** * Streams read per round trip. Large enough that the query count is negligible @@ -146,6 +147,21 @@ async function sendLowBalanceAlert( alertData, ); + // The low-balance alert is a stream event like any other, so it reaches + // webhook subscribers too (#1854). A failing endpoint is logged by the + // dispatcher and recorded as a delivery, never rethrown into the sweep. + try { + await dispatchWebhookEvent("stream.low_balance", alertData, [ + runway.sender, + runway.recipient, + ]); + } catch (error) { + logger.error( + `[RunwayWorker] webhook dispatch failed for stream ${runway.streamId}:`, + error, + ); + } + logger.info( `[RunwayWorker] ${alertType} alert sent for stream ${runway.streamId}: ${hoursRemaining.toFixed(1)}h remaining`, ); From a3e329dd80f027c17a76c276841e5f6d21daad78 Mon Sep 17 00:00:00 2001 From: ayobami Date: Sat, 21 Nov 2026 15:36:28 +0000 Subject: [PATCH 2/5] fix(backend): bind notification channels to the authenticated wallet The notification router trusted the client. POST /link-code took req.body.address, generated the verification code with Math.random() and returned that code in the response, so anyone could mint a code for any wallet, read it from their own HTTP response, and attach their own Telegram chat to a stranger's stream notifications. linkTelegram, setDiscordWebhook and the web-push endpoints trusted the body the same way (#1855). Every route now requires a session, and the address is the session's; a body that names another wallet is refused with 403 rather than ignored. Codes come from crypto.randomBytes (10 hex characters instead of ~31 predictable bits) and are no longer echoed back - the caller gets the address and expiry. Tests assert the code shape and that two codes differ. --- backend/src/routes/v1/notifications.routes.ts | 75 +++++++++++++++---- backend/src/services/notification.service.ts | 8 +- backend/tests/notification.service.test.ts | 13 ++++ 3 files changed, 81 insertions(+), 15 deletions(-) diff --git a/backend/src/routes/v1/notifications.routes.ts b/backend/src/routes/v1/notifications.routes.ts index 4141d548..a0eedaf3 100644 --- a/backend/src/routes/v1/notifications.routes.ts +++ b/backend/src/routes/v1/notifications.routes.ts @@ -1,37 +1,85 @@ -import { Router } from 'express'; +import { Router, type Response } from 'express'; import { notificationService } from '../../services/notification.service.js'; import { sendApiError } from '../../lib/api-error.js'; +import { requireAuth } from '../../middleware/auth.js'; +import type { AuthenticatedRequest } from '../../types/auth.types.js'; +/** + * Notification channel routes. + * + * Every route here acts on a wallet's notification settings, so every route + * requires the wallet's own session (#1855). Before this, `/link-code` took + * `req.body.address` from the body and returned the verification code in the + * response, so anyone could mint a code for anyone's wallet, read the code out + * of their own HTTP response, and attach their own Telegram chat to a stranger's + * stream notifications. `linkTelegram`, `setDiscordWebhook` and the web-push + * endpoints trusted the body the same way. + * + * The address is now the authenticated one; a body that names a different + * address is refused rather than silently ignored, so a client that sends one + * by mistake learns about it. + */ export const notificationsRouter = Router(); -notificationsRouter.post('/subscribe', async (req, res) => { +function sessionAddress(req: AuthenticatedRequest): string | null { + const address = req.user?.publicKey; + return typeof address === 'string' && address.length > 0 ? address : null; +} + +/** 401 when the session has no wallet, 403 when it names a different one. */ +function claimedAddress(req: AuthenticatedRequest, res: Response): string | null { + const session = sessionAddress(req); + if (!session) { + res.status(401).json({ error: 'Authentication required' }); + return null; + } + + const claimed = req.body?.address; + if (typeof claimed === 'string' && claimed !== session) { + res.status(403).json({ error: 'Address does not match the authenticated wallet' }); + return null; + } + + return session; +} + +notificationsRouter.post('/subscribe', requireAuth, async (req, res) => { + const address = claimedAddress(req as AuthenticatedRequest, res); + if (!address) return; try { - const result = await notificationService.subscribeWebPush(req.body); + const result = await notificationService.subscribeWebPush({ ...req.body, address }); res.status(201).json(result); } catch (err) { sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); } }); -notificationsRouter.post('/unsubscribe', async (req, res) => { +notificationsRouter.post('/unsubscribe', requireAuth, async (req, res) => { + const address = claimedAddress(req as AuthenticatedRequest, res); + if (!address) return; try { - await notificationService.unsubscribeWebPush(req.body.address, req.body.endpoint); + await notificationService.unsubscribeWebPush(address, req.body.endpoint); res.json({ ok: true }); } catch (err) { sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); } }); -notificationsRouter.post('/link-code', async (req, res) => { +notificationsRouter.post('/link-code', requireAuth, async (req, res) => { + const address = claimedAddress(req as AuthenticatedRequest, res); + if (!address) return; try { - const result = await notificationService.generateLinkCode(req.body.address); - res.json(result); + const result = await notificationService.generateLinkCode(address); + // The code goes to the operator's own channel, never back to the caller + // (#1855): returning it made the second factor meaningless, because the + // same request could attach a chat it controlled. + res.status(201).json({ address: result.address, expiresAt: result.expiresAt }); } catch (err) { sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); } }); -notificationsRouter.post('/telegram/link', async (req, res) => { +notificationsRouter.post('/telegram/link', requireAuth, async (req, res) => { try { const result = await notificationService.linkTelegram(req.body.code, req.body.chatId); res.json(result); @@ -40,12 +88,11 @@ notificationsRouter.post('/telegram/link', async (req, res) => { } }); -notificationsRouter.post('/discord', async (req, res) => { +notificationsRouter.post('/discord', requireAuth, async (req, res) => { + const address = claimedAddress(req as AuthenticatedRequest, res); + if (!address) return; try { - const result = await notificationService.setDiscordWebhook( - req.body.address, - req.body.webhookUrl, - ); + const result = await notificationService.setDiscordWebhook(address, req.body.webhookUrl); res.json(result); } catch (err) { sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); diff --git a/backend/src/services/notification.service.ts b/backend/src/services/notification.service.ts index a332e314..fe9faa91 100644 --- a/backend/src/services/notification.service.ts +++ b/backend/src/services/notification.service.ts @@ -1,3 +1,4 @@ +import crypto from 'crypto'; import { prisma } from '../lib/prisma.js'; // eslint-disable-next-line @typescript-eslint/no-var-requires import webpush from 'web-push'; @@ -61,7 +62,12 @@ export class NotificationService { } async generateLinkCode(address: string) { - const code = Math.random().toString(36).slice(2, 8).toUpperCase(); + // A verification code is a bearer secret: whoever guesses it can attach a + // chat to the wallet. Math.random() is a non-cryptographic PRNG whose + // stream is reproducible from a handful of outputs, and 6 base-36 + // characters is ~31 bits (#1855). 5 CSPRNG bytes give 10 hex characters + // that cannot be predicted from earlier codes. + const code = crypto.randomBytes(5).toString('hex').toUpperCase(); const expiresAt = new Date(Date.now() + 15 * 60 * 1000); return prisma.linkCode.create({ data: { code, address, expiresAt } }); } diff --git a/backend/tests/notification.service.test.ts b/backend/tests/notification.service.test.ts index b9a95315..a6702db4 100644 --- a/backend/tests/notification.service.test.ts +++ b/backend/tests/notification.service.test.ts @@ -338,6 +338,19 @@ describe('NotificationService', () => { expect(result).toHaveProperty('code'); expect(result.address).toBe('GUSER123'); expect(prismaMock.linkCode.create).toHaveBeenCalledTimes(1); + + // #1855: the code must come from a CSPRNG, not Math.random(). Ten + // uppercase hex characters: enough entropy that it cannot be predicted + // from previously issued codes, and cheap to type. + expect(result.code).toMatch(/^[0-9A-F]{10}$/); + + // Two codes for the same wallet must differ. + prismaMock.linkCode.create.mockImplementation(async ({ data }) => ({ + id: 'lc-2', + ...data, + })); + const second = await service.generateLinkCode('GUSER123'); + expect(second.code).not.toBe(result.code); }); it('links telegram when code is valid', async () => { From 902267298d691a02436d0169d00d28e304c7044b Mon Sep 17 00:00:00 2001 From: ayobami Date: Sat, 21 Nov 2026 15:36:28 +0000 Subject: [PATCH 3/5] fix(contracts): settle vested amounts before modify_rate moves the anchor modify_rate set rate and last_update_time with no settlement, contradicting the rationale top_up_stream documents: last_update_time is the accrual anchor, and advancing it discards everything already vested but unwithdrawn. A recipient had to re-accrue tokens they had already earned, and a sender could call this with rate 1 to defer vested wages arbitrarily (#1862). The vested interval is now paid out at the old rate before the anchor moves. It is a real withdrawal rather than a bookkeeping credit: claimable is elapsed*rate clamped to deposited-withdrawn, so crediting withdrawn_amount without paying would delete the tokens. The payout reuses apply_withdrawal (state committed before transfer) and emits TokensWithdrawn, the event the backend indexer books withdrawals from, so the off-chain figure cannot drift. Three tests: paid-before-change with continuity across the change, nothing taken when nothing vested, and a paused stream settling only up to its pause. --- contracts/stream_contract/src/lib.rs | 42 +++++++++++++- contracts/stream_contract/src/test.rs | 80 +++++++++++++++++++++++++++ 2 files changed, 121 insertions(+), 1 deletion(-) diff --git a/contracts/stream_contract/src/lib.rs b/contracts/stream_contract/src/lib.rs index eee7a309..cc1b3c9a 100644 --- a/contracts/stream_contract/src/lib.rs +++ b/contracts/stream_contract/src/lib.rs @@ -2898,7 +2898,47 @@ impl StreamContract { let now = env.ledger().timestamp(); let old_rate = stream.rate_per_second; - // Update the rate + // Settle what has already vested at the old rate before the accrual + // anchor moves (#1862). + // + // `last_update_time` is the anchor `calculate_claimable` measures from + // (the same rationale `top_up_stream` documents). Advancing it without + // settling folds everything the recipient had already earned back into + // the unstreamed remainder, so they have to wait for the *new* rate to + // re-accrue tokens that were already theirs — a sender can call this + // with rate 1 to defer vested wages arbitrarily. + // + // Settling is a real withdrawal, not a bookkeeping credit: the claimable + // figure is `elapsed * rate` clamped to `deposited - withdrawn`, so + // crediting `withdrawn_amount` without paying out would delete the + // tokens instead of preserving them. The payment is committed to storage + // before the transfer (CEI), and it reuses the same event the backend + // indexer books ordinary withdrawals from, so the off-chain + // `withdrawn_amount` cannot drift. + let settled_amount = Self::calculate_claimable(&stream, now); + if settled_amount > 0 { + let recipient = stream.recipient.clone(); + Self::apply_withdrawal( + &env, + &mut stream, + stream_id, + &recipient, + settled_amount, + now, + )?; + emit_tokens_withdrawn( + &env, + TokensWithdrawnEvent { + stream_id, + recipient, + amount: settled_amount, + timestamp: now, + }, + ); + } + + // Update the rate. The anchor still moves to `now`, but only after the + // interval it measured has been paid out, so nothing accrued is lost. stream.rate_per_second = new_rate_per_second; stream.last_update_time = now; diff --git a/contracts/stream_contract/src/test.rs b/contracts/stream_contract/src/test.rs index a5ef6d3e..9e83f77a 100644 --- a/contracts/stream_contract/src/test.rs +++ b/contracts/stream_contract/src/test.rs @@ -6865,6 +6865,86 @@ fn test_coverage_modify_rate_recomputes_end_time_and_emits() { assert_eq!(stream.last_update_time, now); } +#[test] +fn test_coverage_modify_rate_settles_accrued_amount_before_anchor_moves() { + // #1862: everything vested when the rate changes is paid out at the old + // rate. Before this, the anchor moved without settling and the recipient + // had to re-accrue tokens they had already earned. + let env = Env::default(); + env.mock_all_auths(); + let (token, _) = create_token(&env); + let client = create_contract(&env); + let sender = Address::generate(&env); + let recipient = Address::generate(&env); + mint(&env, &token, &sender, 1_000); + + // 1_000 over 1_000s → 1 token per second. + let id = client.create_stream(&sender, &recipient, &token, &1_000, &1_000); + advance(&env, 100); + + let new_end = client.modify_rate(&sender, &id, &2); + let now = env.ledger().timestamp(); + let stream = client.get_stream(&id).unwrap(); + + // The 100 tokens accrued at the old rate were paid, not discarded. + assert_eq!(stream.withdrawn_amount, 100); + assert_eq!(token::Client::new(&env, &token).balance(&recipient), 100); + + // The new rate applies only to the 900 that had not vested yet. + assert_eq!(stream.rate_per_second, 2); + assert_eq!(stream.last_update_time, now); + assert_eq!(new_end, now + 450); + + // Continuity: 50s at the new rate adds 100 more, on top of what was paid. + advance(&env, 50); + assert_eq!(client.withdraw(&recipient, &id), 100); + assert_eq!(token::Client::new(&env, &token).balance(&recipient), 200); +} + +#[test] +fn test_coverage_modify_rate_takes_nothing_when_nothing_has_vested() { + // The common case — a rate change moments after creation — must stay a + // pure bookkeeping change: no transfer, no withdrawal booked. + let env = Env::default(); + env.mock_all_auths(); + let (token, _) = create_token(&env); + let client = create_contract(&env); + let sender = Address::generate(&env); + let recipient = Address::generate(&env); + mint(&env, &token, &sender, 1_000); + + let id = client.create_stream(&sender, &recipient, &token, &1_000, &1_000); + client.modify_rate(&sender, &id, &2); + + let stream = client.get_stream(&id).unwrap(); + assert_eq!(stream.withdrawn_amount, 0); + assert_eq!(token::Client::new(&env, &token).balance(&recipient), 0); + assert_eq!(token::Client::new(&env, &token).balance(&client.address), 1_000); +} + +#[test] +fn test_coverage_modify_rate_settles_up_to_the_pause_point_only() { + // A paused stream accrues nothing after the pause, so a rate change while + // paused settles exactly the interval that ran before it. + let env = Env::default(); + env.mock_all_auths(); + let (token, _) = create_token(&env); + let client = create_contract(&env); + let sender = Address::generate(&env); + let recipient = Address::generate(&env); + mint(&env, &token, &sender, 1_000); + + let id = client.create_stream(&sender, &recipient, &token, &1_000, &1_000); + advance(&env, 100); + client.pause_stream(&sender, &id); + advance(&env, 500); + + client.modify_rate(&sender, &id, &4); + + let stream = client.get_stream(&id).unwrap(); + assert_eq!(stream.withdrawn_amount, 100); + assert_eq!(token::Client::new(&env, &token).balance(&recipient), 100); +} #[test] fn test_coverage_modify_rate_rejects_non_linear_schedule() { let env = Env::default(); From 4a1253c5671e8e5bd5511970b07d8998b6a248e9 Mon Sep 17 00:00:00 2001 From: king-daveed Date: Tue, 24 Nov 2026 14:40:50 +0000 Subject: [PATCH 4/5] fix(backend): throttle the notification channel routes Every handler on this router authenticates a wallet and then writes a per-wallet record, which CodeQL flags as authorization without rate limiting. Apply the shared express-rate-limit factory to the whole router so a flood is rejected before any work happens. --- backend/src/middleware/rate-limiter.middleware.ts | 15 +++++++++++++++ backend/src/routes/v1/notifications.routes.ts | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/backend/src/middleware/rate-limiter.middleware.ts b/backend/src/middleware/rate-limiter.middleware.ts index 59101744..5f50e2d0 100644 --- a/backend/src/middleware/rate-limiter.middleware.ts +++ b/backend/src/middleware/rate-limiter.middleware.ts @@ -67,3 +67,18 @@ export const healthRateLimiter = createRateLimiter({ message: 'Too many health check requests, please try again later.', handler: rateLimitHandler, }); + +/** + * Limiter for the notification-channel routes (#1855, #1931). + * + * Every one of those handlers authenticates a wallet and then writes to a + * per-wallet record, so an unthrottled caller could use them to enumerate + * verification codes or spray channel registrations. The window is generous + * for a human configuring alerts and tight enough to stop a script. + */ +export const notificationRateLimiter = createRateLimiter({ + windowMs: 60 * 1000, + max: 30, + message: 'Too many notification requests, please try again later.', + handler: rateLimitHandler, +}); diff --git a/backend/src/routes/v1/notifications.routes.ts b/backend/src/routes/v1/notifications.routes.ts index a0eedaf3..cb95349f 100644 --- a/backend/src/routes/v1/notifications.routes.ts +++ b/backend/src/routes/v1/notifications.routes.ts @@ -2,6 +2,7 @@ import { Router, type Response } from 'express'; import { notificationService } from '../../services/notification.service.js'; import { sendApiError } from '../../lib/api-error.js'; import { requireAuth } from '../../middleware/auth.js'; +import { notificationRateLimiter } from '../../middleware/rate-limiter.middleware.js'; import type { AuthenticatedRequest } from '../../types/auth.types.js'; /** @@ -21,6 +22,10 @@ import type { AuthenticatedRequest } from '../../types/auth.types.js'; */ export const notificationsRouter = Router(); +// Throttle before the auth/authorization work below runs, so a flood is cheap +// to reject (CodeQL js/missing-rate-limiting, #1931). +notificationsRouter.use(notificationRateLimiter); + function sessionAddress(req: AuthenticatedRequest): string | null { const address = req.user?.publicKey; return typeof address === 'string' && address.length > 0 ? address : null; From 32b9134766899db327317856436465949cb3d883 Mon Sep 17 00:00:00 2001 From: king-daveed Date: Tue, 24 Nov 2026 16:13:12 +0000 Subject: [PATCH 5/5] style(contracts): rustfmt the settle-before-modify tests --- contracts/stream_contract/src/test.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/contracts/stream_contract/src/test.rs b/contracts/stream_contract/src/test.rs index 9e83f77a..7d39d9f6 100644 --- a/contracts/stream_contract/src/test.rs +++ b/contracts/stream_contract/src/test.rs @@ -6919,7 +6919,10 @@ fn test_coverage_modify_rate_takes_nothing_when_nothing_has_vested() { let stream = client.get_stream(&id).unwrap(); assert_eq!(stream.withdrawn_amount, 0); assert_eq!(token::Client::new(&env, &token).balance(&recipient), 0); - assert_eq!(token::Client::new(&env, &token).balance(&client.address), 1_000); + assert_eq!( + token::Client::new(&env, &token).balance(&client.address), + 1_000 + ); } #[test]