Skip to content

Commit

Permalink
Combine QrCodeEvent, SasEvent and VerificationEvent (#3386)
Browse files Browse the repository at this point in the history
* Move IReciprocateQr to `crypto-api` and rename

* Move ISasEvent to `crypto-api`, and rename

... and add some ✨comments✨

* Combine QrCodeEvent, SasEvent and VerificationEvent together

... as a precursor to extracting a single `Verifier` interface for `SAS` and `ReciprocateQRCode`.

`enum`s are slightly magical things that have both a type and a value, so we
have to re-export their backwards-compatibility fudges twice.

* Update src/crypto/verification/Base.ts
  • Loading branch information
richvdh authored May 22, 2023
1 parent b62fac9 commit 614f446
Show file tree
Hide file tree
Showing 5 changed files with 153 additions and 48 deletions.
2 changes: 2 additions & 0 deletions src/crypto-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,5 @@ export class DeviceVerificationStatus {
return this.localVerified || (this.trustCrossSignedDevices && this.crossSigningVerified);
}
}

export * from "./crypto-api/verification";
112 changes: 112 additions & 0 deletions src/crypto-api/verification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
Copyright 2023 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { MatrixEvent } from "../models/event";

/** Events emitted by `Verifier`. */
export enum VerifierEvent {
/**
* The verification has been cancelled, by us or the other side.
*
* The payload is either an {@link Error}, or an (incoming or outgoing) {@link MatrixEvent}, depending on
* unspecified reasons.
*/
Cancel = "cancel",

/**
* SAS data has been exchanged and should be displayed to the user.
*
* The payload is the {@link ShowQrCodeCallbacks} object.
*/
ShowSas = "show_sas",

/**
* QR code data should be displayed to the user.
*
* The payload is the {@link ShowQrCodeCallbacks} object.
*/
ShowReciprocateQr = "show_reciprocate_qr",
}

/** Listener type map for {@link VerifierEvent}s. */
export type VerifierEventHandlerMap = {
[VerifierEvent.Cancel]: (e: Error | MatrixEvent) => void;
[VerifierEvent.ShowSas]: (sas: ShowSasCallbacks) => void;
[VerifierEvent.ShowReciprocateQr]: (qr: ShowQrCodeCallbacks) => void;
};

/**
* Callbacks for user actions while a QR code is displayed.
*
* This is exposed as the payload of a `VerifierEvent.ShowReciprocateQr` event, or can be retrieved directly from the
* verifier as `reciprocateQREvent`.
*/
export interface ShowQrCodeCallbacks {
/** The user confirms that the verification data matches */
confirm(): void;

/** Cancel the verification flow */
cancel(): void;
}

/**
* Callbacks for user actions while a SAS is displayed.
*
* This is exposed as the payload of a `VerifierEvent.ShowSas` event, or directly from the verifier as `sasEvent`.
*/
export interface ShowSasCallbacks {
/** The generated SAS to be shown to the user */
sas: GeneratedSas;

/** Function to call if the user confirms that the SAS matches.
*
* @returns A Promise that completes once the m.key.verification.mac is queued.
*/
confirm(): Promise<void>;

/**
* Function to call if the user finds the SAS does not match.
*
* Sends an `m.key.verification.cancel` event with a `m.mismatched_sas` error code.
*/
mismatch(): void;

/** Cancel the verification flow */
cancel(): void;
}

/** A generated SAS to be shown to the user, in alternative formats */
export interface GeneratedSas {
/**
* The SAS as three numbers between 0 and 8191.
*
* Only populated if the `decimal` SAS method was negotiated.
*/
decimal?: [number, number, number];

/**
* The SAS as seven emojis.
*
* Only populated if the `emoji` SAS method was negotiated.
*/
emoji?: EmojiMapping[];
}

/**
* An emoji for the generated SAS. A tuple `[emoji, name]` where `emoji` is the emoji itself and `name` is the
* English name.
*/
export type EmojiMapping = [emoji: string, name: string];
21 changes: 14 additions & 7 deletions src/crypto/verification/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import { KeysDuringVerification, requestKeysDuringVerification } from "../CrossS
import { IVerificationChannel } from "./request/Channel";
import { MatrixClient } from "../../client";
import { VerificationRequest } from "./request/VerificationRequest";
import { ListenerMap, TypedEventEmitter } from "../../models/typed-event-emitter";
import { TypedEventEmitter } from "../../models/typed-event-emitter";
import { VerifierEvent, VerifierEventHandlerMap } from "../../crypto-api/verification";

const timeoutException = new Error("Verification timed out");

