All files / src/transports native.ts

73.5% Statements 86/117
73.84% Branches 48/65
64.7% Functions 11/17
73.87% Lines 82/111

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387175x                                 1x                                 1x   1x 1x       1x 73x                 23x       23x   23x                         23x 23x             23x 9x       1x           23x   23x                 23x         23x   9x           24x       2x       9x       23x     23x 23x                                                                                           1x 1x       1x 1x                   9x       9x   9x 9x 9x   9x   9x   9x   9x     9x   9x 9x 9x 9x 9x     9x                                               9x                                                         9x           9x   9x 9x   9x                           9x         9x 1x                 9x 9x 7x 7x 7x                 7x   7x   4x 3x 3x         3x       2x     1x   1x 1x 1x 1x     8x   2x 2x 2x 2x           2x       2x 2x         2x                         1x  
import {send} from '@greymass/buoy'
import {
    CallbackPayload,
    Cancelable,
    Checksum256,
    LoginContext,
    PermissionLevel,
    PrivateKey,
    PromptElement,
    PromptResponse,
    PublicKey,
    ResolvedSigningRequest,
    Serializer,
    TransactContext,
    WalletPluginData,
    WalletPluginLoginResponse,
    WalletPluginSignResponse,
} from '@wharfkit/session'
import {
    clearTransactionHandoff,
    extractSignaturesFromCallback,
    generateReturnUrl,
    isAppleHandheld,
    isCallback,
    isKnownMobile,
    isSamePageReturn,
    LinkInfo,
    sealMessage,
    setTransactionCallback,
    storeTransactionHandoff,
    TransactionHandoff,
    verifyLoginCallbackResponse,
    waitForCallback,
    waitForPageReturn,
} from '@wharfkit/protocol-esr'
 
import {AnchorRequestCancelledError} from './errors'
import {switchButton} from './prompt'
import {IdentityRequestBundle, Translator, TransportOptions, WebFallback} from './types'
 
/** Drives the native Anchor apps over an `esr:` deep link, a QR code, and buoy. */
export class NativeTransport {
    constructor(private options: TransportOptions) {}
 
    async login(
        data: WalletPluginData,
        context: LoginContext,
        bundle: IdentityRequestBundle,
        t: Translator,
        fallback?: WebFallback
    ): Promise<WalletPluginLoginResponse> {
        Iif (!context.ui) {
            throw new Error('No UI available')
        }
 
        const {callback, request, sameDeviceRequest, requestKey, privateKey} = bundle
 
        const elements: PromptElement[] = [
            {
                type: 'link',
                label: t('login.link', {default: 'Launch Anchor'}),
                data: {
                    href: sameDeviceRequest.encode(true, false, 'esr:'),
                    label: t('login.link', {default: 'Launch Anchor'}),
                    variant: 'primary',
                },
            },
        ]
 
        // If we know this is NOT a mobile device, show the QR code
        if (!isKnownMobile()) {
            elements.unshift({
                type: 'qr',
                data: request.encode(true, false, 'esr:'),
            })
        }
 
        // An explicitly routed login carries the correction path from the start.
        if (fallback?.immediate) {
            elements.push(
                switchButton(
                    t('mode.switch.to_web', {default: 'Use Anchor in this browser instead'}),
                    'text',
                    () => fallback.onSelect()
                )
            )
        }
 
        // Automatically try to open the link
        window.location.href = sameDeviceRequest.encode(true, false, 'esr:')
 
        const promptResponse = context.ui.prompt({
            title: t('login.title', {default: 'Connect with Anchor'}),
            body: t('login.body', {
                default:
                    'Scan with Anchor on your mobile device or click the button below to open on this device.',
            }),
            elements,
        })
 
        promptResponse.catch(() => {
            // eslint-disable-next-line no-console
            console.info('Modal closed')
        })
 
        const fallbackTimer = fallback
            ? setTimeout(() => {
                  const offer = context.ui!.prompt({
                      title: t('login.title', {default: 'Connect with Anchor'}),
                      body: t('fallback.body', {
                          default: "Don't have the app?",
                      }),
                      elements: [
                          ...elements.filter((element) => element.type !== 'button'),
                          switchButton(
                              t('fallback.label', {default: 'Continue in this browser instead'}),
                              'secondary',
                              () => fallback.onSelect()
                          ),
                      ],
                  })
                  offer.catch(() => undefined)
              }, fallback.delayMs)
            : undefined
 
        const cancelledMessage = t('error.cancelled', {
            default: 'The request was cancelled from Anchor.',
        })
        try {
            const callbackResponse: CallbackPayload = await (
                this.options.waitForCallback ?? waitForCallback
            )(callback, this.options.buoyWs, t)
            verifyLoginCallbackResponse(callbackResponse, context)
 
            Iif (!callbackResponse.cid || !callbackResponse.sa || !callbackResponse.sp) {
                throw new Error('Invalid callback response')
            }
 
            Iif (
                callbackResponse.link_ch &&
                callbackResponse.link_key &&
                callbackResponse.link_name
            ) {
                data.requestKey = requestKey
                data.privateKey = privateKey
                data.signerKey = PublicKey.from(callbackResponse.link_key)
                data.channelUrl = callbackResponse.link_ch
                data.channelName = callbackResponse.link_name
 
                try {
                    Iif (callbackResponse.link_meta) {
                        const metadata = JSON.parse(callbackResponse.link_meta)
                        data.sameDevice = metadata.sameDevice
                        data.launchUrl = metadata.launchUrl
                        data.triggerUrl = metadata.triggerUrl
                    }
                } catch {
                    // link_meta is advisory; a malformed value must not fail the login
                }
            }
 
            const resolvedResponse = await ResolvedSigningRequest.fromPayload(
                callbackResponse,
                context.esrOptions
            )
 
            return {
                chain: Checksum256.from(callbackResponse.cid),
                permissionLevel: PermissionLevel.from({
                    actor: callbackResponse.sa,
                    permission: callbackResponse.sp,
                }),
                identityProof: resolvedResponse.getIdentityProof(callbackResponse.sig),
            }
        } catch (error) {
            if (error instanceof Error && error.message === cancelledMessage) {
                throw new AnchorRequestCancelledError(error.message)
            }
            throw error
        } finally {
            if (fallbackTimer) {
                clearTimeout(fallbackTimer)
            }
        }
    }
 
