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: 8 additions & 7 deletions .github/workflows/deploy-web.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ jobs:
defaults:
run:
working-directory: apps/web
env:
VITE_API_URL: /api/v1
steps:
- uses: actions/checkout@v4

Expand All @@ -42,11 +40,6 @@ jobs:
role-to-assume: ${{ secrets.AWS_GITHUB_ACTIONS_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}

- name: Build frontend
run: |
npm ci
npm run build

- name: Terraform init
working-directory: ${{ env.TF_ENV_DIR }}
env:
Expand All @@ -60,6 +53,14 @@ jobs:
run: |
echo "bucket=$(terraform output -raw web_bucket_name)" >> $GITHUB_OUTPUT
echo "distribution=$(terraform output -raw cloudfront_distribution_id)" >> $GITHUB_OUTPUT
echo "api_url=$(terraform output -raw api_url)" >> $GITHUB_OUTPUT

- name: Build frontend
env:
VITE_API_URL: ${{ steps.tf-outputs.outputs.api_url }}/api/v1
run: |
npm ci
npm run build

- name: Sync assets to S3
run: aws s3 sync dist s3://${{ steps.tf-outputs.outputs.bucket }} --delete
Expand Down
2 changes: 1 addition & 1 deletion apps/api/.env.production.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ AWS_SES_ACCESS_KEY_ID=
AWS_SES_SECRET_ACCESS_KEY=
BILLING_ENABLED=false
CLIENT_URL=https://underflow.example.com
AUTH_COOKIE_DOMAIN=underflow.example.com
AUTH_COOKIE_DOMAIN=
AUTH_COOKIE_SAME_SITE=lax
LOG_LEVEL=info
RATE_LIMIT_AUTH_WINDOW_MS=60000
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export const app = express();
const stripeWebhookPath = "/api/v1/subscriptions/webhook/stripe";
const jsonParser = express.json();

app.set("trust proxy", true);

app.use(
cors({
origin: env.CLIENT_URL,
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/config/csrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const {
getSecret: () => env.CSRF_SECRET,
getSessionIdentifier: (req: Request) => {
const userAgent = req.headers["user-agent"] ?? "unknown-user-agent";
return `${req.ip}:${userAgent}`;
return String(userAgent);
},
cookieName: csrfCookieName,
cookieOptions: {
Expand Down
12 changes: 12 additions & 0 deletions apps/api/src/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,16 @@ export const userController = {

res.status(200).json({ message: "Other sessions logged out successfully" });
},

async requestMyAccountDeletion(req: Request, res: Response): Promise<void> {
if (!req.user) {
throw new AppError("Unauthorized", 401);
}

await userService.requestAccountDeletion(req.user.id);

res.status(200).json({
message: "Account deletion request submitted successfully",
});
},
};
6 changes: 6 additions & 0 deletions apps/api/src/routes/users.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,9 @@ usersRouter.post(
authMiddleware,
asyncHandler(userController.logoutOtherSessions),
);
usersRouter.post(
"/me/request-account-deletion",
mutationRateLimit,
authMiddleware,
asyncHandler(userController.requestMyAccountDeletion),
);
14 changes: 14 additions & 0 deletions apps/api/src/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
UserSession,
User,
} from "../types/auth.types.js";
import { logger } from "../lib/logger.js";
import { AppError } from "../utils/app-error.js";
import { hashPassword, verifyPassword } from "../utils/password.js";

Expand Down Expand Up @@ -172,4 +173,17 @@ export const userService = {

await refreshTokenRepository.revokeByUserIdExcept(userId, currentSessionId);
},

async requestAccountDeletion(userId: string): Promise<void> {
const user = await userRepository.findById(userId);

if (!user) {
throw new AppError("User not found", 404);
}

logger.warn("Account deletion requested", {
userId: user.id,
email: user.email,
});
},
};
29 changes: 29 additions & 0 deletions apps/api/src/test/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,35 @@ test("POST /api/v1/users/me/sessions/logout-others revokes all other sessions",
}
});

test("POST /api/v1/users/me/request-account-deletion records a deletion request", async () => {
const { app, userService, signAccessToken } = await loadModules();
const originalRequestAccountDeletion = userService.requestAccountDeletion;

let capturedUserId: string | null = null;
userService.requestAccountDeletion = async (userId) => {
capturedUserId = userId;
};

try {
const user = buildUser();
const accessToken = signAccessToken(buildAuthenticatedClaims(user));

const response = await request(app)
.post("/api/v1/users/me/request-account-deletion")
.set("Authorization", `Bearer ${accessToken}`)
.send({});

assert.equal(response.status, 200);
assert.equal(capturedUserId, "user-123");
assert.equal(
response.body.message,
"Account deletion request submitted successfully",
);
} finally {
userService.requestAccountDeletion = originalRequestAccountDeletion;
}
});

test("GET /api/v1/notifications returns the notifications feed", async () => {
const { app, notificationService, signAccessToken } = await loadModules();
const originalGetFeedForUser = notificationService.getFeedForUser;
Expand Down
2 changes: 1 addition & 1 deletion apps/web/.env.production.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
VITE_API_URL=/api/v1
VITE_API_URL=https://api.underflow.example.com/api/v1
VITE_APP_NAME=Underflow
VITE_DEFAULT_THEME=system
16 changes: 15 additions & 1 deletion apps/web/src/lib/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,21 @@ export const AUTH_SESSION_EXPIRED_EVENT = "underflow:auth-session-expired";

const parseResponse = async <T>(response: Response): Promise<T> => {
const text = await response.text();
const data = text ? (JSON.parse(text) as unknown) : {};
let data: unknown = {};

if (text) {
try {
data = JSON.parse(text) as unknown;
} catch {
throw new ApiError(
response.status,
response.ok ? "Received a non-JSON response" : "Unexpected non-JSON error response",
{
responseTextPreview: text.slice(0, 200),
},
);
}
}

if (!response.ok) {
const payload =
Expand Down
6 changes: 6 additions & 0 deletions apps/web/src/lib/api/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,10 @@ export const usersApi = {
body: {},
requireAuth: true,
}),
requestAccountDeletion: () =>
apiRequest<{ message: string }>("/users/me/request-account-deletion", {
method: "POST",
body: {},
requireAuth: true,
}),
};
40 changes: 38 additions & 2 deletions apps/web/src/pages/app/ProfileSettingsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export const ProfileSettingsPage = (): JSX.Element => {
const [isSavingPassword, setIsSavingPassword] = useState(false);
const [isSavingPreferences, setIsSavingPreferences] = useState(false);
const [isLoggingOutOthers, setIsLoggingOutOthers] = useState(false);
const [isRequestingDeletion, setIsRequestingDeletion] = useState(false);

const preferencesQuery = useAsyncData(
async () => {
Expand Down Expand Up @@ -200,6 +201,37 @@ export const ProfileSettingsPage = (): JSX.Element => {
}
};

const handleRequestAccountDeletion = async () => {
setError(null);

const confirmed = window.confirm(
"Send an account deletion request? This does not delete your account immediately.",
);

if (!confirmed) {
return;
}

setIsRequestingDeletion(true);

try {
await usersApi.requestAccountDeletion();
showToast({
title: "Deletion request submitted",
description: "Our team can now review your account deletion request.",
tone: "success",
});
} catch (submitError) {
setError(
submitError instanceof Error
? submitError.message
: "Unable to submit account deletion request",
);
} finally {
setIsRequestingDeletion(false);
}
};

const updatePreference = (key: keyof EmailPreferencesState, value: boolean) => {
setEmailPreferences((current) => ({ ...current, [key]: value }));
};
Expand Down Expand Up @@ -472,8 +504,12 @@ export const ProfileSettingsPage = (): JSX.Element => {
resource data.
</p>
</div>
<Button type="button" variant="ghost">
Request Account Deletion
<Button
onClick={() => void handleRequestAccountDeletion()}
type="button"
variant="ghost"
>
{isRequestingDeletion ? "Submitting..." : "Request Account Deletion"}
</Button>
</section>
</div>
Expand Down
58 changes: 58 additions & 0 deletions apps/web/src/pages/app/app-pages.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { AwsAccountsPage } from "./AwsAccountsPage";
import { ConnectAwsAccountPage } from "./ConnectAwsAccountPage";
import { AlertsPage } from "./AlertsPage";
import { CreateAlertPage } from "./CreateAlertPage";
import { ProfileSettingsPage } from "./ProfileSettingsPage";
import { WorkspaceSettingsPage } from "./WorkspaceSettingsPage";

const authApiMock = vi.hoisted(() => ({
Expand Down Expand Up @@ -52,6 +53,17 @@ const alertsApiMock = vi.hoisted(() => ({
remove: vi.fn(),
}));

const usersApiMock = vi.hoisted(() => ({
updateProfile: vi.fn(),
updatePassword: vi.fn(),
getPreferences: vi.fn(),
updatePreferences: vi.fn(),
getSessions: vi.fn(),
revokeSession: vi.fn(),
logoutOtherSessions: vi.fn(),
requestAccountDeletion: vi.fn(),
}));

vi.mock("../../lib/api/auth", () => ({
authApi: authApiMock,
}));
Expand All @@ -68,6 +80,10 @@ vi.mock("../../lib/api/alerts", () => ({
alertsApi: alertsApiMock,
}));

vi.mock("../../lib/api/users", () => ({
usersApi: usersApiMock,
}));

const signedInUser = {
id: "user-1",
email: "user@example.com",
Expand Down Expand Up @@ -163,6 +179,34 @@ beforeEach(() => {
awsApiMock.update.mockResolvedValue({ awsAccount: { ...awsAccount, name: "Prod updated" } });
alertsApiMock.list.mockResolvedValue({ alerts: [] });
alertsApiMock.remove.mockResolvedValue(undefined);
usersApiMock.getPreferences.mockResolvedValue({
preferences: {
costAlerts: true,
driftReports: true,
maintenance: false,
featureReleases: true,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
},
});
usersApiMock.getSessions.mockResolvedValue({
sessions: [
{
id: "session-current",
deviceLabel: "Mac",
userAgent: "Mozilla/5.0 (Macintosh)",
ipAddress: "127.0.0.1",
createdAt: "2026-01-01T00:00:00.000Z",
lastUsedAt: "2026-01-01T00:00:00.000Z",
revokedAt: null,
isCurrent: true,
},
],
});
usersApiMock.requestAccountDeletion.mockResolvedValue({
message: "Account deletion request submitted successfully",
});
vi.spyOn(window, "confirm").mockImplementation(() => true);
});

afterEach(() => {
Expand Down Expand Up @@ -477,3 +521,17 @@ test("alert creation submits a scoped rule", async () => {
});
});
});

test("profile settings submits an account deletion request", async () => {
renderPage(
"/app/settings/profile",
"/app/settings/profile",
<ProfileSettingsPage />,
);

fireEvent.click(await screen.findByRole("button", { name: "Request Account Deletion" }));

await waitFor(() => {
expect(usersApiMock.requestAccountDeletion).toHaveBeenCalledTimes(1);
});
});
Loading
Loading