Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions backend/src/middleware/rate-limiter.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
80 changes: 66 additions & 14 deletions backend/src/routes/v1/notifications.routes.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,90 @@
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 { notificationRateLimiter } from '../../middleware/rate-limiter.middleware.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) => {
// 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;
}

/** 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) => {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
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) => {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
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) => {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
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) => {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
try {
const result = await notificationService.linkTelegram(req.body.code, req.body.chatId);
res.json(result);
Expand All @@ -40,12 +93,11 @@ notificationsRouter.post('/telegram/link', async (req, res) => {
}
});

notificationsRouter.post('/discord', async (req, res) => {
notificationsRouter.post('/discord', requireAuth, async (req, res) => {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
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');
Expand Down
8 changes: 7 additions & 1 deletion backend/src/services/notification.service.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 } });
}
Expand Down
53 changes: 46 additions & 7 deletions backend/src/workers/soroban-event-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string, unknown>,
): Promise<void> {
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<void> {
Expand Down Expand Up @@ -893,7 +932,7 @@ export class SorobanEventWorker {
}
});

sseService.broadcastToStream(String(streamId), "stream.created", {
await this.publishStreamEvent(streamId, "stream.created", {
streamId,
sender,
recipient,
Expand Down Expand Up @@ -949,7 +988,7 @@ export class SorobanEventWorker {
}),
);

sseService.broadcastToStream(String(streamId), "stream.topped_up", {
await this.publishStreamEvent(streamId, "stream.topped_up", {
streamId,
amount,
newDepositedAmount,
Expand Down Expand Up @@ -1044,7 +1083,7 @@ export class SorobanEventWorker {
});
});

sseService.broadcastToStream(String(streamId), "stream.withdrawn", {
await this.publishStreamEvent(streamId, "stream.withdrawn", {
streamId,
recipient,
amount,
Expand Down Expand Up @@ -1140,7 +1179,7 @@ export class SorobanEventWorker {
});
});

sseService.broadcastToStream(String(streamId), "stream.cancelled", {
await this.publishStreamEvent(streamId, "stream.cancelled", {
streamId,
refundedAmount,
amountWithdrawn,
Expand Down Expand Up @@ -1213,7 +1252,7 @@ export class SorobanEventWorker {
}
});

sseService.broadcastToStream(String(streamId), "stream.completed", {
await this.publishStreamEvent(streamId, "stream.completed", {
streamId,
recipient,
totalWithdrawn,
Expand Down Expand Up @@ -1354,7 +1393,7 @@ export class SorobanEventWorker {
}
});

sseService.broadcastToStream(String(streamId), "stream.paused", {
await this.publishStreamEvent(streamId, "stream.paused", {
streamId,
sender,
pausedAt,
Expand Down Expand Up @@ -1446,7 +1485,7 @@ export class SorobanEventWorker {
}
});

sseService.broadcastToStream(String(streamId), "stream.resumed", {
await this.publishStreamEvent(streamId, "stream.resumed", {
streamId,
sender,
newEndTime: newEndTime.toString(),
Expand Down
16 changes: 16 additions & 0 deletions backend/src/workers/stream-runway-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`,
);
Expand Down
13 changes: 13 additions & 0 deletions backend/tests/notification.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
42 changes: 41 additions & 1 deletion contracts/stream_contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Loading
Loading