Skip to content

Commit

Permalink
Add option to automatically retry refresh with /v1 prefix on error
Browse files Browse the repository at this point in the history
  • Loading branch information
davidisaaclee committed Jan 2, 2023
1 parent 2c85e75 commit c8aa908
Showing 1 changed file with 39 additions and 11 deletions.
50 changes: 39 additions & 11 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,15 @@ export interface IRefreshTokenOpts {
* @defaultValue false
*/
forcePrefixV1?: boolean;

/**
* If true, automatically retries the refresh request using a `/v1` prefix
* if request fails with an `M_UNRECOGNIZED` error. This is a workaround to
* target Synapse before and after v1.72.
* This has no effect if `forcePrefixV1` is true.
* @defaultValue false
*/
retryWithPrefixV1OnUnrecognizedRequest?: boolean;
}

export enum RoomVersionStability {
Expand Down Expand Up @@ -7527,17 +7536,36 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
* @returns Promise which resolves to the new token.
* @returns Rejects with an error response.
*/
public refreshToken(refreshToken: string, options: IRefreshTokenOpts = {}): Promise<IRefreshTokenResponse> {
return this.http.authedRequest(
Method.Post,
"/refresh",
undefined,
{ refresh_token: refreshToken },
{
prefix: options.forcePrefixV1 ? ClientPrefix.V1 : ClientPrefix.V3,
inhibitLogoutEmit: true, // we don't want to cause logout loops
},
);
public async refreshToken(refreshToken: string, options: IRefreshTokenOpts = {}): Promise<IRefreshTokenResponse> {
try {
return await this.http.authedRequest(
Method.Post,
"/refresh",
undefined,
{ refresh_token: refreshToken },
{
prefix: options.forcePrefixV1 ? ClientPrefix.V1 : ClientPrefix.V3,
inhibitLogoutEmit: true, // we don't want to cause logout loops
},
);
} catch (err) {
// If caller wants to `retryWithPrefixV1OnUnrecognizedRequest`, try
// again with `forcePrefixV1: true`.
if (
err instanceof MatrixError &&
err.errcode === "M_UNRECOGNIZED" &&
options.retryWithPrefixV1OnUnrecognizedRequest &&
!options.forcePrefixV1
) {
return this.refreshToken(refreshToken, {
...options,
forcePrefixV1: true,
});
}

// Otherwise, pass along the caught error.
throw err;
}
}

/**
Expand Down

0 comments on commit c8aa908

Please sign in to comment.