All files / src/transports web.ts

88.37% Statements 76/86
64.1% Branches 25/39
91.3% Functions 21/23
88.23% Lines 75/85

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 271210x                         1x 1x               1x   1x 1x     1x 1x     1x 72x 236x   72x       1x 32x 32x 32x               1x 71x     26x         67x                             24x   24x 24x               2x 2x   2x       2x               2x 2x               2x                 6x 1x     5x   5x 5x   5x   5x 5x               5x                   5x                                           29x 29x 29x 96x 29x         29x 2x     27x 27x 13x 13x     27x           27x 127x 3x 3x       27x 27x   1x 1x     1x 1x 1x           2x                     2x 2x 2x 8x 2x       2x 2x                                     2x 2x 1x                   1x  
import {ReceiveOptions} from '@greymass/buoy'
import {
    CallbackPayload,
    Checksum256,
    LoginContext,
    PermissionLevel,
    PromptElement,
    ResolvedSigningRequest,
    TransactContext,
    UserInterface,
    WalletPluginData,
    WalletPluginLoginResponse,
    WalletPluginSignResponse,
} from '@wharfkit/session'
import {PrivateKey, PublicKey, UInt64} from '@wharfkit/antelope'
import {
    extractSignaturesFromCallback,
    isCallback,
    LinkInfo,
    sealMessage,
    setTransactionCallback,
    waitForCallback,
} from '@wharfkit/protocol-esr'
 
import {AnchorRequestCancelledError} from './errors'
import {switchButton} from './prompt'
import {IdentityRequestBundle, TransportOptions} from './types'
 
const POPUP_WIDTH = 450
const POPUP_HEIGHT = 750
 
// Raw concatenation, not URLSearchParams: the deployed authenticator decodes the values unescaped.
function signPageUrl(baseUrl: string, params: Record<string, string>): string {
    const query = Object.entries(params)
        .map(([key, value]) => `${key}=${value}`)
        .join('&')
    return `${baseUrl}/sign?${query}`
}
 
/** Open the authenticator popup. Synchronous: browsers only honour it inside a user gesture. */
export function openAuthenticatorWindow(url: string): Window | null {
    const left = Math.round(window.screenX + (window.outerWidth - POPUP_WIDTH) / 2)
    const top = Math.round(window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2)
    return window.open(
        url,
        'anchor-web',
        `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top}`
    )
}
 
/** Drives the Anchor web authenticator in a popup window, over buoy. */
export class WebTransport {
    constructor(private options: TransportOptions) {}
 
    openWindow(url: string): Window | null {
        return openAuthenticatorWindow(url)
    }
 
    /** Build the login URL for a prepared identity request. Synchronous. */
    loginUrl(context: LoginContext, bundle: IdentityRequestBundle, baseUrl: string): string {
        return signPageUrl(baseUrl, {
            esr: String(bundle.request.encode()),
            chain: String(context.chain?.id),
            requestKey: String(bundle.requestKey),
        })
    }
 
    async login(
        data: WalletPluginData,
        context: LoginContext,
        bundle: IdentityRequestBundle,
        baseUrl: string,
        popup?: Window | null,
        switchOffer?: {onSelect: () => void}
    ): Promise<WalletPluginLoginResponse> {
        context.appName = context.appName || 'Unknown App'
 
        const url = this.loginUrl(context, bundle, baseUrl)
        const {payload} = await this.awaitPopup(
            url,
            bundle.callback,
            context.ui,
            popup === undefined ? this.openWindow(url) : popup,
            switchOffer
        )
 
        data.encryptionKey = String(bundle.privateKey)
        data.messageKey = payload.link_key
 
        Iif (!payload.cid) {
            throw new Error('Login failed: No chain ID returned')
        }
 
        const loginResponse: WalletPluginLoginResponse = {
            chain: Checksum256.from(payload.cid),
            permissionLevel: PermissionLevel.from({
                actor: payload.sa,
                permission: payload.sp,
            }),
        }
 
        if (payload.sig) {
            Object.assign(loginResponse, {
                identityProof: {
                    signature: payload.sig,
                    signedRequest: bundle.request.encode(),
                },
            })
        }
 
        return loginResponse
    }
 
    async sign(
        data: WalletPluginData,
        resolved: ResolvedSigningRequest,
        context: TransactContext,
        baseUrl: string
    ): Promise<WalletPluginSignResponse> {
        if (!data.encryptionKey || !data.messageKey) {
            throw new Error('No request keys available - please login first')
        }
 
        const expiration = resolved.transaction.expiration.toDate()
 
        const modifiedRequest = await context.createRequest({transaction: resolved.transaction})
        modifiedRequest.setInfoKey('link', LinkInfo.from({expiration}))
 
        const callback = setTransactionCallback(modifiedRequest, this.options.buoyUrl)
 
        const nonce = UInt64.from(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))
        const sealedRequest = await sealMessage(
            modifiedRequest.encode(),
            PrivateKey.from(data.encryptionKey),
            PublicKey.from(data.messageKey),
            nonce
        )
 
