π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Move staff API calls into services
Manav Rathie85e858a70ce
diff --git a/infra/staff/src/App.tsx b/infra/staff/src/App.tsxindex f1467fdc74..d48f4d6bbf 100644--- a/infra/staff/src/App.tsx+++ b/infra/staff/src/App.tsx@@ -13,29 +13,8 @@ import { StorageBonusTableComponent } from "./components/StorageBonusTableComponimport { TokensTableComponent } from "./components/TokenTableComponent";import { UserComponent, type UserData } from "./components/UserComponent";import duckieimage from "./components/duckie.png";+import { getUser } from "./services/admin-user";import { StaffSessionProvider } from "./services/session";-import { apiOrigin } from "./services/support";--interface UserResponse {- user: { ID: string; email: string; creationTime: number };- subscription: {- productID: string;- paymentProvider: string;- expiryTime: number;- storage: number;- };- authCodes?: number;- details?: {- usage?: number;- storageBonus?: number;- profileData: {- isEmailMFAEnabled: boolean;- isTwoFactorEnabled: boolean;- passkeyCount: number;- canDisableEmailMFA: boolean;- };- };-}export const App: React.FC = () => {const [urlCredentials] = useState(readUrlCredentials);@@ -67,30 +46,26 @@ export const App: React.FC = () => {const startTime = Date.now();try {const userSearchInput = input.trim();- const url = buildUserSearchUrl(userSearchInput);- const response = await fetch(url, {- headers: {- "Content-Type": "application/json",- "X-Auth-Token": authToken,- },- });- if (!response.ok) {- throw new Error("Network response was not ok");+ const userDataResponse = await getUser(+ { token: authToken },+ userSearchInput,+ );+ if (!userDataResponse.subscription) {+ throw new Error("Subscription data not found");}- const userDataResponse: UserResponse =- (await response.json()) as UserResponse;+ const { subscription } = userDataResponse;const userEmail = userDataResponse.user.email || userSearchInput;setSelectedUserEmail(userEmail);const emailMFAEnabled =- userDataResponse.details?.profileData.isEmailMFAEnabled ??+ userDataResponse.details?.profileData?.isEmailMFAEnabled ??false;const twoFactorEnabled =- userDataResponse.details?.profileData.isTwoFactorEnabled ??+ userDataResponse.details?.profileData?.isTwoFactorEnabled ??false;const passkeysEnabled =- (userDataResponse.details?.profileData.passkeyCount ?? 0) > 0;+ (userDataResponse.details?.profileData?.passkeyCount ?? 0) > 0;const canDisableEmailMFA =- userDataResponse.details?.profileData.canDisableEmailMFA ??+ userDataResponse.details?.profileData?.canDisableEmailMFA ??false;const extractedUserData: UserData = {@@ -119,10 +94,7 @@ export const App: React.FC = () => {{kind: "text",label: "Total",- value: formatStorage(- userDataResponse.subscription.storage,- true,- ),+ value: formatStorage(subscription.storage, true),},{kind: "text",@@ -141,22 +113,19 @@ export const App: React.FC = () => {{kind: "text",label: "Product ID",- value:- userDataResponse.subscription.productID || "None",+ value: subscription.productID || "None",},{kind: "text",label: "Provider",- value:- userDataResponse.subscription.paymentProvider ||- "None",+ value: subscription.paymentProvider || "None",},{kind: "expiry",label: "Expiry time",value:new Date(- userDataResponse.subscription.expiryTime / 1000,+ subscription.expiryTime / 1000,).toISOString() || "None",},],@@ -373,16 +342,6 @@ const readUrlCredentials = () => {return { email: urlParams.get("email"), token: urlParams.get("token") };};-const buildUserSearchUrl = (input: string): string => {- const trimmedInput = input.trim();- if (isNumericUserId(trimmedInput)) {- return `${apiOrigin}/admin/user?id=${encodeURIComponent(trimmedInput)}`;- }- return `${apiOrigin}/admin/user?email=${encodeURIComponent(trimmedInput)}`;-};--const isNumericUserId = (value: string): boolean => /^\d+$/.test(value);-const formatStorage = (bytes: number | undefined, noneWhenZero = false) => {if (bytes === undefined || (noneWhenZero && bytes === 0)) {return "None";diff --git a/infra/staff/src/components/AddOTT.tsx b/infra/staff/src/components/AddOTT.tsxindex 016f21b6f4..2e39bc0d9c 100644--- a/infra/staff/src/components/AddOTT.tsx+++ b/infra/staff/src/components/AddOTT.tsx@@ -15,12 +15,8 @@ import {Typography,} from "@mui/material";import React, { useEffect, useState } from "react";+import { addOTT } from "../services/admin-user";import { useStaffSession } from "../services/session";-import {- apiOrigin,- requireToken,- responseErrorMessage,-} from "../services/support";const APP_OPTIONS = [{ label: "Photos", value: "photos" },@@ -72,35 +68,17 @@ export const AddOTT: React.FC<AddOTTProps> = ({ open, onClose, userEmail }) => {throw new Error("User email is unavailable");}- const token = requireToken(session);-const otp = generateOTP();const expiryTime = computeExpiryTimeMicros();setExpiryPreview(expiryTime);- const response = await fetch(`${apiOrigin}/admin/user/add-ott`, {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Auth-Token": token,- },- body: JSON.stringify({- email: userEmail,- code: otp,- app: selectedApp,- expiryTime,- }),+ await addOTT(session, {+ email: userEmail,+ code: otp,+ app: selectedApp,+ expiryTime,});- if (!response.ok) {- throw new Error(- await responseErrorMessage(- response,- "Failed to create OTT",- ),- );- }-setCreatedOtp(otp);} catch (err) {if (err instanceof Error) {diff --git a/infra/staff/src/components/ChangeEmail.tsx b/infra/staff/src/components/ChangeEmail.tsxindex ada86c0733..cf21af58a0 100644--- a/infra/staff/src/components/ChangeEmail.tsx+++ b/infra/staff/src/components/ChangeEmail.tsx@@ -9,13 +9,8 @@ import {TextField,} from "@mui/material";import React, { useEffect, useState } from "react";+import { changeUserEmail, getSelectedUserID } from "../services/admin-user";import { useStaffSessionRef } from "../services/session";-import {- apiOrigin,- getCurrentAdminUserId,- requireToken,- responseErrorMessage,-} from "../services/support";interface ChangeEmailProps {open: boolean;@@ -34,7 +29,7 @@ export const ChangeEmail: React.FC<ChangeEmailProps> = ({ open, onClose }) => {setNewEmail(email);try {- setUserID(await getCurrentAdminUserId(session));+ setUserID(await getSelectedUserID(session));} catch (error) {console.error("Error fetching user ID:", error);}@@ -57,27 +52,7 @@ export const ChangeEmail: React.FC<ChangeEmailProps> = ({ open, onClose }) => {event.preventDefault();try {- const token = requireToken(sessionRef.current);- const url = `${apiOrigin}/admin/user/change-email`;- const body = { userID, email: newEmail };- const response = await fetch(url, {- method: "PUT",- headers: {- "Content-Type": "application/json",- "X-Auth-Token": token,- },- body: JSON.stringify(body),- });-- if (!response.ok) {- throw new Error(- await responseErrorMessage(- response,- "Network response was not ok",- ),- );- }-+ await changeUserEmail(sessionRef.current, userID, newEmail);onClose();} catch (error) {console.error("Error updating email:", error);diff --git a/infra/staff/src/components/CloseFamily.tsx b/infra/staff/src/components/CloseFamily.tsxindex 1978c169d9..9b3ec5709a 100644--- a/infra/staff/src/components/CloseFamily.tsx+++ b/infra/staff/src/components/CloseFamily.tsx@@ -1,11 +1,6 @@import React, { useState } from "react";+import { closeFamily } from "../services/admin-user";import { useStaffSession } from "../services/session";-import {- apiOrigin,- getCurrentAdminUserId,- requireToken,- responseErrorMessage,-} from "../services/support";import { ConfirmationDialog } from "./ConfirmationDialog";interface CloseFamilyProps {@@ -25,29 +20,7 @@ export const CloseFamily: React.FC<CloseFamilyProps> = ({const handleClosure = async () => {try {setLoading(true);- const token = requireToken(session);- const userId = await getCurrentAdminUserId(session);- const response = await fetch(- `${apiOrigin}/admin/user/close-family`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Auth-Token": token,- },- body: JSON.stringify({ userId }),- },- );-- if (!response.ok) {- throw new Error(- await responseErrorMessage(- response,- "Failed to close family",- ),- );- }-+ await closeFamily(session);handleCloseFamily();handleClose();} catch (error) {diff --git a/infra/staff/src/components/DeleteAccount.tsx b/infra/staff/src/components/DeleteAccount.tsxindex c1929b4a2c..dc0d1f6332 100644--- a/infra/staff/src/components/DeleteAccount.tsx+++ b/infra/staff/src/components/DeleteAccount.tsx@@ -1,11 +1,6 @@import React from "react";+import { deleteAccount } from "../services/admin-user";import { useStaffSession } from "../services/session";-import {- apiOrigin,- requireEmail,- requireToken,- responseErrorMessage,-} from "../services/support";import { ConfirmationDialog } from "./ConfirmationDialog";interface DeleteAccountProps {@@ -21,20 +16,7 @@ export const DeleteAccount: React.FC<DeleteAccountProps> = ({const handleDelete = async () => {try {- const email = requireEmail(session);- const token = requireToken(session);- const response = await fetch(- `${apiOrigin}/admin/user/delete?email=${encodeURIComponent(email)}`,- { method: "DELETE", headers: { "X-Auth-Token": token } },- );- if (!response.ok) {- throw new Error(- await responseErrorMessage(- response,- "Failed to delete user account",- ),- );- }+ await deleteAccount(session);handleClose();} catch (error) {if (error instanceof Error) {diff --git a/infra/staff/src/components/Disable2FA.tsx b/infra/staff/src/components/Disable2FA.tsxindex d5a8e61ae9..bc94198f71 100644--- a/infra/staff/src/components/Disable2FA.tsx+++ b/infra/staff/src/components/Disable2FA.tsx@@ -1,11 +1,6 @@import React, { useState } from "react";+import { disable2FA } from "../services/admin-user";import { useStaffSession } from "../services/session";-import {- apiOrigin,- getCurrentAdminUserId,- requireToken,- responseErrorMessage,-} from "../services/support";import { ConfirmationDialog } from "./ConfirmationDialog";interface Disable2FAProps {@@ -25,28 +20,7 @@ export const Disable2FA: React.FC<Disable2FAProps> = ({const handleDisable = async () => {try {setLoading(true);- const token = requireToken(session);- const userID = await getCurrentAdminUserId(session);- const response = await fetch(- `${apiOrigin}/admin/user/disable-2fa`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Auth-Token": token,- },- body: JSON.stringify({ userID }),- },- );-- if (!response.ok) {- throw new Error(- await responseErrorMessage(- response,- "Failed to disable 2FA",- ),- );- }+ await disable2FA(session);handleDisable2FA();handleClose();} catch (error) {diff --git a/infra/staff/src/components/DisablePasskeys.tsx b/infra/staff/src/components/DisablePasskeys.tsxindex ae5f31e0a3..5c0a02e200 100644--- a/infra/staff/src/components/DisablePasskeys.tsx+++ b/infra/staff/src/components/DisablePasskeys.tsx@@ -1,11 +1,6 @@import React, { useState } from "react";+import { disablePasskeys } from "../services/admin-user";import { useStaffSession } from "../services/session";-import {- apiOrigin,- getCurrentAdminUserId,- requireToken,- responseErrorMessage,-} from "../services/support";import { ConfirmationDialog } from "./ConfirmationDialog";interface DisablePasskeysProps {@@ -25,28 +20,7 @@ export const DisablePasskeys: React.FC<DisablePasskeysProps> = ({const handleDisabling = async () => {try {setLoading(true);- const token = requireToken(session);- const userId = await getCurrentAdminUserId(session);-- const disablePasskeysUrl = `${apiOrigin}/admin/user/disable-passkeys`;- const response = await fetch(disablePasskeysUrl, {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Auth-Token": token,- },- body: JSON.stringify({ userId }),- });-- if (!response.ok) {- throw new Error(- await responseErrorMessage(- response,- "Failed to disable passkeys",- ),- );- }-+ await disablePasskeys(session);handleDisablePasskeys();handleClose();} catch (error) {diff --git a/infra/staff/src/components/FamilyComponentTable.tsx b/infra/staff/src/components/FamilyComponentTable.tsxindex f251e0afbc..b5d733ac1a 100644--- a/infra/staff/src/components/FamilyComponentTable.tsx+++ b/infra/staff/src/components/FamilyComponentTable.tsx@@ -11,19 +11,11 @@ import {TableRow,} from "@mui/material";import React, { useEffect, useState } from "react";+import { getFamilyMembers, type FamilyMember } from "../services/admin-user";import { useInitialStaffSession } from "../services/session";-import { getCurrentAdminUser } from "../services/support";import { CloseFamily } from "./CloseFamily";import { StatusBadge } from "./StatusBadge";-interface FamilyMember {- id: string;- email: string;- status: string;- usage: number;- storageLimit: number;-}-export const FamilyTableComponent: React.FC = () => {const [familyMembers, setFamilyMembers] = useState<FamilyMember[]>([]);const [closeFamilyOpen, setCloseFamilyOpen] = useState(false);@@ -34,12 +26,7 @@ export const FamilyTableComponent: React.FC = () => {useEffect(() => {const fetchData = async () => {try {- const userData = await getCurrentAdminUser<{- details?: { familyData?: { members?: FamilyMember[] } };- }>(session);- const members: FamilyMember[] =- userData.details?.familyData?.members ?? [];- setFamilyMembers(members);+ setFamilyMembers(await getFamilyMembers(session));} catch (error) {console.error("Error fetching family data:", error);setError("No family data");diff --git a/infra/staff/src/components/StorageBonusTableComponent.tsx b/infra/staff/src/components/StorageBonusTableComponent.tsxindex aec2082806..e74040ebc7 100644--- a/infra/staff/src/components/StorageBonusTableComponent.tsx+++ b/infra/staff/src/components/StorageBonusTableComponent.tsx@@ -8,20 +8,12 @@ import {TableRow,} from "@mui/material";import React, { useEffect, useState } from "react";+import { getStorageBonuses, type StorageBonus } from "../services/admin-user";import { useInitialStaffSession } from "../services/session";-import { getCurrentAdminUser } from "../services/support";import { StatusBadge } from "./StatusBadge";-interface BonusData {- storage: number;- type: string;- createdAt: number;- validTill: number;- isRevoked: boolean;-}-export const StorageBonusTableComponent: React.FC = () => {- const [storageBonuses, setStorageBonuses] = useState<BonusData[]>([]);+ const [storageBonuses, setStorageBonuses] = useState<StorageBonus[]>([]);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const session = useInitialStaffSession();@@ -29,12 +21,7 @@ export const StorageBonusTableComponent: React.FC = () => {useEffect(() => {const fetchData = async () => {try {- const userData = await getCurrentAdminUser<{- details?: { bonusData?: { storageBonuses?: BonusData[] } };- }>(session);- const bonuses: BonusData[] =- userData.details?.bonusData?.storageBonuses ?? [];- setStorageBonuses(bonuses);+ setStorageBonuses(await getStorageBonuses(session));} catch (error) {console.error("Error fetching bonus data:", error);setError("No bonus data");diff --git a/infra/staff/src/components/ToggleEmailMFA.tsx b/infra/staff/src/components/ToggleEmailMFA.tsxindex 10f30b04a9..53860ed71f 100644--- a/infra/staff/src/components/ToggleEmailMFA.tsx+++ b/infra/staff/src/components/ToggleEmailMFA.tsx@@ -1,11 +1,6 @@import React, { useState } from "react";+import { updateEmailMFA } from "../services/admin-user";import { useStaffSession } from "../services/session";-import {- apiOrigin,- getCurrentAdminUserId,- requireToken,- responseErrorMessage,-} from "../services/support";import { ConfirmationDialog } from "./ConfirmationDialog";interface ToggleEmailMFAProps {@@ -25,28 +20,7 @@ export const ToggleEmailMFA: React.FC<ToggleEmailMFAProps> = ({const handleToggle = async (enable: boolean) => {try {setLoading(true);- const token = requireToken(session);- const userId = await getCurrentAdminUserId(session);-- const toggleEmailMFAUrl = `${apiOrigin}/admin/user/update-email-mfa`;- const response = await fetch(toggleEmailMFAUrl, {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Auth-Token": token,- },- body: JSON.stringify({ userID: userId, emailMFA: enable }),- });-- if (!response.ok) {- throw new Error(- await responseErrorMessage(- response,- "Failed to update Email MFA",- ),- );- }-+ await updateEmailMFA(session, enable);handleToggleEmailMFA(enable);handleClose();} catch (error) {diff --git a/infra/staff/src/components/TokenTableComponent.tsx b/infra/staff/src/components/TokenTableComponent.tsxindex 49b6a3a94c..fffc7fafc1 100644--- a/infra/staff/src/components/TokenTableComponent.tsx+++ b/infra/staff/src/components/TokenTableComponent.tsx@@ -9,18 +9,10 @@ import {TableSortLabel,} from "@mui/material";import React, { useEffect, useMemo, useState } from "react";+import { getTokens, type TokenData } from "../services/admin-user";import { useInitialStaffSession } from "../services/session";-import { getCurrentAdminUser } from "../services/support";import { StatusBadge } from "./StatusBadge";-interface TokenData {- creationTime: number;- lastUsedTime: number;- ua: string;- isDeleted: boolean;- app: string;-}-export const TokensTableComponent: React.FC = () => {const [tokens, setTokens] = useState<TokenData[]>([]);const [loading, setLoading] = useState(true);@@ -32,10 +24,7 @@ export const TokensTableComponent: React.FC = () => {useEffect(() => {const fetchData = async () => {try {- const userData = await getCurrentAdminUser<{- tokens?: TokenData[];- }>(session);- setTokens(userData.tokens ?? []);+ setTokens(await getTokens(session));} catch (error) {console.error("Error fetching token data:", error);setError("No token data");diff --git a/infra/staff/src/components/UpdateSubscription.tsx b/infra/staff/src/components/UpdateSubscription.tsxindex bc766046b6..fc673a943f 100644--- a/infra/staff/src/components/UpdateSubscription.tsx+++ b/infra/staff/src/components/UpdateSubscription.tsx@@ -17,27 +17,11 @@ import {import React, { useEffect, useState } from "react";import DatePicker from "react-datepicker";import "react-datepicker/dist/react-datepicker.css";-import { useInitialStaffSession, useStaffSession } from "../services/session";import {- apiOrigin,- getCurrentAdminUser,- requireToken,- responseErrorMessage,-} from "../services/support";--interface Subscription {- productID: string;- paymentProvider: string;- storage: number;- originalTransactionID: string;- expiryTime: number;- userID: string;- attributes: { customerID: string; stripeAccountCountry: string };-}--interface UserDataResponse {- subscription: Subscription | null;-}+ getSelectedSubscription,+ updateUserSubscription,+} from "../services/admin-user";+import { useInitialStaffSession, useStaffSession } from "../services/session";interface UpdateSubscriptionProps {open: boolean;@@ -75,36 +59,21 @@ export const UpdateSubscription: React.FC<UpdateSubscriptionProps> = ({useEffect(() => {const fetchData = async () => {try {- const userDataResponse =- await getCurrentAdminUser<UserDataResponse>(initialSession);-- if (!userDataResponse.subscription) {- throw new Error("Subscription data not found");- }-- const expiryTime = new Date(- userDataResponse.subscription.expiryTime / 1000,- );+ const subscription =+ await getSelectedSubscription(initialSession);+ const expiryTime = new Date(subscription.expiryTime / 1000);setValues({- productId: userDataResponse.subscription.productID || "",- provider:- userDataResponse.subscription.paymentProvider || "",- storage:- userDataResponse.subscription.storage /- (1024 * 1024 * 1024) || 0,- transactionId:- userDataResponse.subscription.originalTransactionID ||- "",+ productId: subscription.productID || "",+ provider: subscription.paymentProvider || "",+ storage: subscription.storage / (1024 * 1024 * 1024) || 0,+ transactionId: subscription.originalTransactionID || "",expiryTime,- userId: userDataResponse.subscription.userID || "",+ userId: subscription.userID || "",attributes: {- customerID:- userDataResponse.subscription.attributes- .customerID || "",+ customerID: subscription.attributes?.customerID || "",stripeAccountCountry:- userDataResponse.subscription.attributes- .stripeAccountCountry || "",+ subscription.attributes?.stripeAccountCountry || "",},});} catch (error) {@@ -144,15 +113,12 @@ export const UpdateSubscription: React.FC<UpdateSubscriptionProps> = ({event.preventDefault();try {- const token = requireToken(session);- const url = `${apiOrigin}/admin/user/subscription`;-let expiryTime = null;if (values.expiryTime) {expiryTime = values.expiryTime.getTime() * 1000;}- const body = {+ await updateUserSubscription(session, {userId: values.userId,storage: values.storage * 1024 ** 3,expiryTime,@@ -164,25 +130,7 @@ export const UpdateSubscription: React.FC<UpdateSubscriptionProps> = ({stripeAccountCountry:values.attributes.stripeAccountCountry,},- };-- const response = await fetch(url, {- method: "PUT",- headers: {- "Content-Type": "application/json",- "X-Auth-Token": token,- },- body: JSON.stringify(body),});-- if (!response.ok) {- throw new Error(- await responseErrorMessage(- response,- "Network response was not ok",- ),- );- }onClose();} catch (error) {if (error instanceof Error) {diff --git a/infra/staff/src/services/admin-user.ts b/infra/staff/src/services/admin-user.tsnew file mode 100644index 0000000000..8b711df973--- /dev/null+++ b/infra/staff/src/services/admin-user.ts@@ -0,0 +1,255 @@+import { z } from "zod";+import {+ apiURL,+ ensureOk,+ requireEmail,+ staffJSONRequestHeaders,+ staffRequestHeaders,+} from "./api";+import type { StaffSession } from "./session";++const UserProfileData = z.looseObject({+ isEmailMFAEnabled: z.boolean().optional(),+ isTwoFactorEnabled: z.boolean().optional(),+ passkeyCount: z.number().optional(),+ canDisableEmailMFA: z.boolean().optional(),+});++const FamilyMember = z.looseObject({+ id: z.string(),+ email: z.string(),+ status: z.string(),+ usage: z.number(),+ storageLimit: z.number(),+});++export type FamilyMember = z.infer<typeof FamilyMember>;++const StorageBonus = z.looseObject({+ storage: z.number(),+ type: z.string(),+ createdAt: z.number(),+ validTill: z.number(),+ isRevoked: z.boolean(),+});++export type StorageBonus = z.infer<typeof StorageBonus>;++const TokenData = z.looseObject({+ creationTime: z.number(),+ lastUsedTime: z.number(),+ ua: z.string().optional(),+ isDeleted: z.boolean(),+ app: z.string(),+});++export type TokenData = z.infer<typeof TokenData>;++const Subscription = z.looseObject({+ productID: z.string().optional(),+ paymentProvider: z.string().optional(),+ storage: z.number(),+ originalTransactionID: z.string().optional(),+ expiryTime: z.number(),+ userID: z.string().optional(),+ attributes: z+ .looseObject({+ customerID: z.string().optional(),+ stripeAccountCountry: z.string().optional(),+ })+ .optional(),+});++export type Subscription = z.infer<typeof Subscription>;++const UserResponse = z.looseObject({+ user: z.looseObject({+ ID: z.string().optional(),+ email: z.string().optional(),+ creationTime: z.number(),+ }),+ subscription: Subscription.nullable().optional(),+ authCodes: z.number().optional(),+ tokens: z.array(TokenData).optional(),+ details: z+ .looseObject({+ usage: z.number().optional(),+ storageBonus: z.number().optional(),+ profileData: UserProfileData.optional(),+ familyData: z+ .looseObject({ members: z.array(FamilyMember).optional() })+ .optional(),+ bonusData: z+ .looseObject({+ storageBonuses: z.array(StorageBonus).optional(),+ })+ .optional(),+ })+ .optional(),+});++export type UserResponse = z.infer<typeof UserResponse>;++interface AddOTTRequest {+ email: string;+ code: string;+ app: string;+ expiryTime: number;+}++export interface UpdateSubscriptionRequest {+ userId: string;+ storage: number;+ expiryTime: number | null;+ productId: string;+ paymentProvider: string;+ transactionId: string;+ attributes: { customerID: string; stripeAccountCountry: string };+}++const userSearchQuery = (input: string) => {+ const trimmedInput = input.trim();+ if (/^\d+$/.test(trimmedInput)) {+ return { id: trimmedInput };+ }+ return { email: trimmedInput };+};++export const getUser = async (+ session: Pick<StaffSession, "token">,+ input: string,+) => {+ const response = await fetch(+ apiURL("/admin/user", userSearchQuery(input)),+ { headers: staffJSONRequestHeaders(session) },+ );+ await ensureOk(response, "Network response was not ok");+ return UserResponse.parse(await response.json());+};++export const getSelectedUser = async (session: StaffSession) => {+ const response = await fetch(+ apiURL("/admin/user", { email: requireEmail(session) }),+ { headers: staffJSONRequestHeaders(session) },+ );+ await ensureOk(response, "Failed to fetch user data");+ return UserResponse.parse(await response.json());+};++export const getSelectedUserID = async (session: StaffSession) => {+ const userData = await getSelectedUser(session);+ const userId = userData.subscription?.userID;+ if (!userId) throw new Error("User ID not found");+ return userId;+};++export const getSelectedSubscription = async (session: StaffSession) => {+ const userData = await getSelectedUser(session);+ if (!userData.subscription) {+ throw new Error("Subscription data not found");+ }+ return userData.subscription;+};++export const getFamilyMembers = async (session: StaffSession) => {+ const userData = await getSelectedUser(session);+ return userData.details?.familyData?.members ?? [];+};++export const getStorageBonuses = async (session: StaffSession) => {+ const userData = await getSelectedUser(session);+ return userData.details?.bonusData?.storageBonuses ?? [];+};++export const getTokens = async (session: StaffSession) => {+ const userData = await getSelectedUser(session);+ return userData.tokens ?? [];+};++export const addOTT = async (+ session: StaffSession,+ { app, code, email, expiryTime }: AddOTTRequest,+) => {+ const response = await fetch(apiURL("/admin/user/add-ott"), {+ method: "POST",+ headers: staffJSONRequestHeaders(session),+ body: JSON.stringify({ email, code, app, expiryTime }),+ });+ await ensureOk(response, "Failed to create OTT");+};++export const changeUserEmail = async (+ session: StaffSession,+ userID: string,+ email: string,+) => {+ const response = await fetch(apiURL("/admin/user/change-email"), {+ method: "PUT",+ headers: staffJSONRequestHeaders(session),+ body: JSON.stringify({ userID, email }),+ });+ await ensureOk(response, "Network response was not ok");+};++export const closeFamily = async (session: StaffSession) => {+ const userId = await getSelectedUserID(session);+ const response = await fetch(apiURL("/admin/user/close-family"), {+ method: "POST",+ headers: staffJSONRequestHeaders(session),+ body: JSON.stringify({ userId }),+ });+ await ensureOk(response, "Failed to close family");+};++export const deleteAccount = async (session: StaffSession) => {+ const response = await fetch(+ apiURL("/admin/user/delete", { email: requireEmail(session) }),+ { method: "DELETE", headers: staffRequestHeaders(session) },+ );+ await ensureOk(response, "Failed to delete user account");+};++export const disable2FA = async (session: StaffSession) => {+ const userID = await getSelectedUserID(session);+ const response = await fetch(apiURL("/admin/user/disable-2fa"), {+ method: "POST",+ headers: staffJSONRequestHeaders(session),+ body: JSON.stringify({ userID }),+ });+ await ensureOk(response, "Failed to disable 2FA");+};++export const disablePasskeys = async (session: StaffSession) => {+ const userId = await getSelectedUserID(session);+ const response = await fetch(apiURL("/admin/user/disable-passkeys"), {+ method: "POST",+ headers: staffJSONRequestHeaders(session),+ body: JSON.stringify({ userId }),+ });+ await ensureOk(response, "Failed to disable passkeys");+};++export const updateEmailMFA = async (+ session: StaffSession,+ emailMFA: boolean,+) => {+ const userID = await getSelectedUserID(session);+ const response = await fetch(apiURL("/admin/user/update-email-mfa"), {+ method: "POST",+ headers: staffJSONRequestHeaders(session),+ body: JSON.stringify({ userID, emailMFA }),+ });+ await ensureOk(response, "Failed to update Email MFA");+};++export const updateUserSubscription = async (+ session: StaffSession,+ request: UpdateSubscriptionRequest,+) => {+ const response = await fetch(apiURL("/admin/user/subscription"), {+ method: "PUT",+ headers: staffJSONRequestHeaders(session),+ body: JSON.stringify(request),+ });+ await ensureOk(response, "Network response was not ok");+};diff --git a/infra/staff/src/services/api.ts b/infra/staff/src/services/api.tsnew file mode 100644index 0000000000..16eef0c4ca--- /dev/null+++ b/infra/staff/src/services/api.ts@@ -0,0 +1,68 @@+import type { StaffSession } from "./session";++export const apiOrigin =+ import.meta.env.VITE_ENTE_API_ORIGIN ?? "https://api.ente.io";++type QueryParamValue = string | number | boolean;++export const apiURL = (+ path: string,+ queryParams?: Record<string, QueryParamValue>,+) => {+ let url = apiOrigin + path;+ if (queryParams) {+ const stringParams = Object.fromEntries(+ Object.entries(queryParams).map(([key, value]) => [+ key,+ value.toString(),+ ]),+ );+ url = `${url}?${new URLSearchParams(stringParams).toString()}`;+ }+ return url;+};++export const requireEmail = ({ email }: Pick<StaffSession, "email">) => {+ if (!email) throw new Error("Email not found");+ return email;+};++export const requireToken = ({ token }: Pick<StaffSession, "token">) => {+ if (!token) throw new Error("Token not found");+ return token;+};++export const staffRequestHeaders = (session: Pick<StaffSession, "token">) => ({+ "X-Auth-Token": requireToken(session),+});++export const staffJSONRequestHeaders = (+ session: Pick<StaffSession, "token">,+) => ({ ...staffRequestHeaders(session), "Content-Type": "application/json" });++export const ensureOk = async (response: Response, fallback: string) => {+ if (!response.ok) {+ throw new Error(await responseErrorMessage(response, fallback));+ }+};++const responseErrorMessage = async (response: Response, fallback: string) => {+ const text = await response.text();+ if (!text) {+ return fallback;+ }++ try {+ const body = JSON.parse(text) as unknown;+ if (body && typeof body === "object" && "message" in body) {+ const { message } = body as { message?: unknown };+ if (typeof message === "string" && message) {+ return message;+ }+ }+ } catch {+ return text;+ }++ return text;+};diff --git a/infra/staff/src/services/support.ts b/infra/staff/src/services/support.tsdeleted file mode 100644index 3b82a026ac..0000000000--- a/infra/staff/src/services/support.ts+++ /dev/null@@ -1,79 +0,0 @@-import { z } from "zod";-import type { StaffSession } from "./session";--export const apiOrigin =- import.meta.env.VITE_ENTE_API_ORIGIN ?? "https://api.ente.io";--const UserDetailsSchema = z.looseObject({});--export type UserDetails = z.infer<typeof UserDetailsSchema>;--/** Fetch details of the user associated with the given {@link authToken}. */-export const getUserDetails = async (- authToken: string,-): Promise<UserDetails> => {- const url = `${apiOrigin}/users/details/v2`;- const res = await fetch(url, { headers: { "X-Auth-Token": authToken } });- if (!res.ok) throw new Error(`Failed to fetch ${url}: HTTP ${res.status}`);- return UserDetailsSchema.parse(await res.json());-};--export const requireEmail = ({ email }: Pick<StaffSession, "email">) => {- if (!email) throw new Error("Email not found");- return email;-};--export const requireToken = ({ token }: Pick<StaffSession, "token">) => {- if (!token) throw new Error("Token not found");- return token;-};--export const responseErrorMessage = async (- response: Response,- fallback: string,-) => {- const text = await response.text();- if (!text) {- return fallback;- }-- try {- const body = JSON.parse(text) as unknown;- if (body && typeof body === "object" && "message" in body) {- const { message } = body as { message?: unknown };- if (typeof message === "string" && message) {- return message;- }- }- } catch {- return text;- }-- return text;-};--export const getCurrentAdminUser = async <T>(- session: StaffSession,-): Promise<T> => {- const email = requireEmail(session);- const token = requireToken(session);- const url = `${apiOrigin}/admin/user?email=${encodeURIComponent(email)}`;- const response = await fetch(url, {- headers: { "Content-Type": "application/json", "X-Auth-Token": token },- });- if (!response.ok) {- throw new Error(- await responseErrorMessage(response, "Failed to fetch user data"),- );- }- return (await response.json()) as T;-};--export const getCurrentAdminUserId = async (session: StaffSession) => {- const userData = await getCurrentAdminUser<{- subscription?: { userID?: string } | null;- }>(session);- const userId = userData.subscription?.userID;- if (!userId) throw new Error("User ID not found");- return userId;-};