All files / src index.ts

96.8% Statements 121/125
92.85% Branches 52/56
96% Functions 24/25
97.45% Lines 115/118

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 384314x                             1x   1x       1x 1x               1x 1x 1x 1x                                       1x 1x                                         64x         64x     64x   64x 64x 64x 64x   64x           64x 64x   64x           64x                 64x                       41x         81x 53x 53x 53x 28x   26x         16x         5x               10x 10x       10x 4x   6x       41x       41x 39x 39x 39x 39x 39x           39x 5x 5x     34x 34x   22x                     12x     7x 4x     3x   4x 4x     4x                 4x 5x       5x     3x 3x       1x                                 25x 4x   3x   1x 1x       25x       25x   25x 25x 25x 25x 3x   2x   3x         25x       2x     1x       25x   25x 4x 1x     3x   3x                         12x 12x 12x 7x 4x 1x 1x   3x     3x 3x     12x                   5x 5x 3x 2x 2x   1x     5x               9x               9x   9x 5x 5x 1x       4x     4x   1x   1x    
import {
    AbstractWalletPlugin,
    ChainDefinition,
    Checksum256,
    LoginContext,
    Logo,
    PermissionLevel,
    PrivateKey,
    PublicKey,
    ResolvedSigningRequest,
    TransactContext,
    WalletPluginConfig,
    WalletPluginLoginResponse,
    WalletPluginMetadata,
    WalletPluginSignResponse,
} from '@wharfkit/session'
import {Checksum256Type} from '@wharfkit/antelope'
import {createIdentityRequest} from '@wharfkit/protocol-esr'
 
import WebSocket from 'isomorphic-ws'
 
import defaultTranslations from './translations'
import {resolveWebAuthenticatorUrl} from './chains'
import {
    AnchorMode,
    promptForMode,
    promptForRecovery,
    readLoginOptions,
    readMode,
    writeMode,
} from './mode'
import {AnchorRequestCancelledError} from './transports/errors'
import {NativeTransport} from './transports/native'
import {openAuthenticatorWindow, WebTransport} from './transports/web'
import {IdentityRequestBundle, Translator, TransportOptions} from './transports/types'
 
/** Options controlling Anchor's native and browser transports. */
export interface WalletPluginAnchorOptions {
    /** Buoy callback service URL. */
    buoyUrl?: string
    /** WebSocket override forwarded to Buoy callback handling. */
    buoyWs?: WebSocket
    /** Extra or replacement web-authenticator URLs keyed by chain ID. */
    webAuthenticatorUrls?: Record<string, string>
    /** Delay in milliseconds before app login offers the browser fallback. */
    webFallbackDelayMs?: number
    /** Explicit login route; omit it to ask on each supported-chain login. */
    mode?: AnchorMode
    /** Buoy and callback overrides forwarded to both transports. */
    transport?: Pick<TransportOptions, 'send' | 'waitForCallback' | 'generateReturnUrl'>
}
 
/** Default delay before app login offers the browser fallback, in milliseconds. */
export const DEFAULT_WEB_FALLBACK_DELAY_MS = 8000
export class WalletPluginAnchor extends AbstractWalletPlugin {
    chain: Checksum256 | undefined
    auth: PermissionLevel | undefined
    requestKey: PublicKey | undefined
    privateKey: PrivateKey | undefined
    signerKey: PublicKey | undefined
    channelUrl: string | undefined
    channelName: string | undefined
    buoyUrl: string
    buoyWs: WebSocket | undefined
 
    webAuthenticatorUrls: Record<string, string>
    webFallbackDelayMs: number
 
    private native: NativeTransport
    private web: WebTransport
    private loginModeOverride: AnchorMode | undefined
 
    /**
     * The unique identifier for the wallet plugin.
     */
    id = 'anchor'
 
    /**
     * The translations for this plugin
     */
    translations = defaultTranslations
 
    constructor(options?: WalletPluginAnchorOptions) {
        super()
 
        this.buoyUrl = options?.buoyUrl || 'https://cb.anchor.link'
        this.buoyWs = options?.buoyWs
        this.webAuthenticatorUrls = options?.webAuthenticatorUrls || {}
        this.webFallbackDelayMs = options?.webFallbackDelayMs ?? DEFAULT_WEB_FALLBACK_DELAY_MS
 
        const transportOptions: TransportOptions = {
            id: this.id,
            buoyUrl: this.buoyUrl,
            buoyWs: this.buoyWs,
            ...options?.transport,
        }
        this.native = new NativeTransport(transportOptions)
        this.web = new WebTransport(transportOptions)
 
        this.setMode(options?.mode)
    }
 