        // Bare ciphertext, not the serialized SealedMessage — that is the format the authenticator decodes.
        const signUrl = signPageUrl(baseUrl, {
            sealed: sealedRequest.ciphertext.toString('hex'),
            nonce: nonce.toString(),
            chain: String(context.chain?.id),
            accountName: String(context.accountName),
            permissionName: String(context.permissionName),
            appName: String(context.appName),
            requestKey: String(PrivateKey.from(data.encryptionKey).toPublic()),
        })
 
        const response = await this.awaitPopup(
            signUrl,
            callback,
            context.ui,
            this.openWindow(signUrl)
        )
 
        const signatures = extractSignaturesFromCallback(response.payload)
        Iif (!isCallback(response.payload) || signatures.length === 0) {
            throw new Error('Signing failed: No signatures returned')
        }
 
        return {signatures, resolved}
    }
 
    private awaitPopup(
        url: string,
        receiveOptions: ReceiveOptions,
        ui: UserInterface | undefined,
        popup: Window | null,
        switchOffer?: {onSelect: () => void}
    ): Promise<{payload: CallbackPayload}> {
        return new Promise((resolve, reject) => {
            const t = ui?.getTranslate(this.options.id)
            const translate = (key: string, fallbackText: string) =>
                t ? t(key, {default: fallbackText}) : fallbackText
            const cancelledMessage = translate(
                'error.cancelled',
                'The request was cancelled from Anchor.'
            )
 
            if (!popup) {
                return this.promptManualOpen(url, receiveOptions, ui).then(resolve, reject)
            }
 
            const elements: PromptElement[] = []
            if (switchOffer) {
                const label = translate('mode.switch.to_app', 'Use the Anchor app instead')
                elements.push(switchButton(label, 'text', () => switchOffer.onSelect()))
            }
 
            ui?.prompt({
                title: translate('web.waiting.title', 'Approve in Anchor'),
                body: translate('web.waiting.body', 'Please approve this in the Anchor window.'),
                elements,
            }).catch(() => undefined)
 
            const checkClosedInterval = setInterval(() => {
                if (popup.closed) {
                    clearInterval(checkClosedInterval)
                    reject(new AnchorRequestCancelledError())
                }
            }, 1000)
 
            const onCallback = this.options.waitForCallback ?? waitForCallback
            onCallback(receiveOptions, this.options.buoyWs, t)
                .then((response) => {
                    popup.close()
                    resolve({payload: response})
                })
                .catch((error) => {
                    popup.close()
                    if (error instanceof Error && error.message === cancelledMessage) {
                        reject(new AnchorRequestCancelledError(error.message))
                    } else E{
                        reject(error)
                    }
                })
                .finally(() => {
                    clearInterval(checkClosedInterval)
                })
        })
    }
 
    /** Popup blocked: offer a real link, which no popup blocker touches, and listen for the callback. */
    private promptManualOpen(
        url: string,
        receiveOptions: ReceiveOptions,
        ui: UserInterface | undefined
    ): Promise<{payload: CallbackPayload}> {
        return new Promise((resolve, reject) => {
            const t = ui?.getTranslate(this.options.id)
            const translate = (key: string, fallbackText: string) =>
                t ? t(key, {default: fallbackText}) : fallbackText
            const cancelledMessage = translate(
                'error.cancelled',
                'The request was cancelled from Anchor.'
            )
            const openLabel = translate('web.blocked.label', 'Open Anchor')
            ui?.prompt({
                title: translate('web.blocked.title', 'Pop-up blocked'),
                body: translate(
                    'web.blocked.body',
                    'Pop-up blocked by your browser. Open the Anchor window manually.'
                ),
                elements: [
                    {
                        type: 'link',
                        label: openLabel,
                        data: {
                            href: url,
                            label: openLabel,
                            variant: 'primary',
                        },
                    },
                ],
            }).catch(reject)
 
            const onCallback = this.options.waitForCallback ?? waitForCallback
            onCallback(receiveOptions, this.options.buoyWs, t)
                .then((response) => resolve({payload: response}))
                .catch((error) => {
                    if (error instanceof Error && error.message === cancelledMessage) {
                        reject(new AnchorRequestCancelledError(error.message))
                    } else {
                        reject(error)
                    }
                })
        })
    }
}