diff --git a/src/api/chat.ts b/src/api/chat.ts index 6570255..e62f954 100644 --- a/src/api/chat.ts +++ b/src/api/chat.ts @@ -1,4 +1,4 @@ -import { generateClient } from 'aws-amplify/api'; +import { generateClient, type GraphQLSubscription } from 'aws-amplify/api'; import type { MediaKind, Platform } from 'onehook-api-client'; import { callSdk, sdkClient } from './sdk-client'; import { hasGraphQLErrors, toGraphQLError } from './graphql-error'; @@ -6,75 +6,45 @@ import type { Message as ChatMessage, MessageReceipt, DeletedMessage, + MessageReaction, + TypingIndicator, + ScreenshotEvent, + StarredMessage, + PresenceUpdate as GeneratedPresenceUpdate, + MessageContentType as GeneratedMessageContentType, + PresenceState as GeneratedPresenceState, + Subscription, } from 'onehook-api-client/graphql'; -export type { ChatMessage, MessageReceipt, DeletedMessage }; +export type { ChatMessage, MessageReceipt, DeletedMessage, MessageReaction, TypingIndicator, ScreenshotEvent }; // ───────────────────────────────────────────────────────────────────────────── -// Local types for the rich-messaging capabilities added to the chat GraphQL schema -// (reactions, replies, content types, typing/presence/screenshot). These are declared here rather -// than imported from `onehook-api-client/graphql` because that SDK is regenerated and republished -// from the backend schema asynchronously; declaring them locally lets the client use the new -// operations immediately and stay type-safe. Once the SDK republishes they can be swapped for the -// generated types. +// Chat types: the backend's generated GraphQL types (onehook-api-client/graphql). The two enums are +// re-expressed as their string values, so code keeps writing 'TEXT' / 'ONLINE'; a generated value is +// still assignable to them, and a value the schema drops stops compiling. // ───────────────────────────────────────────────────────────────────────────── -/** Mirrors the GraphQL `MessageContentType` enum. */ -export type MessageContentType = 'TEXT' | 'IMAGE' | 'VOICE' | 'STICKER' | 'GIF' | 'FILE'; +/** The GraphQL `MessageContentType` values. */ +export type MessageContentType = `${GeneratedMessageContentType}`; -/** Mirrors the GraphQL `PresenceState` enum. */ -export type PresenceState = 'ONLINE' | 'OFFLINE'; +/** The GraphQL `PresenceState` values. */ +export type PresenceState = `${GeneratedPresenceState}`; /** - * The chat message with the fields added to the schema. `reactions` is the AWSJSON scalar, delivered - * as a JSON string the client parses into a map of `reactorUserId -> reaction ciphertext`; each value - * is E2E-encrypted exactly like a message body. + * A chat message. `reactions` is the AWSJSON scalar, delivered as a JSON string the client parses into + * a map of `reactorUserId -> reaction ciphertext`; each value is E2E-encrypted exactly like a body. */ export interface ChatMessageExtended extends Omit { contentType?: MessageContentType | null; - replyToMessageId?: string | null; - replyToTimestamp?: number | null; - reactions?: string | null; -} - -/** Real-time fan-out shape of `reactToMessage` / `onMessageReaction`. `reaction` is null on a clear. */ -export interface MessageReaction { - matchId: string; - messageId: string; - timestamp: number; - userId: string; - reaction?: string | null; -} - -/** Ephemeral typing signal (`sendTypingIndicator` / `onTypingIndicator`). */ -export interface TypingIndicator { - matchId: string; - userId: string; - isTyping: boolean; - timestamp: number; } /** Ephemeral presence signal (`updatePresence` / `onPresenceUpdate`). `lastActiveAt` is "last seen". */ -export interface PresenceUpdate { - matchId: string; - userId: string; +export interface PresenceUpdate extends Omit { state: PresenceState; - lastActiveAt: number; -} - -/** Ephemeral screenshot signal (`notifyScreenshot` / `onScreenshotTaken`). */ -export interface ScreenshotEvent { - matchId: string; - userId: string; - timestamp: number; } /** Private caller-scoped star record (`getStarredMessages` / `setMessageStarred`). */ -export interface StarredMessageRecord { - matchId: string; - messageId: string; - starredAt: number; -} +export type StarredMessageRecord = StarredMessage; /** Optional fields for {@link ChatMessagingApi.sendMessage}. */ export interface SendMessageOptions { @@ -368,6 +338,33 @@ export function appSyncClient() { return client(); } +/** A field of the generated GraphQL `Subscription` type. */ +export type SubscriptionField = Exclude; + +/** + * Subscribes to one field of the generated `Subscription` type and calls `onValue` with each non-null + * value. The payload type comes from the schema, so a renamed or reshaped subscription stops compiling + * here. Returns an unsubscribe function. + */ +export function subscribeToField( + query: string, + variables: Record, + field: F, + onValue: (value: NonNullable) => void, + logTag: string +): () => void { + const sub = appSyncClient() + .graphql>({ query, variables }) + .subscribe({ + next: ({ data }) => { + const value = data?.[field]; + if (value != null) onValue(value); + }, + error: (err) => console.error(`[${logTag}] ${String(field)} subscription error`, err), + }); + return () => sub.unsubscribe(); +} + async function graphql(query: string, variables: Record): Promise { let res: unknown; try { @@ -532,17 +529,7 @@ export const ChatMessagingApi = { /** Subscribe to new messages for a match. Returns an unsubscribe function. */ subscribeToNewMessages: (matchId: string, onMessage: (m: ChatMessageExtended) => void): (() => void) => { - const sub = ( - client().graphql({ query: ON_NEW_MESSAGE, variables: { matchId } }) as unknown as { - subscribe: (o: { next: (v: { data?: { onNewMessage?: ChatMessageExtended } }) => void; error: (e: unknown) => void }) => { unsubscribe: () => void }; - } - ).subscribe({ - next: ({ data }) => { - if (data?.onNewMessage) onMessage(data.onNewMessage); - }, - error: (err) => console.error('[chat] onNewMessage subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_NEW_MESSAGE, { matchId }, 'onNewMessage', onMessage, 'chat'); }, /** Subscribe to delivery/read receipt updates. Returns an unsubscribe function. */ @@ -550,17 +537,7 @@ export const ChatMessagingApi = { matchId: string, onUpdate: (r: MessageReceipt) => void ): (() => void) => { - const sub = ( - client().graphql({ query: ON_MESSAGE_STATUS_UPDATE, variables: { matchId } }) as unknown as { - subscribe: (o: { next: (v: { data?: { onMessageStatusUpdate?: MessageReceipt } }) => void; error: (e: unknown) => void }) => { unsubscribe: () => void }; - } - ).subscribe({ - next: ({ data }) => { - if (data?.onMessageStatusUpdate) onUpdate(data.onMessageStatusUpdate); - }, - error: (err) => console.error('[chat] onMessageStatusUpdate subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_MESSAGE_STATUS_UPDATE, { matchId }, 'onMessageStatusUpdate', onUpdate, 'chat'); }, /** Subscribe to message deletions. Returns an unsubscribe function. */ @@ -568,17 +545,7 @@ export const ChatMessagingApi = { matchId: string, onDelete: (d: DeletedMessage) => void ): (() => void) => { - const sub = ( - client().graphql({ query: ON_MESSAGE_DELETED, variables: { matchId } }) as unknown as { - subscribe: (o: { next: (v: { data?: { onMessageDeleted?: DeletedMessage } }) => void; error: (e: unknown) => void }) => { unsubscribe: () => void }; - } - ).subscribe({ - next: ({ data }) => { - if (data?.onMessageDeleted) onDelete(data.onMessageDeleted); - }, - error: (err) => console.error('[chat] onMessageDeleted subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_MESSAGE_DELETED, { matchId }, 'onMessageDeleted', onDelete, 'chat'); }, /** Subscribe to message reactions for a match. Returns an unsubscribe function. */ @@ -586,17 +553,7 @@ export const ChatMessagingApi = { matchId: string, onReaction: (r: MessageReaction) => void ): (() => void) => { - const sub = ( - client().graphql({ query: ON_MESSAGE_REACTION, variables: { matchId } }) as unknown as { - subscribe: (o: { next: (v: { data?: { onMessageReaction?: MessageReaction } }) => void; error: (e: unknown) => void }) => { unsubscribe: () => void }; - } - ).subscribe({ - next: ({ data }) => { - if (data?.onMessageReaction) onReaction(data.onMessageReaction); - }, - error: (err) => console.error('[chat] onMessageReaction subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_MESSAGE_REACTION, { matchId }, 'onMessageReaction', onReaction, 'chat'); }, /** Subscribe to the peer's typing indicator. Returns an unsubscribe function. */ @@ -604,17 +561,7 @@ export const ChatMessagingApi = { matchId: string, onTyping: (t: TypingIndicator) => void ): (() => void) => { - const sub = ( - client().graphql({ query: ON_TYPING_INDICATOR, variables: { matchId } }) as unknown as { - subscribe: (o: { next: (v: { data?: { onTypingIndicator?: TypingIndicator } }) => void; error: (e: unknown) => void }) => { unsubscribe: () => void }; - } - ).subscribe({ - next: ({ data }) => { - if (data?.onTypingIndicator) onTyping(data.onTypingIndicator); - }, - error: (err) => console.error('[chat] onTypingIndicator subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_TYPING_INDICATOR, { matchId }, 'onTypingIndicator', onTyping, 'chat'); }, /** Subscribe to the peer's presence (online/offline + last-seen). Returns an unsubscribe function. */ @@ -622,17 +569,7 @@ export const ChatMessagingApi = { matchId: string, onPresence: (p: PresenceUpdate) => void ): (() => void) => { - const sub = ( - client().graphql({ query: ON_PRESENCE_UPDATE, variables: { matchId } }) as unknown as { - subscribe: (o: { next: (v: { data?: { onPresenceUpdate?: PresenceUpdate } }) => void; error: (e: unknown) => void }) => { unsubscribe: () => void }; - } - ).subscribe({ - next: ({ data }) => { - if (data?.onPresenceUpdate) onPresence(data.onPresenceUpdate); - }, - error: (err) => console.error('[chat] onPresenceUpdate subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_PRESENCE_UPDATE, { matchId }, 'onPresenceUpdate', onPresence, 'chat'); }, /** Subscribe to screenshot notifications from the peer. Returns an unsubscribe function. */ @@ -640,17 +577,7 @@ export const ChatMessagingApi = { matchId: string, onScreenshot: (s: ScreenshotEvent) => void ): (() => void) => { - const sub = ( - client().graphql({ query: ON_SCREENSHOT_TAKEN, variables: { matchId } }) as unknown as { - subscribe: (o: { next: (v: { data?: { onScreenshotTaken?: ScreenshotEvent } }) => void; error: (e: unknown) => void }) => { unsubscribe: () => void }; - } - ).subscribe({ - next: ({ data }) => { - if (data?.onScreenshotTaken) onScreenshot(data.onScreenshotTaken); - }, - error: (err) => console.error('[chat] onScreenshotTaken subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_SCREENSHOT_TAKEN, { matchId }, 'onScreenshotTaken', onScreenshot, 'chat'); }, }; diff --git a/src/api/key-recovery.ts b/src/api/key-recovery.ts index d7889d4..f78865d 100644 --- a/src/api/key-recovery.ts +++ b/src/api/key-recovery.ts @@ -1,4 +1,8 @@ -import { appSyncClient } from './chat'; +import type { + KeyRecoverySession as GeneratedKeyRecoverySession, + KeyRecoveryStatus as GeneratedKeyRecoveryStatus, +} from 'onehook-api-client/graphql'; +import { appSyncClient, subscribeToField } from './chat'; import { hasGraphQLErrors, toGraphQLError } from './graphql-error'; /** @@ -9,29 +13,18 @@ import { hasGraphQLErrors, toGraphQLError } from './graphql-error'; * public key, a random challenge, two device ids and a status. The sealed key bundle never does — it * is displayed as a QR code on one device and read by the other's camera. * - * Types are declared locally rather than imported from `onehook-api-client/graphql`, because that - * package is generated and published from the backend schema; declaring them here keeps the client - * buildable in the same commit that adds the schema fields. + * Types are the backend's generated GraphQL types (onehook-api-client/graphql), with the status enum + * re-expressed as its string values so code keeps writing 'PENDING'. */ -export type KeyRecoveryStatus = 'PENDING' | 'DISPLAYING' | 'COMPLETED' | 'DECLINED'; - -export interface KeyRecoverySession { - userId: string; - sessionId: string; - /** The already-registered device asked to hand over the history key. */ - sourceDeviceId: string; - /** The new device receiving it. */ - targetDeviceId: string; - /** Base64 SPKI P-256 public key the target minted for this session only. */ - targetEphemeralPublicKey: string; - /** Base64 32-byte challenge minted by the target; the transfer HKDF salt. */ - challenge: string; +export type KeyRecoveryStatus = `${GeneratedKeyRecoveryStatus}`; + +/** + * A recovery session. `targetEphemeralPublicKey` is the base64 SPKI P-256 key the new device minted for + * this session only; `challenge` the base64 32-byte transfer HKDF salt; times are epoch milliseconds. + */ +export interface KeyRecoverySession extends Omit { status: KeyRecoveryStatus; - /** Epoch milliseconds. */ - createdAt: number; - /** Epoch milliseconds. After this the session is dead on both sides. */ - expiresAt: number; } const SESSION_FIELDS = ` @@ -118,13 +111,6 @@ async function graphql(query: string, variables: Record): Pr return (res as { data: T }).data; } -type Subscribable = { - subscribe: (observer: { - next: (value: { data?: T }) => void; - error: (error: unknown) => void; - }) => { unsubscribe: () => void }; -}; - export const KeyRecoveryApi = { /** * Opens a session from the NEW device. Idempotent per device pair server-side: calling it again @@ -193,18 +179,7 @@ export const KeyRecoveryApi = { sourceDeviceId: string, onRequest: (session: KeyRecoverySession) => void ): (() => void) => { - const sub = ( - appSyncClient().graphql({ - query: ON_KEY_RECOVERY_REQUESTED, - variables: { userId, sourceDeviceId }, - }) as unknown as Subscribable<{ onKeyRecoveryRequested?: KeyRecoverySession }> - ).subscribe({ - next: ({ data }) => { - if (data?.onKeyRecoveryRequested) onRequest(data.onKeyRecoveryRequested); - }, - error: (err) => console.error('[recovery] onKeyRecoveryRequested subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_KEY_RECOVERY_REQUESTED, { userId, sourceDeviceId }, 'onKeyRecoveryRequested', onRequest, 'recovery'); }, /** TARGET device: status changes on its own request (notably the moment the QR goes up). */ @@ -213,17 +188,6 @@ export const KeyRecoveryApi = { targetDeviceId: string, onUpdate: (session: KeyRecoverySession) => void ): (() => void) => { - const sub = ( - appSyncClient().graphql({ - query: ON_KEY_RECOVERY_UPDATED, - variables: { userId, targetDeviceId }, - }) as unknown as Subscribable<{ onKeyRecoveryUpdated?: KeyRecoverySession }> - ).subscribe({ - next: ({ data }) => { - if (data?.onKeyRecoveryUpdated) onUpdate(data.onKeyRecoveryUpdated); - }, - error: (err) => console.error('[recovery] onKeyRecoveryUpdated subscription error', err), - }); - return () => sub.unsubscribe(); + return subscribeToField(ON_KEY_RECOVERY_UPDATED, { userId, targetDeviceId }, 'onKeyRecoveryUpdated', onUpdate, 'recovery'); }, }; diff --git a/src/features/moderation/report/evidence-api.ts b/src/features/moderation/report/evidence-api.ts index 053f1c3..a33b7cb 100644 --- a/src/features/moderation/report/evidence-api.ts +++ b/src/features/moderation/report/evidence-api.ts @@ -15,6 +15,7 @@ * (SDK client, S3 fetch, token provider, sleep) so the orchestration is unit-testable without a * browser or the network. No message text or user ids are ever logged here. */ +import type { ModerationEvidence } from 'saha-equation-admin-portal-client'; import { portalModerationBaseUrl } from '../../../utils/env.config'; import { createModerationEvidenceClient, @@ -58,17 +59,11 @@ export interface PresignRequest { includesMedia: boolean; } -export interface PresignUpload { - url: string; - method: string; - headers: Record; -} +/** The presigned PUT (the portal SDK's generated `EvidenceUpload`). */ +export type PresignUpload = ModerationEvidence.EvidenceUpload; -export interface PresignResponse { - evidenceId: string; - upload: PresignUpload; - expiresAt: number; -} +/** The portal SDK's generated `PresignEvidenceResponse`. */ +export type PresignResponse = ModerationEvidence.PresignEvidenceResponse; export interface CompleteRequest { reportId: string; @@ -80,11 +75,8 @@ export interface CompleteRequest { lastSentAt: number; } -export interface CompleteResponse { - evidenceId: string; - status: string; - idempotent: boolean; -} +/** The portal SDK's generated `CompleteEvidenceResponse`. */ +export type CompleteResponse = ModerationEvidence.CompleteEvidenceResponse; export interface RetryOptions { /** Max additional attempts after the first on a retryable 503. Default 4. */ @@ -167,7 +159,7 @@ async function evidenceCall(call: () => Promise): Promise { const evidenceClient = clientOf(t); - return evidenceCall(() => evidenceClient.presignEvidence(req)) as Promise; + return evidenceCall(() => evidenceClient.presignEvidence(req)); } /** @@ -220,7 +212,7 @@ export async function completeEvidence( while (true) { try { const evidenceClient = clientOf(t); - return (await evidenceCall(() => evidenceClient.completeEvidence(req))) as CompleteResponse; + return await evidenceCall(() => evidenceClient.completeEvidence(req)); } catch (err) { const retryable = err instanceof EvidenceError && err.status === 503 && err.code === FINALIZE_RETRY_CODE; diff --git a/src/lib/mr-onehook.ts b/src/lib/mr-onehook.ts index d45c878..bfcd110 100644 --- a/src/lib/mr-onehook.ts +++ b/src/lib/mr-onehook.ts @@ -31,7 +31,7 @@ import { MrOneHookPlan, type ChatAttachment, type ChatAttachmentRef, - type ProductConnectionChatCommandInput, + type ProductConnectionChatCommandOutput, } from 'onehook-mr-onehook-client'; import { fetchIdToken, mrOneHookClient, sdkFailure, withoutMetadata } from '../api/external-sdk-clients'; import { @@ -455,7 +455,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook // One generated-SDK call (ProductConnectionChat). An HTTP failure comes back as {status, body} so // the session and availability rules below can read the error code; a network error throws. type Attempt = - | { ok: true; data: unknown } + | { ok: true; data: Omit } | { ok: false; status: number; body: { error?: unknown } & Record }; const attempt = async (useSession: boolean): Promise => { const body = buildMemberChatRequestBody({ @@ -473,7 +473,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook : {}), }); try { - const out = await mrOneHookClient.productConnectionChat(body as ProductConnectionChatCommandInput); + const out = await mrOneHookClient.productConnectionChat(body); return { ok: true, data: withoutMetadata(out) }; } catch (err) { const failure = sdkFailure(err); @@ -516,7 +516,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook if (outcome) throw new MemberChatTerminalError(outcome); throw new Error('SERVER_ERROR'); } - return parseMemberChatResponse((response as { data: unknown }).data); + return parseMemberChatResponse(response.data); }, // scope captured via key + matchId. // eslint-disable-next-line react-hooks/exhaustive-deps