@solana-mobile/mobile-wallet-adapter-protocol 2.0.0 → 2.0.2

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.
Files changed (70) hide show
  1. package/.gitignore +2 -0
  2. package/README.md +69 -62
  3. package/android/.gitignore +14 -0
  4. package/android/.gradle/4.4.1/fileChanges/last-build.bin +0 -0
  5. package/android/.gradle/4.4.1/fileHashes/fileHashes.bin +0 -0
  6. package/android/.gradle/4.4.1/fileHashes/fileHashes.lock +0 -0
  7. package/android/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock +0 -0
  8. package/android/.gradle/7.1/dependencies-accessors/gc.properties +0 -0
  9. package/android/.gradle/7.1/fileChanges/last-build.bin +0 -0
  10. package/android/.gradle/7.1/fileHashes/fileHashes.lock +0 -0
  11. package/android/.gradle/7.1/gc.properties +0 -0
  12. package/android/.gradle/7.5/checksums/checksums.lock +0 -0
  13. package/android/.gradle/7.5/dependencies-accessors/dependencies-accessors.lock +0 -0
  14. package/android/.gradle/7.5/dependencies-accessors/gc.properties +0 -0
  15. package/android/.gradle/7.5/fileChanges/last-build.bin +0 -0
  16. package/android/.gradle/7.5/fileHashes/fileHashes.lock +0 -0
  17. package/android/.gradle/7.5/gc.properties +0 -0
  18. package/android/.gradle/7.5.1/checksums/checksums.lock +0 -0
  19. package/android/.gradle/7.5.1/checksums/sha1-checksums.bin +0 -0
  20. package/android/.gradle/7.5.1/dependencies-accessors/dependencies-accessors.lock +0 -0
  21. package/android/.gradle/7.5.1/dependencies-accessors/gc.properties +0 -0
  22. package/android/.gradle/7.5.1/fileChanges/last-build.bin +0 -0
  23. package/android/.gradle/7.5.1/fileHashes/fileHashes.lock +0 -0
  24. package/android/.gradle/7.5.1/gc.properties +0 -0
  25. package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
  26. package/android/.gradle/buildOutputCleanup/cache.properties +2 -0
  27. package/android/.gradle/checksums/checksums.lock +0 -0
  28. package/android/.gradle/checksums/md5-checksums.bin +0 -0
  29. package/android/.gradle/checksums/sha1-checksums.bin +0 -0
  30. package/android/.gradle/vcs-1/gc.properties +0 -0
  31. package/android/build.gradle +146 -146
  32. package/android/gradle/wrapper/gradle-wrapper.properties +5 -5
  33. package/android/src/main/java/com/solanamobile/mobilewalletadapter/reactnative/SolanaMobileWalletAdapterModule.kt +178 -139
  34. package/lib/cjs/index.browser.js +290 -81
  35. package/lib/cjs/index.js +290 -81
  36. package/lib/cjs/index.native.js +180 -28
  37. package/lib/esm/index.browser.js +288 -82
  38. package/lib/esm/index.js +288 -82
  39. package/lib/types/index.browser.d.ts +68 -5
  40. package/lib/types/index.browser.d.ts.map +1 -1
  41. package/lib/types/index.d.ts +68 -5
  42. package/lib/types/index.d.ts.map +1 -1
  43. package/lib/types/index.native.d.ts +68 -5
  44. package/lib/types/index.native.d.ts.map +1 -1
  45. package/package.json +56 -51
  46. package/src/__forks__/react-native/base64Utils.ts +1 -0
  47. package/src/__forks__/react-native/transact.ts +92 -0
  48. package/src/arrayBufferToBase64String.ts +10 -0
  49. package/src/associationPort.ts +19 -0
  50. package/src/base64Utils.ts +3 -0
  51. package/src/createHelloReq.ts +12 -0
  52. package/src/createMobileWalletProxy.ts +175 -0
  53. package/src/createSIWSMessage.ts +14 -0
  54. package/src/createSequenceNumberVector.ts +11 -0
  55. package/src/encryptedMessage.ts +60 -0
  56. package/src/errors.ts +95 -0
  57. package/src/generateAssociationKeypair.ts +10 -0
  58. package/src/generateECDHKeypair.ts +10 -0
  59. package/src/getAssociateAndroidIntentURL.ts +57 -0
  60. package/src/getJWS.ts +19 -0
  61. package/src/getStringWithURLUnsafeBase64CharactersReplaced.ts +11 -0
  62. package/src/index.ts +3 -0
  63. package/src/jsonRpcMessage.ts +38 -0
  64. package/src/parseHelloRsp.ts +46 -0
  65. package/src/parseSessionProps.ts +33 -0
  66. package/src/startSession.ts +94 -0
  67. package/src/transact.ts +266 -0
  68. package/src/types.ts +181 -0
  69. package/tsconfig.cjs.json +7 -0
  70. package/tsconfig.json +8 -0
