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
4 changes: 3 additions & 1 deletion apps/web/app/routes/budget.recurring.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
and,
visibleRecurringRulesCondition,
eq,
isNull,
parseHomeCurrency,
} from "@amigo/db";
import { RecurringList } from "@/app/components/recurring-list";
Expand All @@ -31,7 +32,8 @@ export async function loader({ context }: LoaderFunctionArgs) {
const rules = await db.query.recurringTransactions.findMany({
where: and(
scopeToHousehold(recurringTransactions.householdId, session.householdId),
visibleRecurringRulesCondition(session.userId)
visibleRecurringRulesCondition(session.userId),
isNull(recurringTransactions.deletedAt)
),
orderBy: (r, { desc }) => [desc(r.createdAt)],
});
Expand Down
12 changes: 2 additions & 10 deletions apps/web/server/api/accounts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
and,
CURRENCY_CODES,
eq,
financialAccounts,
FINANCIAL_ACCOUNT_TYPES,
Expand All @@ -23,16 +22,9 @@ import { enforceRateLimit, ROUTE_RATE_LIMITS } from "../middleware/rate-limit";
import { getSplatSegments, type ApiHandler } from "./route";
import { getHomeCurrency } from "../lib/household-currency";
import { insertManyAuditLogs, withAudit } from "../lib/audit";
import { zCurrencyCode } from "../lib/request-validation";

const zCurrencyCode = z.enum(
CURRENCY_CODES as unknown as [CurrencyCode, ...CurrencyCode[]]
);
const zAccountType = z.enum(
FINANCIAL_ACCOUNT_TYPES as unknown as [
(typeof FINANCIAL_ACCOUNT_TYPES)[number],
...(typeof FINANCIAL_ACCOUNT_TYPES)[number][],
]
);
const zAccountType = z.enum(FINANCIAL_ACCOUNT_TYPES);

const createAccountSchema = z.object({
name: z.string().min(1),
Expand Down
1 change: 1 addition & 0 deletions apps/web/server/api/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ async function assertCanViewAuditRecord(
});
break;
case "recurring_transactions":
// Tombstones remain readable for audit history authorization.
record = await db.query.recurringTransactions.findFirst({
where: and(
eq(recurringTransactions.id, recordId),
Expand Down
3 changes: 2 additions & 1 deletion apps/web/server/api/budgets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ export const handleBudgetsRequest: ApiHandler = async ({
where: and(
eq(recurringTransactions.id, recurringRuleId),
scopeToHousehold(recurringTransactions.householdId, session!.householdId),
visibleRecurringRulesCondition(session!.userId)
visibleRecurringRulesCondition(session!.userId),
isNull(recurringTransactions.deletedAt)
),
});
if (rule?.budgetId) {
Expand Down
8 changes: 7 additions & 1 deletion apps/web/server/api/calendar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,13 @@ export const handleCalendarRequest: ApiHandler = async ({
db
.select()
.from(recurringTransactions)
.where(and(householdScope, visibleRecurringRulesCondition(session!.userId)))
.where(
and(
householdScope,
visibleRecurringRulesCondition(session!.userId),
isNull(recurringTransactions.deletedAt)
)
)
.all(),
db
.select()
Expand Down
3 changes: 2 additions & 1 deletion apps/web/server/api/debts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ import { enforceRateLimit, ROUTE_RATE_LIMITS } from "../middleware/rate-limit";
import { getSplatSegments, type ApiHandler } from "./route";
import { getHomeCurrency } from "../lib/household-currency";
import { withAudit } from "../lib/audit";
import { zCurrencyCode } from "../lib/request-validation";

const currencySchema = z.enum(["CAD", "USD", "EUR", "GBP", "MXN"]).optional();
const currencySchema = zCurrencyCode.optional();

const loanShape = {
type: z.literal("LOAN"),
Expand Down
117 changes: 91 additions & 26 deletions apps/web/server/api/invites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { assertPermission, canManageMembers } from "../lib/permissions";
import { assertSessionStillValid } from "../lib/session";
import { enforceRateLimit, ROUTE_RATE_LIMITS } from "../middleware/rate-limit";
import { getSplatPath, getSplatSegments, type ApiHandler } from "./route";
import { insertManyAuditLogs, withAudit } from "../lib/audit";

const INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
/** Stable client-facing message — never echo provider Error.message. */
Expand Down Expand Up @@ -174,15 +175,34 @@ export const handleInvitesRequest: ApiHandler = async ({
throw new ActionError("Household not found", "NOT_FOUND");
}

await db.insert(householdInvites).values({
id: inviteIdValue,
householdId: session!.householdId,
codeHash,
codeDisplay,
createdByUserId: session!.userId,
invitedEmail,
expiresAt,
});
await withAudit(
db,
{
householdId: session!.householdId,
tableName: "household_invites",
recordId: inviteIdValue,
operation: "INSERT",
newValues: {
id: inviteIdValue,
expiresAt: expiresAt.toISOString(),
createdByUserId: session!.userId,
hasInvitedEmail: Boolean(invitedEmail),
},
changedBy: session!.userId,
},
async () => {
await db.insert(householdInvites).values({
id: inviteIdValue,
householdId: session!.householdId,
codeHash,
codeDisplay,
createdByUserId: session!.userId,
invitedEmail,
expiresAt,
});
return { id: inviteIdValue };
}
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

let emailSent = false;
let emailError: string | null = null;
Expand Down Expand Up @@ -267,23 +287,44 @@ export const handleInvitesRequest: ApiHandler = async ({
throw new ActionError("Invite already revoked", "VALIDATION_ERROR");
}

const revoked = await db
.update(householdInvites)
.set({ revokedAt: new Date() })
.where(
and(
eq(householdInvites.id, inviteId),
scopeToHousehold(householdInvites.householdId, session!.householdId),
isNull(householdInvites.usedAt),
isNull(householdInvites.revokedAt)
)
)
.returning({ id: householdInvites.id })
.get();

if (!revoked) {
throw new ActionError("Invite is no longer valid", "VALIDATION_ERROR");
}
await withAudit(
db,
{
householdId: session!.householdId,
tableName: "household_invites",
recordId: inviteId,
operation: "UPDATE",
oldValues: { revokedAt: null },
newValues: (result) => ({ revokedAt: result.revokedAt }),
changedBy: session!.userId,
},
async () => {
const result = await db
.update(householdInvites)
.set({ revokedAt: new Date() })
.where(
and(
eq(householdInvites.id, inviteId),
scopeToHousehold(
householdInvites.householdId,
session!.householdId
),
isNull(householdInvites.usedAt),
isNull(householdInvites.revokedAt)
)
)
.returning({
id: householdInvites.id,
revokedAt: householdInvites.revokedAt,
})
.get();

if (!result) {
throw new ActionError("Invite is no longer valid", "VALIDATION_ERROR");
}
return result;
}
);

return Response.json({ success: true });
}
Expand Down Expand Up @@ -543,6 +584,30 @@ export const handleInviteAcceptRequest: ApiHandler = async ({
)
);

await insertManyAuditLogs(db, [
{
householdId: invite.householdId,
tableName: "household_invites",
recordId: invite.id,
operation: "UPDATE",
oldValues: { usedAt: null, usedByUserId: null },
newValues: { usedAt: usedAt.toISOString(), usedByUserId: userId },
changedBy: userId,
},
{
householdId: invite.householdId,
tableName: "users",
recordId: userId,
operation: "INSERT",
newValues: {
id: userId,
role: "member",
householdId: invite.householdId,
},
changedBy: userId,
},
]);

// Best-effort after D1 (matches settings rename). Session can repair later.
try {
await setClerkHouseholdMetadata(clerk, auth.userId, {
Expand Down
74 changes: 72 additions & 2 deletions apps/web/server/api/members.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { invalidateSessionCachesForHouseholdMembers } from "../lib/session-cache
import { assertSessionStillValid } from "../lib/session";
import { enforceRateLimit, ROUTE_RATE_LIMITS } from "../middleware/rate-limit";
import { getSplatPath, getSplatSegments, type ApiHandler } from "./route";
import { insertManyAuditLogs, withAudit } from "../lib/audit";

const updateRoleSchema = z.object({
role: z.enum(["admin", "member"]),
Expand Down Expand Up @@ -158,7 +159,22 @@ export const handleMembersRequest: ApiHandler = async ({
"Not authorized to assign this role"
);

await db.update(users).set({ role }).where(eq(users.id, userId));
await withAudit(
db,
{
householdId: session!.householdId,
tableName: "users",
recordId: userId,
operation: "UPDATE",
oldValues: { role: targetUser.role },
newValues: { role },
changedBy: session!.userId,
},
async () => {
await db.update(users).set({ role }).where(eq(users.id, userId));
return { role };
}
);

await invalidateSessionCachesForHouseholdMembers(env, [
{ authId: targetUser.authId },
Expand Down Expand Up @@ -356,6 +372,27 @@ export const handleMembersRequest: ApiHandler = async ({
);
}

await insertManyAuditLogs(db, [
{
householdId,
tableName: "users",
recordId: newOwnerId,
operation: "UPDATE",
oldValues: { role: previousNewOwnerRole },
newValues: { role: "owner" },
changedBy: currentOwnerId,
},
{
householdId,
tableName: "users",
recordId: currentOwnerId,
operation: "UPDATE",
oldValues: { role: "owner" },
newValues: { role: "admin" },
changedBy: currentOwnerId,
},
]);

await invalidateSessionCachesForHouseholdMembers(env, [
{ authId: currentUser.authId },
{ authId: newOwner.authId },
Expand Down Expand Up @@ -420,7 +457,12 @@ export const handleMembersRequest: ApiHandler = async ({
db
.select({ count: sql<number>`count(*)` })
.from(recurringTransactions)
.where(eq(recurringTransactions.userId, userId))
.where(
and(
eq(recurringTransactions.userId, userId),
isNull(recurringTransactions.deletedAt)
)
)
.then((result) => result[0]?.count ?? 0),
db
.select({ count: sql<number>`count(*)` })
Expand Down Expand Up @@ -547,6 +589,20 @@ export const handleMembersRequest: ApiHandler = async ({
throw error;
}

await insertManyAuditLogs(db, [
{
householdId: session!.householdId,
tableName: "users",
recordId: userId,
operation: "DELETE",
oldValues: {
id: targetUser.id,
role: targetUser.role,
},
changedBy: session!.userId,
},
]);

await invalidateSessionCachesForHouseholdMembers(env, [
{ authId: targetUser.authId },
]);
Expand Down Expand Up @@ -651,6 +707,20 @@ export const handleMembersRequest: ApiHandler = async ({
throw error;
}

await insertManyAuditLogs(db, [
{
householdId: session!.householdId,
tableName: "users",
recordId: leavingUserId,
operation: "DELETE",
oldValues: {
id: currentUser.id,
role: currentUser.role,
},
changedBy: leavingUserId,
},
]);

await invalidateSessionCachesForHouseholdMembers(env, [
{ authId: currentUser.authId },
]);
Expand Down
14 changes: 7 additions & 7 deletions apps/web/server/api/push.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { and, eq, getDb, lt, pushSubscriptions } from "@amigo/db";
import { z } from "zod";
import { ActionError } from "../lib/errors";
import { ActionError, jsonError } from "../lib/errors";
import type { ApiHandler } from "./route";

const PUSH_SUBSCRIPTION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
Expand Down Expand Up @@ -105,9 +105,9 @@ export const handlePushRequest: ApiHandler = async ({

if (existing) {
if (existing.userId !== session!.userId) {
return Response.json(
{ error: "Subscription endpoint belongs to another user" },
{ status: 403 }
return jsonError(
"Subscription endpoint belongs to another user",
"PERMISSION_DENIED"
);
}

Expand Down Expand Up @@ -138,9 +138,9 @@ export const handlePushRequest: ApiHandler = async ({
});

if (existing && existing.userId !== session!.userId) {
return Response.json(
{ error: "Subscription endpoint belongs to another user" },
{ status: 403 }
return jsonError(
"Subscription endpoint belongs to another user",
"PERMISSION_DENIED"
);
}

Expand Down
Loading