@solana-mobile/mobile-wallet-adapter-protocol 2.2.2 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,182 +0,0 @@
1
- import { createSIWSMessageBase64 } from "./createSIWSMessage";
2
- import {
3
- AuthorizationResult,
4
- MobileWallet,
5
- ProtocolVersion,
6
- SignInPayload,
7
- SignInResult,
8
- SolanaCloneAuthorization,
9
- SolanaSignTransactions
10
- } from "./types";
11
- import type { IdentifierArray } from "@wallet-standard/core";
12
-
13
- /**
14
- * Creates a {@link MobileWallet} proxy that handles backwards compatibility and API to RPC conversion.
15
- *
16
- * @param protocolVersion the protocol version in use for this session/request
17
- * @param protocolRequestHandler callback function that handles sending the RPC request to the wallet endpoint.
18
- * @returns a {@link MobileWallet} proxy
19
- */
20
- export default function createMobileWalletProxy<
21
- TMethodName extends keyof MobileWallet,
22
- TReturn extends Awaited<ReturnType<MobileWallet[TMethodName]>>
23
- >(
24
- protocolVersion: ProtocolVersion,
25
- protocolRequestHandler: (method: string, params: Parameters<MobileWallet[TMethodName]>[0]) => Promise<any>
26
- ): MobileWallet {
27
- return new Proxy<MobileWallet>({} as MobileWallet, {
28
- get<TMethodName extends keyof MobileWallet>(target: MobileWallet, p: TMethodName) {
29
- // Wrapping a Proxy in a promise results in the Proxy being asked for a 'then' property so must
30
- // return null if 'then' is called on this proxy to let the 'resolve()' call know this is not a promise.
31
- // see: https://stackoverflow.com/a/53890904
32
- //@ts-ignore
33
- if (p === 'then') {
34
- return null;
35
- }
36
- if (target[p] == null) {
37
- target[p] = async function (inputParams: Parameters<MobileWallet[TMethodName]>[0]) {
38
- const { method, params } = handleMobileWalletRequest(p, inputParams, protocolVersion);
39
- const result = await protocolRequestHandler(method, params) as Awaited<ReturnType<MobileWallet[TMethodName]>>;
40
- // if the request tried to sign in but the wallet did not return a sign in result, fallback on message signing
41
- if (method === 'authorize' && (params as any).sign_in_payload && !(result as any).sign_in_result) {
42
- (result as any)['sign_in_result'] = await signInFallback(
43
- (params as Parameters<MobileWallet['authorize']>[0]).sign_in_payload as SignInPayload,
44
- result as Awaited<ReturnType<MobileWallet['authorize']>>,
45
- protocolRequestHandler
46
- );
47
- }
48
- return handleMobileWalletResponse(p, result, protocolVersion) as TReturn;
49
- } as MobileWallet[TMethodName];
50
- }
51
- return target[p];
52
- },
53
- defineProperty() {
54
- return false;
55
- },
56
- deleteProperty() {
57
- return false;
58
- },
59
- });
60
- };
61
-
62
- /**
63
- * Handles all {@link MobileWallet} API requests and determines the correct MWA RPC method and params to call.
64
- * This handles backwards compatibility, based on the provided @protocolVersion.
65
- *
66
- * @param methodName the name of {@link MobileWallet} method that was called
67
- * @param methodParams the parameters that were passed to the method
68
- * @param protocolVersion the protocol version in use for this session/request
69
- * @returns the RPC request method and params that should be sent to the wallet endpoint
70
- */
71
- function handleMobileWalletRequest<TMethodName extends keyof MobileWallet>(
72
- methodName: TMethodName,
73
- methodParams: Parameters<MobileWallet[TMethodName]>[0],
74
- protocolVersion: ProtocolVersion
75
- ) {
76
- let params = methodParams;
77
- let method: string = methodName
78
- .toString()
79
- .replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
80
- .toLowerCase();
81
- switch (methodName) {
82
- case 'authorize': {
83
- let { chain } = params as Parameters<MobileWallet['authorize']>[0];
84
- if (protocolVersion === 'legacy') {
85
- switch (chain) {
86
- case 'solana:testnet': { chain = 'testnet'; break; }
87
- case 'solana:devnet': { chain = 'devnet'; break; }
88
- case 'solana:mainnet': { chain = 'mainnet-beta'; break; }
89
- default: { chain = (params as any).cluster; }
90
- }
91
- (params as any).cluster = chain;
92
- } else {
93
- switch (chain) {
94
- case 'testnet':
95
- case 'devnet': { chain = `solana:${chain}`; break; }
96
- case 'mainnet-beta': { chain = 'solana:mainnet'; break; }
97
- }
98
- (params as Parameters<MobileWallet['authorize']>[0]).chain = chain;
99
- }
100
- }
101
- case 'reauthorize': {
102
- const { auth_token, identity } = params as Parameters<MobileWallet['authorize' | 'reauthorize']>[0];
103
- if (auth_token) {
104
- switch (protocolVersion) {
105
- case 'legacy': {
106
- method = 'reauthorize';
107
- params = { auth_token: auth_token, identity: identity };
108
- break;
109
- }
110
- default: {
111
- method = 'authorize';
112
- break;
113
- }
114
- }
115
- }
116
- break;
117
- }
118
- }
119
- return { method, params }
120
- };
121
-
122
- /**
123
- * Handles all {@link MobileWallet} API responses and modifies the response for backwards compatibility, if needed
124
- *
125
- * @param method the {@link MobileWallet} method that was called
126
- * @param response the original response that was returned by the method call
127
- * @param protocolVersion the protocol version in use for this session/request
128
- * @returns the possibly modified response
129
- */
130
- function handleMobileWalletResponse<TMethodName extends keyof MobileWallet>(
131
- method: TMethodName,
132
- response: Awaited<ReturnType<MobileWallet[TMethodName]>>,
133
- protocolVersion: ProtocolVersion
134
- ): Awaited<ReturnType<MobileWallet[TMethodName]>> {
135
- switch (method) {
136
- case 'getCapabilities': {
137
- const capabilities = response as Awaited<ReturnType<MobileWallet['getCapabilities']>>
138
- switch (protocolVersion) {
139
- case 'legacy': {
140
- const features: `${string}:${string}`[] = [ SolanaSignTransactions ];
141
- if (capabilities.supports_clone_authorization === true) {
142
- features.push(SolanaCloneAuthorization);
143
- }
144
- return {
145
- ...capabilities,
146
- features: features as IdentifierArray,
147
- } as Awaited<ReturnType<MobileWallet[TMethodName]>>;
148
- }
149
- case 'v1': {
150
- return {
151
- ...capabilities,
152
- supports_sign_and_send_transactions: true,
153
- supports_clone_authorization: capabilities.features.includes(SolanaCloneAuthorization)
154
- } as Awaited<ReturnType<MobileWallet[TMethodName]>>;
155
- }
156
- }
157
- }
158
- }
159
- return response;
160
- };
161
-
162
- async function signInFallback(
163
- signInPayload: SignInPayload,
164
- authorizationResult: Awaited<ReturnType<MobileWallet['authorize']>>,
165
- protocolRequestHandler: (method: string, params: Parameters<MobileWallet['signMessages']>[0]) => Promise<unknown>
166
- ) {
167
- const domain = signInPayload.domain ?? window.location.host;
168
- const address = (authorizationResult as AuthorizationResult).accounts[0].address;
169
- const siwsMessage = createSIWSMessageBase64({ ...signInPayload, domain, address })
170
- const signMessageResult = await (protocolRequestHandler('sign_messages',
171
- {
172
- addresses: [ address ],
173
- payloads: [ siwsMessage ]
174
- }
175
- ) as ReturnType<MobileWallet['signMessages']>);
176
- const signInResult: SignInResult = {
177
- address: address,
178
- signed_message: siwsMessage,
179
- signature: signMessageResult.signed_payloads[0].slice(siwsMessage.length)
180
- };
181
- return signInResult;
182
- }
@@ -1,14 +0,0 @@
1
- import {
2
- SolanaSignInInputWithRequiredFields,
3
- createSignInMessageText,
4
- } from '@solana/wallet-standard-util';
5
- import { SignInPayload } from './types';
6
- import { encode } from './base64Utils';
7
-
8
- export function createSIWSMessage(payload: SolanaSignInInputWithRequiredFields & SignInPayload): string {
9
- return createSignInMessageText(payload);
10
- }
11
-
12
- export function createSIWSMessageBase64(payload: SolanaSignInInputWithRequiredFields & SignInPayload): string {
13
- return encode(createSIWSMessage(payload));
14
- }
@@ -1,11 +0,0 @@
1
- export const SEQUENCE_NUMBER_BYTES = 4;
2
-
3
- export default function createSequenceNumberVector(sequenceNumber: number): Uint8Array {
4
- if (sequenceNumber >= 4294967296) {
5
- throw new Error('Outbound sequence number overflow. The maximum sequence number is 32-bytes.');
6
- }
7
- const byteArray = new ArrayBuffer(SEQUENCE_NUMBER_BYTES);
8
- const view = new DataView(byteArray);
9
- view.setUint32(0, sequenceNumber, /* littleEndian */ false);
10
- return new Uint8Array(byteArray);
11
- }
@@ -1,60 +0,0 @@
1
- import createSequenceNumberVector, { SEQUENCE_NUMBER_BYTES } from './createSequenceNumberVector.js';
2
- import { SharedSecret } from './parseHelloRsp.js';
3
-
4
- const INITIALIZATION_VECTOR_BYTES = 12;
5
- export const ENCODED_PUBLIC_KEY_LENGTH_BYTES = 65;
6
-
7
- export async function encryptMessage(
8
- plaintext: string,
9
- sequenceNumber: number,
10
- sharedSecret: SharedSecret,
11
- ) {
12
- const sequenceNumberVector = createSequenceNumberVector(sequenceNumber);
13
- const initializationVector = new Uint8Array(INITIALIZATION_VECTOR_BYTES);
14
- crypto.getRandomValues(initializationVector);
15
- const ciphertext = await crypto.subtle.encrypt(
16
- getAlgorithmParams(sequenceNumberVector, initializationVector),
17
- sharedSecret,
18
- new TextEncoder().encode(plaintext),
19
- );
20
- const response = new Uint8Array(
21
- sequenceNumberVector.byteLength + initializationVector.byteLength + ciphertext.byteLength,
22
- );
23
- response.set(new Uint8Array(sequenceNumberVector), 0);
24
- response.set(new Uint8Array(initializationVector), sequenceNumberVector.byteLength);
25
- response.set(new Uint8Array(ciphertext), sequenceNumberVector.byteLength + initializationVector.byteLength);
26
- return response;
27
- }
28
-
29
- export async function decryptMessage(message: ArrayBuffer, sharedSecret: SharedSecret) {
30
- const sequenceNumberVector = message.slice(0, SEQUENCE_NUMBER_BYTES);
31
- const initializationVector = message.slice(
32
- SEQUENCE_NUMBER_BYTES,
33
- SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES,
34
- );
35
- const ciphertext = message.slice(SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES);
36
- const plaintextBuffer = await crypto.subtle.decrypt(
37
- getAlgorithmParams(sequenceNumberVector, initializationVector),
38
- sharedSecret,
39
- ciphertext,
40
- );
41
- const plaintext = getUtf8Decoder().decode(plaintextBuffer);
42
- return plaintext
43
- }
44
-
45
- function getAlgorithmParams(sequenceNumber: ArrayBuffer, initializationVector: ArrayBuffer) {
46
- return {
47
- additionalData: sequenceNumber,
48
- iv: initializationVector,
49
- name: 'AES-GCM',
50
- tagLength: 128, // 16 byte tag => 128 bits
51
- };
52
- }
53
-
54
- let _utf8Decoder: TextDecoder | undefined;
55
- function getUtf8Decoder() {
56
- if (_utf8Decoder === undefined) {
57
- _utf8Decoder = new TextDecoder('utf-8');
58
- }
59
- return _utf8Decoder;
60
- }
package/src/errors.ts DELETED
@@ -1,101 +0,0 @@
1
- // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
2
- export const SolanaMobileWalletAdapterErrorCode = {
3
- ERROR_ASSOCIATION_PORT_OUT_OF_RANGE: 'ERROR_ASSOCIATION_PORT_OUT_OF_RANGE',
4
- ERROR_REFLECTOR_ID_OUT_OF_RANGE: 'ERROR_REFLECTOR_ID_OUT_OF_RANGE',
5
- ERROR_FORBIDDEN_WALLET_BASE_URL: 'ERROR_FORBIDDEN_WALLET_BASE_URL',
6
- ERROR_SECURE_CONTEXT_REQUIRED: 'ERROR_SECURE_CONTEXT_REQUIRED',
7
- ERROR_SESSION_CLOSED: 'ERROR_SESSION_CLOSED',
8
- ERROR_SESSION_TIMEOUT: 'ERROR_SESSION_TIMEOUT',
9
- ERROR_WALLET_NOT_FOUND: 'ERROR_WALLET_NOT_FOUND',
10
- ERROR_INVALID_PROTOCOL_VERSION: 'ERROR_INVALID_PROTOCOL_VERSION',
11
- ERROR_BROWSER_NOT_SUPPORTED: 'ERROR_BROWSER_NOT_SUPPORTED',
12
- } as const;
13
- type SolanaMobileWalletAdapterErrorCodeEnum =
14
- typeof SolanaMobileWalletAdapterErrorCode[keyof typeof SolanaMobileWalletAdapterErrorCode];
15
-
16
- type ErrorDataTypeMap = {
17
- [SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE]: {
18
- port: number;
19
- };
20
- [SolanaMobileWalletAdapterErrorCode.ERROR_REFLECTOR_ID_OUT_OF_RANGE]: {
21
- id: number;
22
- };
23
- [SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL]: undefined;
24
- [SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED]: undefined;
25
- [SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED]: {
26
- closeEvent: CloseEvent;
27
- };
28
- [SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT]: undefined;
29
- [SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND]: undefined;
30
- [SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION]: undefined;
31
- [SolanaMobileWalletAdapterErrorCode.ERROR_BROWSER_NOT_SUPPORTED]: undefined;
32
- };
33
-
34
- export class SolanaMobileWalletAdapterError<TErrorCode extends SolanaMobileWalletAdapterErrorCodeEnum> extends Error {
35
- data: ErrorDataTypeMap[TErrorCode] | undefined;
36
- code: TErrorCode;
37
- constructor(
38
- ...args: ErrorDataTypeMap[TErrorCode] extends Record<string, unknown>
39
- ? [code: TErrorCode, message: string, data: ErrorDataTypeMap[TErrorCode]]
40
- : [code: TErrorCode, message: string]
41
- ) {
42
- const [code, message, data] = args;
43
- super(message);
44
- this.code = code;
45
- this.data = data;
46
- this.name = 'SolanaMobileWalletAdapterError';
47
- }
48
- }
49
-
50
- type JSONRPCErrorCode = number;
51
-
52
- // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
53
- export const SolanaMobileWalletAdapterProtocolErrorCode = {
54
- // Keep these in sync with `mobilewalletadapter/common/ProtocolContract.java`.
55
- ERROR_AUTHORIZATION_FAILED: -1,
56
- ERROR_INVALID_PAYLOADS: -2,
57
- ERROR_NOT_SIGNED: -3,
58
- ERROR_NOT_SUBMITTED: -4,
59
- ERROR_TOO_MANY_PAYLOADS: -5,
60
- ERROR_ATTEST_ORIGIN_ANDROID: -100,
61
- } as const;
62
- type SolanaMobileWalletAdapterProtocolErrorCodeEnum =
63
- typeof SolanaMobileWalletAdapterProtocolErrorCode[keyof typeof SolanaMobileWalletAdapterProtocolErrorCode];
64
-
65
- type ProtocolErrorDataTypeMap = {
66
- [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_AUTHORIZATION_FAILED]: undefined;
67
- [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_INVALID_PAYLOADS]: undefined;
68
- [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_NOT_SIGNED]: undefined;
69
- [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_NOT_SUBMITTED]: undefined;
70
- [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_TOO_MANY_PAYLOADS]: undefined;
71
- [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_ATTEST_ORIGIN_ANDROID]: {
72
- attest_origin_uri: string;
73
- challenge: string;
74
- context: string;
75
- };
76
- };
77
-
78
- export class SolanaMobileWalletAdapterProtocolError<
79
- TErrorCode extends SolanaMobileWalletAdapterProtocolErrorCodeEnum,
80
- > extends Error {
81
- data: ProtocolErrorDataTypeMap[TErrorCode] | undefined;
82
- code: TErrorCode | JSONRPCErrorCode;
83
- jsonRpcMessageId: number;
84
- constructor(
85
- ...args: ProtocolErrorDataTypeMap[TErrorCode] extends Record<string, unknown>
86
- ? [
87
- jsonRpcMessageId: number,
88
- code: TErrorCode | JSONRPCErrorCode,
89
- message: string,
90
- data: ProtocolErrorDataTypeMap[TErrorCode],
91
- ]
92
- : [jsonRpcMessageId: number, code: TErrorCode | JSONRPCErrorCode, message: string]
93
- ) {
94
- const [jsonRpcMessageId, code, message, data] = args;
95
- super(message);
96
- this.code = code;
97
- this.data = data;
98
- this.jsonRpcMessageId = jsonRpcMessageId;
99
- this.name = 'SolanaMobileWalletAdapterProtocolError';
100
- }
101
- }
@@ -1,10 +0,0 @@
1
- export default async function generateAssociationKeypair(): Promise<CryptoKeyPair> {
2
- return await crypto.subtle.generateKey(
3
- {
4
- name: 'ECDSA',
5
- namedCurve: 'P-256',
6
- },
7
- false /* extractable */,
8
- ['sign'] /* keyUsages */,
9
- );
10
- }
@@ -1,10 +0,0 @@
1
- export default async function generateECDHKeypair(): Promise<CryptoKeyPair> {
2
- return await crypto.subtle.generateKey(
3
- {
4
- name: 'ECDH',
5
- namedCurve: 'P-256',
6
- },
7
- false /* extractable */,
8
- ['deriveKey', 'deriveBits'] /* keyUsages */,
9
- );
10
- }
@@ -1,77 +0,0 @@
1
- import arrayBufferToBase64String from './arrayBufferToBase64String.js';
2
- import { assertAssociationPort } from './associationPort.js';
3
- import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
4
- import getStringWithURLUnsafeBase64CharactersReplaced from './getStringWithURLUnsafeBase64CharactersReplaced.js';
5
- import { ProtocolVersion } from './types.js';
6
- import { fromUint8Array } from './base64Utils.js';
7
-
8
- const INTENT_NAME = 'solana-wallet';
9
-
10
- function getPathParts(pathString: string) {
11
- return (
12
- pathString
13
- // Strip leading and trailing slashes
14
- .replace(/(^\/+|\/+$)/g, '')
15
- // Return an array of directories
16
- .split('/')
17
- );
18
- }
19
-
20
- function getIntentURL(methodPathname: string, intentUrlBase?: string) {
21
- let baseUrl: URL | null = null;
22
- if (intentUrlBase) {
23
- try {
24
- baseUrl = new URL(intentUrlBase);
25
- } catch {} // eslint-disable-line no-empty
26
- if (baseUrl?.protocol !== 'https:') {
27
- throw new SolanaMobileWalletAdapterError(
28
- SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,
29
- 'Base URLs supplied by wallets must be valid `https` URLs',
30
- );
31
- }
32
- }
33
- baseUrl ||= new URL(`${INTENT_NAME}:/`);
34
- const pathname = methodPathname.startsWith('/')
35
- ? // Method is an absolute path. Replace it wholesale.
36
- methodPathname
37
- : // Method is a relative path. Merge it with the existing one.
38
- [...getPathParts(baseUrl.pathname), ...getPathParts(methodPathname)].join('/');
39
- return new URL(pathname, baseUrl);
40
- }
41
-
42
- export default async function getAssociateAndroidIntentURL(
43
- associationPublicKey: CryptoKey,
44
- putativePort: number,
45
- associationURLBase?: string,
46
- protocolVersions: ProtocolVersion[] = ['v1'],
47
- ): Promise<URL> {
48
- const associationPort = assertAssociationPort(putativePort);
49
- const exportedKey = await crypto.subtle.exportKey('raw', associationPublicKey);
50
- const encodedKey = arrayBufferToBase64String(exportedKey);
51
- const url = getIntentURL('v1/associate/local', associationURLBase);
52
- url.searchParams.set('association', getStringWithURLUnsafeBase64CharactersReplaced(encodedKey));
53
- url.searchParams.set('port', `${associationPort}`);
54
- protocolVersions.forEach( (version) => {
55
- url.searchParams.set('v', version);
56
- })
57
- return url;
58
- }
59
-
60
- export async function getRemoteAssociateAndroidIntentURL(
61
- associationPublicKey: CryptoKey,
62
- hostAuthority: string,
63
- reflectorId: Uint8Array,
64
- associationURLBase?: string,
65
- protocolVersions: ProtocolVersion[] = ['v1'],
66
- ): Promise<URL> {
67
- const exportedKey = await crypto.subtle.exportKey('raw', associationPublicKey);
68
- const encodedKey = arrayBufferToBase64String(exportedKey);
69
- const url = getIntentURL('v1/associate/remote', associationURLBase);
70
- url.searchParams.set('association', getStringWithURLUnsafeBase64CharactersReplaced(encodedKey));
71
- url.searchParams.set('reflector', `${hostAuthority}`);
72
- url.searchParams.set('id', `${fromUint8Array(reflectorId, true)}`);
73
- protocolVersions.forEach( (version) => {
74
- url.searchParams.set('v', version);
75
- })
76
- return url;
77
- }
package/src/getJWS.ts DELETED
@@ -1,19 +0,0 @@
1
- import arrayBufferToBase64String from './arrayBufferToBase64String.js';
2
-
3
- export default async function getJWS(payload: string, privateKey: CryptoKey) {
4
- const header = { alg: 'ES256' };
5
- const headerEncoded = window.btoa(JSON.stringify(header));
6
- const payloadEncoded = window.btoa(payload);
7
- const message = `${headerEncoded}.${payloadEncoded}`;
8
- const signatureBuffer = await crypto.subtle.sign(
9
- {
10
- name: 'ECDSA',
11
- hash: 'SHA-256',
12
- },
13
- privateKey,
14
- new TextEncoder().encode(message),
15
- );
16
- const signature = arrayBufferToBase64String(signatureBuffer);
17
- const jws = `${message}.${signature}`;
18
- return jws;
19
- }
@@ -1,11 +0,0 @@
1
- export default function getStringWithURLUnsafeCharactersReplaced(unsafeBase64EncodedString: string): string {
2
- return unsafeBase64EncodedString.replace(
3
- /[/+=]/g,
4
- (m) =>
5
- ({
6
- '/': '_',
7
- '+': '-',
8
- '=': '.',
9
- }[m] as string),
10
- );
11
- }
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- export * from './errors.js';
2
- export * from './transact.js';
3
- export * from './types.js';
@@ -1,38 +0,0 @@
1
- import { decryptMessage, encryptMessage } from './encryptedMessage.js';
2
- import { SolanaMobileWalletAdapterProtocolError } from './errors.js';
3
- import { SharedSecret } from './parseHelloRsp.js';
4
-
5
- interface JSONRPCRequest<TParams> {
6
- id: number;
7
- jsonrpc: '2.0';
8
- method: string;
9
- params: TParams;
10
- }
11
-
12
- type JSONRPCResponse<TMessage> = {
13
- id: number;
14
- jsonrpc: '2.0';
15
- result: TMessage;
16
- };
17
-
18
- export async function encryptJsonRpcMessage<TParams>(
19
- jsonRpcMessage: JSONRPCRequest<TParams>,
20
- sharedSecret: SharedSecret,
21
- ) {
22
- const plaintext = JSON.stringify(jsonRpcMessage);
23
- const sequenceNumber = jsonRpcMessage.id;
24
- return encryptMessage(plaintext, sequenceNumber, sharedSecret);
25
- }
26
-
27
- export async function decryptJsonRpcMessage<TMessage>(message: ArrayBuffer, sharedSecret: SharedSecret) {
28
- const plaintext = await decryptMessage(message, sharedSecret);
29
- const jsonRpcMessage = JSON.parse(plaintext);
30
- if (Object.hasOwnProperty.call(jsonRpcMessage, 'error')) {
31
- throw new SolanaMobileWalletAdapterProtocolError<typeof jsonRpcMessage.error.code>(
32
- jsonRpcMessage.id,
33
- jsonRpcMessage.error.code,
34
- jsonRpcMessage.error.message,
35
- );
36
- }
37
- return jsonRpcMessage as JSONRPCResponse<TMessage>;
38
- }
@@ -1,46 +0,0 @@
1
- import { ENCODED_PUBLIC_KEY_LENGTH_BYTES } from "./encryptedMessage";
2
-
3
- /**
4
- * A secret agreed upon by the app and the wallet. Used as
5
- * a symmetric key to encrypt and decrypt messages over an
6
- * unsecured channel.
7
- */
8
- export type SharedSecret = CryptoKey;
9
-
10
- export default async function parseHelloRsp(
11
- payloadBuffer: ArrayBuffer, // The X9.62-encoded wallet endpoint ephemeral ECDH public keypoint.
12
- associationPublicKey: CryptoKey,
13
- ecdhPrivateKey: CryptoKey,
14
- ): Promise<SharedSecret> {
15
- const [associationPublicKeyBuffer, walletPublicKey] = await Promise.all([
16
- crypto.subtle.exportKey('raw', associationPublicKey),
17
- crypto.subtle.importKey(
18
- 'raw',
19
- payloadBuffer.slice(0, ENCODED_PUBLIC_KEY_LENGTH_BYTES),
20
- { name: 'ECDH', namedCurve: 'P-256' },
21
- false /* extractable */,
22
- [] /* keyUsages */,
23
- ),
24
- ]);
25
- const sharedSecret = await crypto.subtle.deriveBits({ name: 'ECDH', public: walletPublicKey }, ecdhPrivateKey, 256);
26
- const ecdhSecretKey = await crypto.subtle.importKey(
27
- 'raw',
28
- sharedSecret,
29
- 'HKDF',
30
- false /* extractable */,
31
- ['deriveKey'] /* keyUsages */,
32
- );
33
- const aesKeyMaterialVal = await crypto.subtle.deriveKey(
34
- {
35
- name: 'HKDF',
36
- hash: 'SHA-256',
37
- salt: new Uint8Array(associationPublicKeyBuffer),
38
- info: new Uint8Array(),
39
- },
40
- ecdhSecretKey,
41
- { name: 'AES-GCM', length: 128 },
42
- false /* extractable */,
43
- ['encrypt', 'decrypt'],
44
- );
45
- return aesKeyMaterialVal as SharedSecret;
46
- }
@@ -1,33 +0,0 @@
1
- import { decryptMessage } from "./encryptedMessage";
2
- import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from "./errors";
3
- import { SharedSecret } from "./parseHelloRsp";
4
- import { ProtocolVersion, SessionProperties } from "./types";
5
-
6
- export default async function parseSessionProps(
7
- message: ArrayBuffer,
8
- sharedSecret: SharedSecret
9
- ): Promise<SessionProperties> {
10
- const plaintext = await decryptMessage(message, sharedSecret);
11
- const jsonProperties = JSON.parse(plaintext);
12
- let protocolVersion: ProtocolVersion = 'legacy';
13
- if (Object.hasOwnProperty.call(jsonProperties, 'v')) {
14
- switch (jsonProperties.v) {
15
- case 1:
16
- case '1':
17
- case 'v1':
18
- protocolVersion = 'v1'
19
- break;
20
- case 'legacy':
21
- protocolVersion = 'legacy'
22
- break;
23
- default:
24
- throw new SolanaMobileWalletAdapterError(
25
- SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION,
26
- `Unknown/unsupported protocol version: ${jsonProperties.v}`
27
- );
28
- }
29
- }
30
- return <SessionProperties>({
31
- protocol_version: protocolVersion
32
- })
33
- }
@@ -1,31 +0,0 @@
1
- import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
2
-
3
- declare const tag: unique symbol;
4
- export type ReflectorId = number & { readonly [tag]: 'ReflectorId' };
5
-
6
- export function getRandomReflectorId(): ReflectorId {
7
- return assertReflectorId(getRandomInt(0, 9007199254740991)); // 0 < id < 2^53 - 1
8
- }
9
-
10
- function getRandomInt(min: number, max: number) {
11
- const randomBuffer = new Uint32Array(1);
12
-
13
- window.crypto.getRandomValues(randomBuffer);
14
-
15
- let randomNumber = randomBuffer[0] / (0xffffffff + 1);
16
-
17
- min = Math.ceil(min);
18
- max = Math.floor(max);
19
- return Math.floor(randomNumber * (max - min + 1)) + min;
20
- }
21
-
22
- export function assertReflectorId(id: number): ReflectorId {
23
- if (id < 0 || id > 9007199254740991) { // 0 < id < 2^53 - 1
24
- throw new SolanaMobileWalletAdapterError(
25
- SolanaMobileWalletAdapterErrorCode.ERROR_REFLECTOR_ID_OUT_OF_RANGE,
26
- `Association port number must be between 49152 and 65535. ${id} given.`,
27
- { id },
28
- );
29
- }
30
- return id as ReflectorId;
31
- }