@@ -0,0 +1,175 @@
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
+ if (target[p] == null) {
30
+ target[p] = async function (inputParams: Parameters<MobileWallet[TMethodName]>[0]) {
31
+ const { method, params } = handleMobileWalletRequest(p, inputParams, protocolVersion);
32
+ const result = await protocolRequestHandler(method, params) as Awaited<ReturnType<MobileWallet[TMethodName]>>;
33
+ // if the request tried to sign in but the wallet did not return a sign in result, fallback on message signing
34
+ if (method === 'authorize' && (params as any).sign_in_payload && !(result as any).sign_in_result) {
35
+ (result as any)['sign_in_result'] = await signInFallback(
36
+ (params as Parameters<MobileWallet['authorize']>[0]).sign_in_payload as SignInPayload,
37
+ result as Awaited<ReturnType<MobileWallet['authorize']>>,
38
+ protocolRequestHandler
39
+ );
40
+ }
41
+ return handleMobileWalletResponse(p, result, protocolVersion) as TReturn;
42
+ } as MobileWallet[TMethodName];
43
+ }
44
+ return target[p];
45
+ },
46
+ defineProperty() {
47
+ return false;
48
+ },
49
+ deleteProperty() {
50
+ return false;
51
+ },
52
+ });
53
+ };
54
+
55
+ /**
56
+ * Handles all {@link MobileWallet} API requests and determines the correct MWA RPC method and params to call.
57
+ * This handles backwards compatibility, based on the provided @protocolVersion.
58
+ *
59
+ * @param methodName the name of {@link MobileWallet} method that was called
60
+ * @param methodParams the parameters that were passed to the method
61
+ * @param protocolVersion the protocol version in use for this session/request
62
+ * @returns the RPC request method and params that should be sent to the wallet endpoint
63
+ */
64
+ function handleMobileWalletRequest<TMethodName extends keyof MobileWallet>(
65
+ methodName: TMethodName,
66
+ methodParams: Parameters<MobileWallet[TMethodName]>[0],
67
+ protocolVersion: ProtocolVersion
68
+ ) {
69
+ let params = methodParams;
70
+ let method: string = methodName
71
+ .toString()
72
+ .replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
73
+ .toLowerCase();
74
+ switch (methodName) {
75
+ case 'authorize': {
76
+ let { chain } = params as Parameters<MobileWallet['authorize']>[0];
77
+ if (protocolVersion === 'legacy') {
78
+ switch (chain) {
79
+ case 'solana:testnet': { chain = 'testnet'; break; }
80
+ case 'solana:devnet': { chain = 'devnet'; break; }
81
+ case 'solana:mainnet': { chain = 'mainnet-beta'; break; }
82
+ default: { chain = (params as any).cluster; }
83
+ }
84
+ (params as any).cluster = chain;
85
+ } else {
86
+ switch (chain) {
87
+ case 'testnet':
88
+ case 'devnet': { chain = `solana:${chain}`; break; }
89
+ case 'mainnet-beta': { chain = 'solana:mainnet'; break; }
90
+ }
91
+ (params as Parameters<MobileWallet['authorize']>[0]).chain = chain;
92
+ }
93
+ }
94
+ case 'reauthorize': {
95
+ const { auth_token, identity } = params as Parameters<MobileWallet['authorize' | 'reauthorize']>[0];
96
+ if (auth_token) {
97
+ switch (protocolVersion) {
98
+ case 'legacy': {
99
+ method = 'reauthorize';
100
+ params = { auth_token: auth_token, identity: identity };
101
+ break;
102
+ }
103
+ default: {
104
+ method = 'authorize';
105
+ break;
106
+ }
107
+ }
108
+ }
109
+ break;
110
+ }
111
+ }
112
+ return { method, params }
113
+ };
114
+
115
+ /**
116
+ * Handles all {@link MobileWallet} API responses and modifies the response for backwards compatibility, if needed
117
+ *
118
+ * @param method the {@link MobileWallet} method that was called
119
+ * @param response the original response that was returned by the method call
120
+ * @param protocolVersion the protocol version in use for this session/request
121
+ * @returns the possibly modified response
122
+ */
123
+ function handleMobileWalletResponse<TMethodName extends keyof MobileWallet>(
124
+ method: TMethodName,
125
+ response: Awaited<ReturnType<MobileWallet[TMethodName]>>,
126
+ protocolVersion: ProtocolVersion
127
+ ): Awaited<ReturnType<MobileWallet[TMethodName]>> {
128
+ switch (method) {
129
+ case 'getCapabilities': {
130
+ const capabilities = response as Awaited<ReturnType<MobileWallet['getCapabilities']>>
131
+ switch (protocolVersion) {
132
+ case 'legacy': {
133
+ const features: `${string}:${string}`[] = [ SolanaSignTransactions ];
134
+ if (capabilities.supports_clone_authorization === true) {
135
+ features.push(SolanaCloneAuthorization);
136
+ }
137
+ return {
138
+ ...capabilities,
139
+ features: features as IdentifierArray,
140
+ } as Awaited<ReturnType<MobileWallet[TMethodName]>>;
141
+ }
142
+ case 'v1': {
143
+ return {
144
+ ...capabilities,
145
+ supports_sign_and_send_transactions: true,
146
+ supports_clone_authorization: capabilities.features.includes(SolanaCloneAuthorization)
147
+ } as Awaited<ReturnType<MobileWallet[TMethodName]>>;
148
+ }
149
+ }
150
+ }
151
+ }
152
+ return response;
153
+ };
154
+
155
+ async function signInFallback(
156
+ signInPayload: SignInPayload,
157
+ authorizationResult: Awaited<ReturnType<MobileWallet['authorize']>>,
158
+ protocolRequestHandler: (method: string, params: Parameters<MobileWallet['signMessages']>[0]) => Promise<unknown>
159
+ ) {
160
+ const domain = signInPayload.domain ?? window.location.host;
161
+ const address = (authorizationResult as AuthorizationResult).accounts[0].address;
162
+ const siwsMessage = createSIWSMessageBase64({ ...signInPayload, domain, address })
163
+ const signMessageResult = await (protocolRequestHandler('sign_messages',
164
+ {
165
+ addresses: [ address ],
166
+ payloads: [ siwsMessage ]
167
+ }
168
+ ) as ReturnType<MobileWallet['signMessages']>);
169
+ const signInResult: SignInResult = {
170
+ address: address,
171
+ signed_message: siwsMessage,
172
+ signature: signMessageResult.signed_payloads[0].slice(siwsMessage.length)
173
+ };
174
+ return signInResult;
175
+ }
@@ -0,0 +1,14 @@
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
+ }
@@ -0,0 +1,11 @@
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
+ }
@@ -0,0 +1,60 @@
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 ADDED
@@ -0,0 +1,95 @@
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_FORBIDDEN_WALLET_BASE_URL: 'ERROR_FORBIDDEN_WALLET_BASE_URL',
5
+ ERROR_SECURE_CONTEXT_REQUIRED: 'ERROR_SECURE_CONTEXT_REQUIRED',
6
+ ERROR_SESSION_CLOSED: 'ERROR_SESSION_CLOSED',
7
+ ERROR_SESSION_TIMEOUT: 'ERROR_SESSION_TIMEOUT',
8
+ ERROR_WALLET_NOT_FOUND: 'ERROR_WALLET_NOT_FOUND',
9
+ ERROR_INVALID_PROTOCOL_VERSION: 'ERROR_INVALID_PROTOCOL_VERSION',
10
+ } as const;
11
+ type SolanaMobileWalletAdapterErrorCodeEnum =
12
+ typeof SolanaMobileWalletAdapterErrorCode[keyof typeof SolanaMobileWalletAdapterErrorCode];
13
+
14
+ type ErrorDataTypeMap = {
15
+ [SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE]: {
16
+ port: number;
17
+ };
18
+ [SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL]: undefined;
19
+ [SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED]: undefined;
20
+ [SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED]: {
21
+ closeEvent: CloseEvent;
22
+ };
23
+ [SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT]: undefined;
24
+ [SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND]: undefined;
25
+ [SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION]: undefined;
26
+ };
27
+
28
+ export class SolanaMobileWalletAdapterError<TErrorCode extends SolanaMobileWalletAdapterErrorCodeEnum> extends Error {
29
+ data: ErrorDataTypeMap[TErrorCode] | undefined;
30
+ code: TErrorCode;
31
+ constructor(
32
+ ...args: ErrorDataTypeMap[TErrorCode] extends Record<string, unknown>
33
+ ? [code: TErrorCode, message: string, data: ErrorDataTypeMap[TErrorCode]]
34
+ : [code: TErrorCode, message: string]
35
+ ) {
36
+ const [code, message, data] = args;
37
+ super(message);
38
+ this.code = code;
39
+ this.data = data;
40
+ this.name = 'SolanaMobileWalletAdapterError';
41
+ }
42
+ }
43
+
44
+ type JSONRPCErrorCode = number;
45
+
46
+ // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
47
+ export const SolanaMobileWalletAdapterProtocolErrorCode = {
48
+ // Keep these in sync with `mobilewalletadapter/common/ProtocolContract.java`.
49
+ ERROR_AUTHORIZATION_FAILED: -1,
50
+ ERROR_INVALID_PAYLOADS: -2,
51
+ ERROR_NOT_SIGNED: -3,
52
+ ERROR_NOT_SUBMITTED: -4,
53
+ ERROR_TOO_MANY_PAYLOADS: -5,
54
+ ERROR_ATTEST_ORIGIN_ANDROID: -100,
55
+ } as const;
56
+ type SolanaMobileWalletAdapterProtocolErrorCodeEnum =
57
+ typeof SolanaMobileWalletAdapterProtocolErrorCode[keyof typeof SolanaMobileWalletAdapterProtocolErrorCode];
58
+
59
+ type ProtocolErrorDataTypeMap = {
60
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_AUTHORIZATION_FAILED]: undefined;
61
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_INVALID_PAYLOADS]: undefined;
62
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_NOT_SIGNED]: undefined;
63
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_NOT_SUBMITTED]: undefined;
64
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_TOO_MANY_PAYLOADS]: undefined;
65
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_ATTEST_ORIGIN_ANDROID]: {
66
+ attest_origin_uri: string;
67
+ challenge: string;
68
+ context: string;
69
+ };
70
+ };
71
+
72
+ export class SolanaMobileWalletAdapterProtocolError<
73
+ TErrorCode extends SolanaMobileWalletAdapterProtocolErrorCodeEnum,
74
+ > extends Error {
75
+ data: ProtocolErrorDataTypeMap[TErrorCode] | undefined;
76
+ code: TErrorCode | JSONRPCErrorCode;
77
+ jsonRpcMessageId: number;
78
+ constructor(
79
+ ...args: ProtocolErrorDataTypeMap[TErrorCode] extends Record<string, unknown>
80
+ ? [
81
+ jsonRpcMessageId: number,
82
+ code: TErrorCode | JSONRPCErrorCode,
83
+ message: string,
84
+ data: ProtocolErrorDataTypeMap[TErrorCode],
85
+ ]
86
+ : [jsonRpcMessageId: number, code: TErrorCode | JSONRPCErrorCode, message: string]
87
+ ) {
88
+ const [jsonRpcMessageId, code, message, data] = args;
89
+ super(message);
90
+ this.code = code;
91
+ this.data = data;
92
+ this.jsonRpcMessageId = jsonRpcMessageId;
93
+ this.name = 'SolanaMobileWalletAdapterProtocolError';
94
+ }
95
+ }
@@ -0,0 +1,10 @@
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
+ }
@@ -0,0 +1,10 @@
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
+ }
@@ -0,0 +1,57 @@
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
+
7
+ const INTENT_NAME = 'solana-wallet';
8
+
9
+ function getPathParts(pathString: string) {
10
+ return (
11
+ pathString
12
+ // Strip leading and trailing slashes
13
+ .replace(/(^\/+|\/+$)/g, '')
14
+ // Return an array of directories
15
+ .split('/')
16
+ );
17
+ }
18
+
19
+ function getIntentURL(methodPathname: string, intentUrlBase?: string) {
20
+ let baseUrl: URL | null = null;
21
+ if (intentUrlBase) {
22
+ try {
23
+ baseUrl = new URL(intentUrlBase);
24
+ } catch {} // eslint-disable-line no-empty
25
+ if (baseUrl?.protocol !== 'https:') {
26
+ throw new SolanaMobileWalletAdapterError(
27
+ SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,
28
+ 'Base URLs supplied by wallets must be valid `https` URLs',
29
+ );
30
+ }
31
+ }
32
+ baseUrl ||= new URL(`${INTENT_NAME}:/`);
33
+ const pathname = methodPathname.startsWith('/')
34
+ ? // Method is an absolute path. Replace it wholesale.
35
+ methodPathname
36
+ : // Method is a relative path. Merge it with the existing one.
37
+ [...getPathParts(baseUrl.pathname), ...getPathParts(methodPathname)].join('/');
38
+ return new URL(pathname, baseUrl);
39
+ }
40
+
41
+ export default async function getAssociateAndroidIntentURL(
42
+ associationPublicKey: CryptoKey,
43
+ putativePort: number,
44
+ associationURLBase?: string,
45
+ protocolVersions: ProtocolVersion[] = ['v1'],
46
+ ): Promise<URL> {
47
+ const associationPort = assertAssociationPort(putativePort);
48
+ const exportedKey = await crypto.subtle.exportKey('raw', associationPublicKey);
49
+ const encodedKey = arrayBufferToBase64String(exportedKey);
50
+ const url = getIntentURL('v1/associate/local', associationURLBase);
51
+ url.searchParams.set('association', getStringWithURLUnsafeBase64CharactersReplaced(encodedKey));
52
+ url.searchParams.set('port', `${associationPort}`);
53
+ protocolVersions.forEach( (version) => {
54
+ url.searchParams.set('v', version);
55
+ })
56
+ return url;
57
+ }
package/src/getJWS.ts ADDED
@@ -0,0 +1,19 @@
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
+ }
@@ -0,0 +1,11 @@
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 ADDED
@@ -0,0 +1,3 @@
1
+ export * from './errors.js';
2
+ export * from './transact.js';
3
+ export * from './types.js';
@@ -0,0 +1,38 @@
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
+ }
@@ -0,0 +1,46 @@
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
+ }
@@ -0,0 +1,33 @@
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
+ }