Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add a customProvider option to the sdk JwtBearerAuth class #5105

Merged
merged 2 commits into from
Jan 10, 2025
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
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import type { Eip1193Provider } from 'ethers';

import { Env, Platform } from '../../shared/env';
import { JwtBearerAuth } from '../authentication';
import type {
AuthSigningOptions,
AuthStorageOptions,
} from '../authentication-jwt-bearer/types';
import { AuthType } from '../authentication-jwt-bearer/types';
import { SNAP_ORIGIN } from '../utils/messaging-signing-snap-requests';

// Alias mocking variables with ANY to test runtime safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -42,13 +45,15 @@ const mockAuthOptions = () => {
* @param mockPublicKey - provide the mock public key
* @param authOptionsOverride - overrides
* @param authOptionsOverride.signing - override auth signing
* @param authOptionsOverride.customProvider - override custom provider
* @returns Auth instance
*/
export function arrangeAuth(
type: `${AuthType}`,
mockPublicKey: string,
authOptionsOverride?: {
signing?: AuthSigningOptions;
customProvider?: Eip1193Provider;
},
) {
const authOptionsMock = mockAuthOptions();
Expand All @@ -67,6 +72,7 @@ export function arrangeAuth(
type: AuthType.SRP,
},
{
customProvider: authOptionsOverride?.customProvider,
storage: {
getLoginResponse: authOptionsMock.mockGetLoginResponse,
setLoginResponse: authOptionsMock.mockSetLoginResponse,
Expand Down Expand Up @@ -103,3 +109,16 @@ export function arrangeAuth(

throw new Error('Unable to arrange auth mock for invalid auth type');
}

/**
* Mock utility - creates a mock provider
* @returns mock provider
*/
export const arrangeMockProvider = () => {
const mockRequest = jest.fn().mockResolvedValue({ [SNAP_ORIGIN]: {} });
const mockProvider: Eip1193Provider = {
request: mockRequest,
};

return { mockProvider, mockRequest };
};
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Eip1193Provider } from 'ethers';

import { ValidationError } from '../errors';
import { getMetaMaskProviderEIP6963 } from '../utils/eip-6963-metamask-provider';
import {
Expand Down Expand Up @@ -32,37 +34,49 @@ const getDefaultEIP6963Provider = async () => {
return provider;
};

const defaultEIP6963SigningOptions: AuthSigningOptions = {
const getDefaultEIP6963SigningOptions = (
customProvider?: Eip1193Provider,
): AuthSigningOptions => ({
getIdentifier: async (): Promise<string> => {
const provider = await getDefaultEIP6963Provider();
const provider = customProvider ?? (await getDefaultEIP6963Provider());
return await MESSAGE_SIGNING_SNAP.getPublicKey(provider);
},
signMessage: async (message: string): Promise<string> => {
const provider = await getDefaultEIP6963Provider();
const provider = customProvider ?? (await getDefaultEIP6963Provider());
if (!message.startsWith('metamask:')) {
throw new ValidationError('message must start with "metamask:"');
}
const formattedMessage = message as `metamask:${string}`;
return await MESSAGE_SIGNING_SNAP.signMessage(provider, formattedMessage);
},
};
});

export class SRPJwtBearerAuth implements IBaseAuth {
#config: AuthConfig;

#options: Required<JwtBearerAuth_SRP_Options>;

#customProvider?: Eip1193Provider;

constructor(
config: AuthConfig & { type: AuthType.SRP },
options: JwtBearerAuth_SRP_Options,
options: JwtBearerAuth_SRP_Options & { customProvider?: Eip1193Provider },
) {
this.#config = config;
this.#customProvider = options.customProvider;
this.#options = {
storage: options.storage,
signing: options.signing ?? defaultEIP6963SigningOptions,
signing:
options.signing ??
getDefaultEIP6963SigningOptions(this.#customProvider),
};
}

setCustomProvider(provider: Eip1193Provider) {
this.#customProvider = provider;
this.#options.signing = getDefaultEIP6963SigningOptions(provider);
}

async getAccessToken(): Promise<string> {
const session = await this.#getAuthSession();
if (session) {
Expand Down Expand Up @@ -92,7 +106,8 @@ export class SRPJwtBearerAuth implements IBaseAuth {
}

async isSnapConnected(): Promise<boolean> {
const provider = await getMetaMaskProviderEIP6963();
const provider =
this.#customProvider ?? (await getDefaultEIP6963Provider());
if (!provider) {
return false;
}
Expand All @@ -102,7 +117,9 @@ export class SRPJwtBearerAuth implements IBaseAuth {
}

async connectSnap(): Promise<string> {
const provider = await getDefaultEIP6963Provider();
const provider =
this.#customProvider ?? (await getDefaultEIP6963Provider());

const res = await connectSnap(provider);
return res;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
arrangeAuthAPIs,
} from './__fixtures__/mock-auth';
import type { MockVariable } from './__fixtures__/test-utils';
import { arrangeAuth } from './__fixtures__/test-utils';
import { arrangeAuth, arrangeMockProvider } from './__fixtures__/test-utils';
import { JwtBearerAuth } from './authentication';
import type { LoginResponse, Pair } from './authentication-jwt-bearer/types';
import {
Expand Down Expand Up @@ -143,6 +143,28 @@ describe('Authentication - constructor()', () => {
);
}).toThrow(UnsupportedAuthTypeError);
});

it('supports using a custom provider as a constructor option', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amazing tests!

const { auth } = arrangeAuth('SRP', MOCK_SRP, {
customProvider: arrangeMockProvider().mockProvider,
});

await auth.connectSnap();
const isSnapConnected = await auth.isSnapConnected();

expect(isSnapConnected).toBe(true);
});

it('supports using a custom provider set at a later point in time', async () => {
const { auth } = arrangeAuth('SRP', MOCK_SRP);

auth.setCustomProvider(arrangeMockProvider().mockProvider);

await auth.connectSnap();
const isSnapConnected = await auth.isSnapConnected();

expect(isSnapConnected).toBe(true);
});
});

describe('Authentication - SRP Flow - getAccessToken() & getUserProfile()', () => {
Expand Down
7 changes: 7 additions & 0 deletions packages/profile-sync-controller/src/sdk/authentication.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Eip1193Provider } from 'ethers';

import type { Env } from '../shared/env';
import { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe';
import { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp';
Expand Down Expand Up @@ -44,6 +46,11 @@ export class JwtBearerAuth implements SIWEInterface, SRPInterface {
throw new UnsupportedAuthTypeError('unsupported auth type');
}

setCustomProvider(provider: Eip1193Provider) {
this.#assertSRP(this.#type, this.#sdk);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect! Yeah we only need this for the SRP flow for now 🙂

this.#sdk.setCustomProvider(provider);
}

async getAccessToken(): Promise<string> {
return await this.#sdk.getAccessToken();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Eip1193Provider } from 'ethers';

import type { MockVariable } from '../__fixtures__/test-utils';
import {
arrangeMockProvider,
type MockVariable,
} from '../__fixtures__/test-utils';
import type { Snap } from './messaging-signing-snap-requests';
import {
MESSAGE_SIGNING_SNAP,
Expand Down Expand Up @@ -83,16 +84,3 @@ describe('MESSAGE_SIGNING_SNAP.signMessage() tests', () => {
expect(mockRequest).toHaveBeenCalled();
});
});

/**
* Mock utility - creates a mock provider
* @returns mock provider
*/
function arrangeMockProvider() {
const mockRequest = jest.fn();
const mockProvider: Eip1193Provider = {
request: mockRequest,
};

return { mockProvider, mockRequest };
}
Loading