Expand All @@ -40,18 +41,24 @@ export class SwitchStartEventError extends Error {

export type KeyVerifier = (keyId: string, device: DeviceInfo, keyInfo: string) => void;

export enum VerificationEvent {
Cancel = "cancel",
}
/** @deprecated use VerifierEvent */
export type VerificationEvent = VerifierEvent;
/** @deprecated use VerifierEvent */
export const VerificationEvent = VerifierEvent;

/** @deprecated use VerifierEventHandlerMap */
export type VerificationEventHandlerMap = {
[VerificationEvent.Cancel]: (e: Error | MatrixEvent) => void;
};

// The type parameters of VerificationBase are no longer used, but we need some placeholders to maintain
// backwards compatibility with applications that reference the class.
export class VerificationBase<
Events extends string,
Arguments extends ListenerMap<Events | VerificationEvent>,
> extends TypedEventEmitter<Events | VerificationEvent, Arguments, VerificationEventHandlerMap> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Events extends string = VerifierEvent,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Arguments = VerifierEventHandlerMap,
> extends TypedEventEmitter<VerifierEvent, VerifierEventHandlerMap> {
private cancelled = false;
private _done = false;
private promise: Promise<void> | null = null;
Expand Down
23 changes: 8 additions & 15 deletions src/crypto/verification/QRCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,26 @@ limitations under the License.
* QR code key verification.
*/

import { VerificationBase as Base, VerificationEventHandlerMap } from "./Base";
import { VerificationBase as Base } from "./Base";
import { newKeyMismatchError, newUserCancelledError } from "./Error";
import { decodeBase64, encodeUnpaddedBase64 } from "../olmlib";
import { logger } from "../../logger";
import { VerificationRequest } from "./request/VerificationRequest";
import { MatrixClient } from "../../client";
import { IVerificationChannel } from "./request/Channel";
import { MatrixEvent } from "../../models/event";
import { ShowQrCodeCallbacks, VerifierEvent } from "../../crypto-api/verification";

export const SHOW_QR_CODE_METHOD = "m.qr_code.show.v1";
export const SCAN_QR_CODE_METHOD = "m.qr_code.scan.v1";

interface IReciprocateQr {
confirm(): void;
cancel(): void;
}

export enum QrCodeEvent {
ShowReciprocateQr = "show_reciprocate_qr",
}

type EventHandlerMap = {
[QrCodeEvent.ShowReciprocateQr]: (qr: IReciprocateQr) => void;
} & VerificationEventHandlerMap;
/** @deprecated use VerifierEvent */
export type QrCodeEvent = VerifierEvent;
/** @deprecated use VerifierEvent */
export const QrCodeEvent = VerifierEvent;

export class ReciprocateQRCode extends Base<QrCodeEvent, EventHandlerMap> {
public reciprocateQREvent?: IReciprocateQr;
export class ReciprocateQRCode extends Base {
public reciprocateQREvent?: ShowQrCodeCallbacks;

public static factory(
channel: IVerificationChannel,
Expand Down
43 changes: 17 additions & 26 deletions src/crypto/verification/SAS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ limitations under the License.
import anotherjson from "another-json";
import { Utility, SAS as OlmSAS } from "@matrix-org/olm";

import { VerificationBase as Base, SwitchStartEventError, VerificationEventHandlerMap } from "./Base";
import { VerificationBase as Base, SwitchStartEventError } from "./Base";
import {
errorFactory,
newInvalidMessageError,
Expand All @@ -33,6 +33,14 @@ import { logger } from "../../logger";
import { IContent, MatrixEvent } from "../../models/event";
import { generateDecimalSas } from "./SASDecimal";
import { EventType } from "../../@types/event";
import { EmojiMapping, GeneratedSas, ShowSasCallbacks, VerifierEvent } from "../../crypto-api/verification";

// backwards-compatibility exports
export {
ShowSasCallbacks as ISasEvent,
GeneratedSas as IGeneratedSas,
EmojiMapping,
} from "../../crypto-api/verification";

const START_TYPE = EventType.KeyVerificationStart;

Expand All @@ -44,8 +52,6 @@ const newMismatchedSASError = errorFactory("m.mismatched_sas", "Mismatched short

const newMismatchedCommitmentError = errorFactory("m.mismatched_commitment", "Mismatched commitment");

type EmojiMapping = [emoji: string, name: string];

const emojiMapping: EmojiMapping[] = [
["🐶", "dog"], // 0
["🐱", "cat"], // 1
Expand Down Expand Up @@ -133,20 +139,8 @@ const sasGenerators = {
emoji: generateEmojiSas,
} as const;

export interface IGeneratedSas {
decimal?: [number, number, number];
emoji?: EmojiMapping[];
}

export interface ISasEvent {
sas: IGeneratedSas;
confirm(): Promise<void>;
cancel(): void;
mismatch(): void;
}

function generateSas(sasBytes: Uint8Array, methods: string[]): IGeneratedSas {
const sas: IGeneratedSas = {};
function generateSas(sasBytes: Uint8Array, methods: string[]): GeneratedSas {
const sas: GeneratedSas = {};
for (const method of methods) {
if (method in sasGenerators) {
// @ts-ignore - ts doesn't like us mixing types like this
Expand Down Expand Up @@ -220,19 +214,16 @@ function intersection<T>(anArray: T[], aSet: Set<T>): T[] {
return Array.isArray(anArray) ? anArray.filter((x) => aSet.has(x)) : [];
}

export enum SasEvent {
ShowSas = "show_sas",
}

type EventHandlerMap = {
[SasEvent.ShowSas]: (sas: ISasEvent) => void;
} & VerificationEventHandlerMap;
/** @deprecated use VerifierEvent */
export type SasEvent = VerifierEvent;
/** @deprecated use VerifierEvent */
export const SasEvent = VerifierEvent;

export class SAS extends Base<SasEvent, EventHandlerMap> {
export class SAS extends Base {
private waitingForAccept?: boolean;
public ourSASPubKey?: string;
public theirSASPubKey?: string;
public sasEvent?: ISasEvent;
public sasEvent?: ShowSasCallbacks;

// eslint-disable-next-line @typescript-eslint/naming-convention
public static get NAME(): string {
Expand Down

0 comments on commit 614f446

Please sign in to comment.