    /**
     * The logic configuration for the wallet plugin.
     */
    readonly config: WalletPluginConfig = {
        // Should the user interface display a chain selector?
        requiresChainSelect: false,
        // Should the user interface display a permission selector?
        requiresPermissionSelect: false,
    }
    /**
     * The metadata for the wallet plugin to be displayed in the user interface.
     */
    readonly metadata: WalletPluginMetadata = WalletPluginMetadata.from({
        name: 'Anchor',
        description: '',
        logo: Logo.from({
            dark: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHN2ZyB3aWR0aD0iMTYwIiBoZWlnaHQ9IjE2MCIgdmlld0JveD0iMCAwIDI1NiAyNTYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPGcgdHJhbnNmb3JtPSJtYXRyaXgoMS40NCwgMC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gODcgODYuMDAwMyA4OS42ODYzIDg2LjAwMDMgOTNWMTE3QzkyLjgyNjUgMTE0LjYzOCA5Ny43MTgzIDEwOC4zNTkgOTcuOTk5NSAxMDFaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K',
        }),
        homepage: 'https://anchorwallet.io',
        download: 'https://anchorwallet.io/download',
    })
 
    login(context: LoginContext): Promise<WalletPluginLoginResponse> {
        return this.handleLogin(context)
    }
 
    /** Override login routing until cleared; pass `undefined` to restore the chooser. */
    setMode(mode: AnchorMode | undefined) {
        if (mode === undefined) {
            this.loginModeOverride = undefined
            delete this.data.mode
            return
        }
        writeMode(this.data, mode)
        this.loginModeOverride = mode
    }
 
    /** Return the mode stored or inferred for signing; this does not imply a login override. */
    getMode(): AnchorMode | undefined {
        return readMode(this.data)
    }
 
    /** Open the chain's web authenticator in a user gesture; unsupported chains return `null`. */
    openWallet(chain?: ChainDefinition | Checksum256Type): Window | null {
        return WalletPluginAnchor.openWallet(chain, this.webAuthenticatorUrls)
    }
 
    /** Open a chain's web authenticator with URL overrides; unsupported chains return `null`. */
    static openWallet(
        chain?: ChainDefinition | Checksum256Type,
        webAuthenticatorUrls?: Record<string, string>
    ): Window | null {
        const chainId = chain && typeof chain === 'object' && 'id' in chain ? chain.id : chain
        const url = resolveWebAuthenticatorUrl(
            chainId as Checksum256Type | undefined,
            webAuthenticatorUrls
        )
        if (!url) {
            return null
        }
        return openAuthenticatorWindow(url)
    }
 
    async handleLogin(context: LoginContext): Promise<WalletPluginLoginResponse> {
        Iif (!context.ui) {
            throw new Error('No UI available')
        }
 
        const perCall = readLoginOptions(this.id, context.arbitrary)
        const preopened = perCall.popup
        const t = context.ui.getTranslate(this.id)
        const webUrl = resolveWebAuthenticatorUrl(context.chain?.id, this.webAuthenticatorUrls)
        try {
            const bundle = (await createIdentityRequest(
                context,
                this.buoyUrl
            )) as IdentityRequestBundle
 
            // Native-only chain: the question has no second answer, so never ask it.
            if (!webUrl) {
                preopened?.close()
                return await this.native.login(this.data, context, bundle, t)
            }
 
            const forcedMode = perCall.mode ?? this.loginModeOverride
            if (forcedMode) {
                writeMode(this.data, forcedMode)
                return await this.loginWithSwitch(
                    context,
                    bundle,
                    t,
                    webUrl,
                    forcedMode,
                    true,
                    preopened
                )
            }
 
            const {mode, popup} = await this.chooseMode(context, bundle, t, webUrl, preopened)
            writeMode(this.data, mode)
 
            if (mode === 'web') {
                return await this.web.login(this.data, context, bundle, webUrl, popup)
            }
            // Freshly chosen: no immediate switch link, but still recover from a silent deep link.
            return await this.loginWithSwitch(context, bundle, t, webUrl, 'app', false)
        } catch (error) {
            preopened?.close()
            Iif (!(error instanceof AnchorRequestCancelledError)) {
                throw error
            }
            return this.recoverLogin(context, t, webUrl)
        }
    }
 
    private async recoverLogin(
        context: LoginContext,
        t: Translator,
        webUrl?: string
    ): Promise<WalletPluginLoginResponse> {
        for (;;) {
            const bundle = (await createIdentityRequest(
                context,
                this.buoyUrl
            )) as IdentityRequestBundle
            const {mode, popup} = await this.chooseRecoveryMode(context, bundle, t, webUrl)
            writeMode(this.data, mode)
 
            try {
                return mode === 'web' && webUrl
                    ? await this.web.login(this.data, context, bundle, webUrl, popup)
                    : await this.native.login(this.data, context, bundle, t)
            } catch (error) {
                Iif (!(error instanceof AnchorRequestCancelledError)) {
                    throw error
                }
            }
        }
    }
 
