@solana-mobile/mobile-wallet-adapter-protocol 2.1.5 → 2.1.7
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.
- package/.DS_Store +0 -0
- package/.gitignore +2 -0
- package/README.md +69 -69
- package/android/.gitignore +14 -0
- package/android/build.gradle +2 -2
- package/lib/cjs/index.browser.js +249 -184
- package/lib/cjs/index.js +249 -184
- package/lib/cjs/index.native.js +8 -0
- package/lib/esm/index.browser.js +249 -184
- package/lib/esm/index.js +249 -184
- package/lib/types/index.browser.d.ts +10 -4
- package/lib/types/index.browser.d.ts.map +1 -1
- package/lib/types/index.d.ts +10 -4
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.native.d.ts +10 -4
- package/lib/types/index.native.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/__forks__/react-native/base64Utils.ts +1 -0
- package/src/__forks__/react-native/transact.ts +91 -0
- package/src/arrayBufferToBase64String.ts +10 -0
- package/src/associationPort.ts +19 -0
- package/src/base64Utils.ts +22 -0
- package/src/codegenSpec/NativeSolanaMobileWalletAdapter.ts +13 -0
- package/src/createHelloReq.ts +12 -0
- package/src/createMobileWalletProxy.ts +182 -0
- package/src/createSIWSMessage.ts +14 -0
- package/src/createSequenceNumberVector.ts +11 -0
- package/src/encryptedMessage.ts +60 -0
- package/src/errors.ts +101 -0
- package/src/generateAssociationKeypair.ts +10 -0
- package/src/generateECDHKeypair.ts +10 -0
- package/src/getAssociateAndroidIntentURL.ts +77 -0
- package/src/getJWS.ts +19 -0
- package/src/getStringWithURLUnsafeBase64CharactersReplaced.ts +11 -0
- package/src/index.ts +3 -0
- package/src/jsonRpcMessage.ts +38 -0
- package/src/parseHelloRsp.ts +46 -0
- package/src/parseSessionProps.ts +33 -0
- package/src/reflectorId.ts +31 -0
- package/src/startSession.ts +98 -0
- package/src/transact.ts +593 -0
- package/src/types.ts +201 -0
- package/tsconfig.cjs.json +7 -0
- package/tsconfig.json +8 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
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
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
|
+
}
|
package/src/index.ts
ADDED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { AssociationPort, getRandomAssociationPort } from './associationPort.js';
|
|
2
|
+
import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
|
|
3
|
+
import getAssociateAndroidIntentURL from './getAssociateAndroidIntentURL.js';
|
|
4
|
+
|
|
5
|
+
// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
|
|
6
|
+
const Browser = {
|
|
7
|
+
Firefox: 0,
|
|
8
|
+
Other: 1,
|
|
9
|
+
} as const;
|
|
10
|
+
type BrowserEnum = typeof Browser[keyof typeof Browser];
|
|
11
|
+
|
|
12
|
+
function assertUnreachable(x: never): never {
|
|
13
|
+
return x;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function getBrowser(): BrowserEnum {
|
|
17
|
+
return navigator.userAgent.indexOf('Firefox/') !== -1 ? Browser.Firefox : Browser.Other;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function getDetectionPromise() {
|
|
21
|
+
// Chrome and others silently fail if a custom protocol is not supported.
|
|
22
|
+
// For these, we wait to see if the browser is navigated away from in
|
|
23
|
+
// a reasonable amount of time (ie. the native wallet opened).
|
|
24
|
+
return new Promise<void>((resolve, reject) => {
|
|
25
|
+
function cleanup() {
|
|
26
|
+
clearTimeout(timeoutId);
|
|
27
|
+
window.removeEventListener('blur', handleBlur);
|
|
28
|
+
}
|
|
29
|
+
function handleBlur() {
|
|
30
|
+
cleanup();
|
|
31
|
+
resolve();
|
|
32
|
+
}
|
|
33
|
+
window.addEventListener('blur', handleBlur);
|
|
34
|
+
const timeoutId = setTimeout(() => {
|
|
35
|
+
cleanup();
|
|
36
|
+
reject();
|
|
37
|
+
}, 3000);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let _frame: HTMLIFrameElement | null = null;
|
|
42
|
+
function launchUrlThroughHiddenFrame(url: URL) {
|
|
43
|
+
if (_frame == null) {
|
|
44
|
+
_frame = document.createElement('iframe');
|
|
45
|
+
_frame.style.display = 'none';
|
|
46
|
+
document.body.appendChild(_frame);
|
|
47
|
+
}
|
|
48
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
49
|
+
_frame.contentWindow!.location.href = url.toString();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function launchAssociation(associationUrl: URL) {
|
|
53
|
+
if (associationUrl.protocol === 'https:') {
|
|
54
|
+
// The association URL is an Android 'App Link' or iOS 'Universal Link'.
|
|
55
|
+
// These are regular web URLs that are designed to launch an app if it
|
|
56
|
+
// is installed or load the actual target webpage if not.
|
|
57
|
+
window.location.assign(associationUrl);
|
|
58
|
+
} else {
|
|
59
|
+
// The association URL has a custom protocol (eg. `solana-wallet:`)
|
|
60
|
+
try {
|
|
61
|
+
const browser = getBrowser();
|
|
62
|
+
switch (browser) {
|
|
63
|
+
case Browser.Firefox:
|
|
64
|
+
// If a custom protocol is not supported in Firefox, it throws.
|
|
65
|
+
launchUrlThroughHiddenFrame(associationUrl);
|
|
66
|
+
// If we reached this line, it's supported.
|
|
67
|
+
break;
|
|
68
|
+
case Browser.Other: {
|
|
69
|
+
const detectionPromise = getDetectionPromise();
|
|
70
|
+
window.location.assign(associationUrl);
|
|
71
|
+
await detectionPromise;
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
default:
|
|
75
|
+
assertUnreachable(browser);
|
|
76
|
+
}
|
|
77
|
+
} catch (e) {
|
|
78
|
+
throw new SolanaMobileWalletAdapterError(
|
|
79
|
+
SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND,
|
|
80
|
+
'Found no installed wallet that supports the mobile wallet protocol.',
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function startSession(
|
|
87
|
+
associationPublicKey: CryptoKey,
|
|
88
|
+
associationURLBase?: string,
|
|
89
|
+
): Promise<AssociationPort> {
|
|
90
|
+
const randomAssociationPort = getRandomAssociationPort();
|
|
91
|
+
const associationUrl = await getAssociateAndroidIntentURL(
|
|
92
|
+
associationPublicKey,
|
|
93
|
+
randomAssociationPort,
|
|
94
|
+
associationURLBase,
|
|
95
|
+
);
|
|
96
|
+
await launchAssociation(associationUrl);
|
|
97
|
+
return randomAssociationPort;
|
|
98
|
+
}
|