    async sign(
        data: WalletPluginData,
        resolved: ResolvedSigningRequest,
        context: TransactContext
    ): Promise<WalletPluginSignResponse> {
        Iif (!context.ui) {
            throw new Error('No UI available')
        }
 
        const t = context.ui.getTranslate(this.options.id)
 
        const expiration = resolved.transaction.expiration.toDate()
        const now = new Date()
        const expiresIn = Math.floor(expiration.getTime() - now.getTime())
 
        const modifiedRequest = await context.createRequest({transaction: resolved.transaction})
 
        modifiedRequest.setInfoKey('link', LinkInfo.from({expiration}))
 
        const callback = setTransactionCallback(modifiedRequest, this.options.buoyUrl)
 
        const request = modifiedRequest.encode(true, false)
 
        // Mobile will return true or false, desktop will return undefined
        const isSameDevice = data.sameDevice !== false
 
        const sameDeviceRequest = modifiedRequest.clone()
        const returnUrl = (this.options.generateReturnUrl ?? generateReturnUrl)()
        sameDeviceRequest.setInfoKey('same_device', true)
        if (returnUrl) {
            sameDeviceRequest.setInfoKey('return_path', returnUrl)
        }
 
        const signManually = () => {
            context.ui?.prompt({
                title: t('transact.sign_manually.title', {default: 'Sign manually'}),
                body: t('transact.sign_manually.body', {
                    default:
                        'Scan the QR-code with Anchor on another device or use the button to open it here.',
                }),
                elements: [
                    {
                        type: 'qr',
                        data: String(request),
                    },
                    {
                        type: 'link',
                        label: t('transact.sign_manually.link.title', {default: 'Open Anchor'}),
                        data: {
                            href: String(sameDeviceRequest),
                            label: t('transact.sign_manually.link.title', {default: 'Open Anchor'}),
                        },
                    },
                ],
            })
        }
 
        const promptPromise: Cancelable<PromptResponse> = context.ui.prompt({
            title: t('transact.title', {default: 'Complete using Anchor'}),
            body: t('transact.body', {
                channelName: data.channelName,
                default: `Please open your Anchor Wallet on "${data.channelName}" to review and approve this transaction.`,
            }),
            elements: [
                {
                    type: 'countdown',
                    data: {
                        label: t('transact.await', {default: 'Waiting for response from Anchor'}),
                        end: expiration.toISOString(),
                    },
                },
                {
                    type: 'button',
                    label: t('transact.label', {default: 'Sign manually or with another device'}),
                    data: {
                        onClick: isSameDevice
                            ? () => (window.location.href = sameDeviceRequest.encode())
                            : signManually,
                        label: t('transact.label', {
                            default: 'Sign manually or with another device',
                        }),
                    },
                },
            ],
        })
 
        const timer = setTimeout(() => {
            promptPromise.cancel(
                t('error.expired', {default: 'The request expired, please try again.'})
            )
        }, expiresIn)
 
        promptPromise.catch(() => clearTimeout(timer))
 
        const callbackController = new AbortController()
        const deferCallbackUntilReturn = data.sameDevice && returnUrl && isSamePageReturn(returnUrl)
        const transactionHandoff: TransactionHandoff | null =
            deferCallbackUntilReturn && returnUrl
                ? {
                      version: 1,
                      returnUrl,
                      callback,
                      transactionId: String(resolved.transaction.id),
                      chainId: String(context.chain.id),
                      actor: String(context.permissionLevel.actor),
                      permission: String(context.permissionLevel.permission),
                      expiresAt: expiration.toISOString(),
                  }
                : null
 
        // iOS Safari can open the return_path in a fresh tab; persist enough for it to finish the ceremony.
        if (transactionHandoff) {
            storeTransactionHandoff(transactionHandoff)
        }
 
        // A WebSocket left open while Safari suspends this page can swallow the signature; connect after return.
        const callbackPromise = deferCallbackUntilReturn
            ? waitForPageReturn(returnUrl!, callbackController.signal).then(() =>
                  (this.options.waitForCallback ?? waitForCallback)(
                      callback,
                      this.options.buoyWs,
                      t
                  )
              )
            : (this.options.waitForCallback ?? waitForCallback)(callback, this.options.buoyWs, t)
 
        try {
            if (data.channelUrl) {
                const service = new URL(data.channelUrl).origin
                const channel = new URL(data.channelUrl).pathname.substring(1)
                const sealedMessage = await sealMessage(
                    (data.sameDevice ? sameDeviceRequest : modifiedRequest).encode(
                        true,
                        false,
                        'esr:'
                    ),
                    PrivateKey.from(data.privateKey),
                    PublicKey.from(data.signerKey)
                )
                const payload = Serializer.encode({object: sealedMessage}).array
 
                if (data.sameDevice) {
                    // Safari suspends this page the instant Anchor opens; the request must reach buoy first.
                    await (this.options.send ?? send)(payload, {service, channel})
                    if (data.launchUrl) {
                        window.location.href = data.launchUrl
                    IE} else if (isAppleHandheld()) {
                        window.location.href = 'anchor://link'
                    }
                } else {
                    ;(this.options.send ?? send)(payload, {service, channel})
                }
            } else {
                // If no channel is defined, fallback to the same device request and trigger immediately
                window.location.href = sameDeviceRequest.encode()
            }
        } catch (error) {
            clearTimeout(timer)
            // The abandoned page-return wait rejects on abort; swallow it.
            callbackPromise.catch(() => undefined)
            callbackController.abort()
            promptPromise.cancel()
            throw error
        }
 
        const callbackResponse = await Promise.race([callbackPromise, promptPromise]).finally(
            () => {
                clearTimeout(timer)
                callbackController.abort()
                promptPromise.cancel()
                if (transactionHandoff) {
                    clearTransactionHandoff(transactionHandoff)
                }
            }
        )
 
        const wasSuccessful =
            isCallback(callbackResponse) &&
            extractSignaturesFromCallback(callbackResponse).length > 0
 
        if (wasSuccessful) {
            const resolvedRequest = await ResolvedSigningRequest.fromPayload(
                callbackResponse,
                context.esrOptions
            )
 
            return {
                signatures: extractSignaturesFromCallback(callbackResponse),
                resolved: resolvedRequest,
            }
        }
 
        const errorString = t('error.not_completed', {default: 'The request was not completed.'})
 
        promptPromise.cancel(errorString)
 
        // This shouldn't ever trigger, but just in case
        throw new Error(errorString)
    }
}