    // The alternate transport needs its own identity request: two receivers on one channel race.
    private async loginWithSwitch(
        context: LoginContext,
        bundle: IdentityRequestBundle,
        t: Translator,
        webUrl: string,
        mode: AnchorMode,
        immediate: boolean,
        preopened?: Window
    ): Promise<WalletPluginLoginResponse> {
        if (preopened) {
            if (mode === 'web') {
                // Navigate before the alternate-request await; the caller's popup is idling on a landing page.
                preopened.location.href = this.web.loginUrl(context, bundle, webUrl)
            } else {
                preopened.close()
                preopened = undefined
            }
        }
 
        const alternateBundle = (await createIdentityRequest(
            context,
            this.buoyUrl
        )) as IdentityRequestBundle
        const alternateUrl = this.web.loginUrl(context, alternateBundle, webUrl)
 
        let popup: Window | null = null
        let switchTo: () => void = () => undefined
        const switched = new Promise<'switched'>((resolve) => {
            switchTo = () => {
                if (mode === 'app') {
                    // Must happen inside the click, before any await.
                    popup = this.web.openWindow(alternateUrl)
                }
                resolve('switched')
            }
        })
 
        const primary =
            mode === 'app'
                ? this.native.login(this.data, context, bundle, t, {
                      immediate,
                      delayMs: this.webFallbackDelayMs,
                      onSelect: () => switchTo(),
                  })
                : this.web.login(this.data, context, bundle, webUrl, preopened, {
                      onSelect: () => switchTo(),
                  })
 
        // The loser of the race is abandoned; swallow its eventual rejection.
        primary.catch(() => undefined)
 
        const winner = await Promise.race([primary.then(() => 'primary' as const), switched])
        if (winner === 'primary') {
            return primary
        }
 
        const next: AnchorMode = mode === 'app' ? 'web' : 'app'
        writeMode(this.data, next)
        return next === 'web'
            ? this.web.login(this.data, context, alternateBundle, webUrl, popup)
            : this.native.login(this.data, context, alternateBundle, t)
    }
 
    /** The browser popup opens inside the click handler, before this promise resolves. */
    private chooseMode(
        context: LoginContext,
        bundle: IdentityRequestBundle,
        t: Translator,
        webUrl: string,
        preopened?: Window
    ): Promise<{mode: AnchorMode; popup?: Window | null}> {
        return new Promise((resolve, reject) => {
            const url = this.web.loginUrl(context, bundle, webUrl)
            const prompt = promptForMode(context, t, (mode) => {
                if (mode === 'web') {
                    if (preopened) {
                        preopened.location.href = url
                        resolve({mode, popup: preopened})
                    } else {
                        resolve({mode, popup: this.web.openWindow(url)})
                    }
                } else {
                    preopened?.close()
                    resolve({mode})
                }
            })
            prompt.catch(reject)
        })
    }
 
    private chooseRecoveryMode(
        context: LoginContext,
        bundle: IdentityRequestBundle,
        t: Translator,
        webUrl?: string
    ): Promise<{mode: AnchorMode; popup?: Window | null}> {
        return new Promise((resolve, reject) => {
            const prompt = promptForRecovery(context, t, Boolean(webUrl), (mode) => {
                if (mode === 'web' && webUrl) {
                    const url = this.web.loginUrl(context, bundle, webUrl)
                    resolve({mode, popup: this.web.openWindow(url)})
                } else {
                    resolve({mode})
                }
            })
            prompt.catch(reject)
        })
    }
 
    sign(
        resolved: ResolvedSigningRequest,
        context: TransactContext
    ): Promise<WalletPluginSignResponse> {
        return this.handleSign(resolved, context)
    }
 
    private async handleSign(
        resolved: ResolvedSigningRequest,
        context: TransactContext
    ): Promise<WalletPluginSignResponse> {
        // Never asks a question; v1.x sessions predate the concept and are always native.
        const mode = readMode(this.data) || 'app'
 
        if (mode === 'web') {
            const webUrl = resolveWebAuthenticatorUrl(context.chain?.id, this.webAuthenticatorUrls)
            if (!webUrl) {
                throw new Error(
                    `This session signs in the browser, but there is no Anchor web authenticator for chain ${context.chain?.id}.`
                )
            }
            return this.web.sign(this.data, resolved, context, webUrl)
        }
 
        return this.native.sign(this.data, resolved, context)
    }
}
 
export {DEFAULT_WEB_AUTHENTICATOR_URLS} from './chains'
export type {AnchorLoginOptions, AnchorMode} from './mode'