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
183 changes: 55 additions & 128 deletions src/api/chat.ts
Original file line number Diff line number Diff line change
@@ -1,80 +1,50 @@
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';
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<ChatMessage, 'contentType'> {
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<GeneratedPresenceUpdate, 'state'> {
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 {
Expand Down Expand Up @@ -368,6 +338,33 @@ export function appSyncClient() {
return client();
}

/** A field of the generated GraphQL `Subscription` type. */
export type SubscriptionField = Exclude<keyof Subscription, '__typename'>;

/**
* 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<F extends SubscriptionField>(
query: string,
variables: Record<string, unknown>,
field: F,
onValue: (value: NonNullable<Subscription[F]>) => void,
logTag: string
): () => void {
const sub = appSyncClient()
.graphql<GraphQLSubscription<Subscription>>({ 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<T>(query: string, variables: Record<string, unknown>): Promise<T> {
let res: unknown;
try {
Expand Down Expand Up @@ -532,125 +529,55 @@ 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. */
subscribeToStatusUpdates: (
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. */
subscribeToDeletions: (
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. */
subscribeToReactions: (
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. */
subscribeToTyping: (
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. */
subscribeToPresence: (
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. */
subscribeToScreenshots: (
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');
},
};

Expand Down
68 changes: 16 additions & 52 deletions src/api/key-recovery.ts
Original file line number Diff line number Diff line change
@@ -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';

/**
Expand All @@ -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<GeneratedKeyRecoverySession, 'status'> {
status: KeyRecoveryStatus;
/** Epoch milliseconds. */
createdAt: number;
/** Epoch milliseconds. After this the session is dead on both sides. */
expiresAt: number;
}

const SESSION_FIELDS = `
Expand Down Expand Up @@ -118,13 +111,6 @@ async function graphql<T>(query: string, variables: Record<string, unknown>): Pr
return (res as { data: T }).data;
}

type Subscribable<T> = {
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
Expand Down Expand Up @@ -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). */
Expand All @@ -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');
},
};
Loading
Loading