feat: secure proof-of-payment download routes with shareId validation

Changes:
- Update download links in UI to use shareId instead of locationID
- Add shareId validation to per-bill proof download route
- Add shareId validation to combined proof download route
- Validate TTL before allowing downloads
- Extract locationId from shareId using extractShareId helper

Security:
- Download routes now validate checksum and TTL
- Prevents unauthorized access to proof-of-payment files
- Returns 404 for invalid/expired share links

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Knee Cola
2025-12-08 01:01:38 +01:00
parent 669fb08582
commit f19e1bc023
5 changed files with 63 additions and 16 deletions

View File

@@ -1,15 +1,30 @@
import { getDbClient } from '@/app/lib/dbClient'; import { getDbClient } from '@/app/lib/dbClient';
import { BillingLocation } from '@/app/lib/db-types'; import { BillingLocation } from '@/app/lib/db-types';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { extractShareId, validateShareChecksum } from '@/app/lib/shareChecksum';
export async function GET(request: Request, { params: { id } }: { params: { id: string } }) { export async function GET(request: Request, { params: { id } }: { params: { id: string } }) {
const locationID = id; const shareId = id;
// Validate shareId and extract locationId
const extracted = extractShareId(shareId);
if (!extracted) {
notFound();
}
const { locationId: locationID, checksum } = extracted;
// Validate checksum
if (!validateShareChecksum(locationID, checksum)) {
notFound();
}
const dbClient = await getDbClient(); const dbClient = await getDbClient();
const location = await dbClient.collection<BillingLocation>("lokacije") const location = await dbClient.collection<BillingLocation>("lokacije")
.findOne({ _id: locationID }, { .findOne({ _id: locationID }, {
projection: { projection: {
utilBillsProofOfPayment: 1, utilBillsProofOfPayment: 1,
shareTTL: 1,
} }
}); });
@@ -17,6 +32,11 @@ export async function GET(request: Request, { params:{ id } }: { params: { id:st
notFound(); notFound();
} }
// Check if sharing is active and not expired
if (!location.shareTTL || new Date() > location.shareTTL) {
notFound();
}
// Convert fileContentsBase64 from Base64 string to binary // Convert fileContentsBase64 from Base64 string to binary
const fileContentsBuffer = Buffer.from(location.utilBillsProofOfPayment.fileContentsBase64, 'base64'); const fileContentsBuffer = Buffer.from(location.utilBillsProofOfPayment.fileContentsBase64, 'base64');

View File

@@ -1,12 +1,28 @@
import { getDbClient } from '@/app/lib/dbClient'; import { getDbClient } from '@/app/lib/dbClient';
import { BillingLocation } from '@/app/lib/db-types'; import { BillingLocation } from '@/app/lib/db-types';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { extractShareId, validateShareChecksum } from '@/app/lib/shareChecksum';
export async function GET(_request: Request, { params: { id } }: { params: { id: string } }) { export async function GET(_request: Request, { params: { id } }: { params: { id: string } }) {
// Parse locationID-billID format // Parse shareId-billID format
const [locationID, billID] = id.split('-'); // shareId = 40 chars (locationId 24 + checksum 16)
const shareId = id.substring(0, 40);
const billID = id.substring(41); // Skip the '-' separator
if (!locationID || !billID) { if (!shareId || !billID) {
notFound();
}
// Validate shareId and extract locationId
const extracted = extractShareId(shareId);
if (!extracted) {
notFound();
}
const { locationId: locationID, checksum } = extracted;
// Validate checksum
if (!validateShareChecksum(locationID, checksum)) {
notFound(); notFound();
} }
@@ -14,9 +30,10 @@ export async function GET(_request: Request, { params:{ id } }: { params: { id:s
const location = await dbClient.collection<BillingLocation>("lokacije") const location = await dbClient.collection<BillingLocation>("lokacije")
.findOne({ _id: locationID }, { .findOne({ _id: locationID }, {
projection: { projection: {
// Don't load bill attachments, only proof of payment // Don't load bill attachments, only proof of payment and shareTTL
"bills._id": 1, "bills._id": 1,
"bills.proofOfPayment": 1, "bills.proofOfPayment": 1,
"shareTTL": 1,
} }
}); });
@@ -24,6 +41,11 @@ export async function GET(_request: Request, { params:{ id } }: { params: { id:s
notFound(); notFound();
} }
// Check if sharing is active and not expired
if (!location.shareTTL || new Date() > location.shareTTL) {
notFound();
}
// Find the specific bill // Find the specific bill
const bill = location.bills.find(b => b._id === billID); const bill = location.bills.find(b => b._id === billID);

View File

@@ -10,6 +10,7 @@ import Link from "next/link";
import { useLocale, useTranslations } from "next-intl"; import { useLocale, useTranslations } from "next-intl";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
import { get } from "http"; import { get } from "http";
import { generateShareLink } from "../lib/actions/locationActions";
export interface LocationCardProps { export interface LocationCardProps {
location: BillingLocation; location: BillingLocation;
@@ -33,15 +34,19 @@ export const LocationCard: FC<LocationCardProps> = ({ location, currency }) => {
// sum all the paid bill amounts (regardless of who pays) // sum all the paid bill amounts (regardless of who pays)
const monthlyExpense = bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0); const monthlyExpense = bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0);
const handleCopyLinkClick = () => { const handleCopyLinkClick = async () => {
// copy URL to clipboard // copy URL to clipboard
const url = `${window.location.origin}/${currentLocale}/share/location/${_id}`; const shareLink = await generateShareLink(_id);
navigator.clipboard.writeText(url);
// use NextJS toast to notiy user that the link was copied if(shareLink.error) {
toast.error(shareLink.error, { theme: "dark" });
} else {
navigator.clipboard.writeText(shareLink.shareUrl as string);
toast.success(t("link-copy-message"), { theme: "dark" }); toast.success(t("link-copy-message"), { theme: "dark" });
} }
}
return ( return (
<div data-key={_id} className="card card-compact card-bordered max-w-[30em] bg-base-100 border-1 border-neutral my-1"> <div data-key={_id} className="card card-compact card-bordered max-w-[30em] bg-base-100 border-1 border-neutral my-1">
<div className="card-body"> <div className="card-body">

View File

@@ -130,7 +130,7 @@ export const ViewBillCard: FC<ViewBillCardProps> = ({ location, bill, shareId })
proofOfPaymentFilename ? ( proofOfPaymentFilename ? (
<div className="mt-3 ml-[-.5rem]"> <div className="mt-3 ml-[-.5rem]">
<Link <Link
href={`/share/proof-of-payment/per-bill/${locationID}-${billID}/`} href={`/share/proof-of-payment/per-bill/${shareId || locationID}-${billID}/`}
target="_blank" target="_blank"
className='text-center w-full max-w-[20rem] text-nowrap truncate inline-block' className='text-center w-full max-w-[20rem] text-nowrap truncate inline-block'
> >

View File

@@ -195,7 +195,7 @@ export const ViewLocationCard: FC<ViewLocationCardProps> = ({ location, userSett
attachmentFilename ? ( attachmentFilename ? (
<div className="mt-3 ml-[-.5rem]"> <div className="mt-3 ml-[-.5rem]">
<Link <Link
href={`/share/proof-of-payment/combined/${_id}/`} href={`/share/proof-of-payment/combined/${shareId || _id}/`}
target="_blank" target="_blank"
className='text-center w-full max-w-[20rem] text-nowrap truncate inline-block' className='text-center w-full max-w-[20rem] text-nowrap truncate inline-block'
> >