All files kit.ts

87.43% Statements 160/183
77.77% Branches 119/153
91.66% Functions 22/24
88.63% Lines 156/176

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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 5351x               1x     1x             1x 1x 1x             1x   1x                                                                                           1x 65x 65x     65x         65x           65x   280x   65x   65x   65x 65x         65x 1x     65x     65x   65x 65x         65x 4x   61x     65x 2x     65x 1x     65x 1x         93x 93x 137x 93x 2x   91x                           43x   43x         7x           45x               43x     43x 20x 19x 23x 5x 5x       42x 28x 28x       42x 42x 40x 40x 2x               42x             21x     21x 21x     21x 1x       20x   21x             20x       20x 20x       41x         41x 41x           2x           39x     39x     39x                   39x     39x     39x     39x           4x 4x         34x     34x 34x 2x 2x 2x 2x 1x   2x 2x               2x     32x           9x 2x 2x     2x       7x             7x   7x   7x 7x   7x 11x                                                               7x 7x     7x     7x 1x           6x 6x       6x 5x       6x                         6x     6x       1x 1x 1x 1x 3x 3x 3x       1x             45x         45x     45x     45x     45x 45x 18x 18x     31x               16x 9x   16x       18x     18x 20x 20x 20x 20x     18x   27x         10x     10x 10x 8x 8x   8x 8x 8x     8x             45x                          
import {
    Checksum256,
    Checksum256Type,
    Name,
    NameType,
    PermissionLevel,
    PermissionLevelType,
} from '@wharfkit/antelope'
import {ChainDefinition} from '@wharfkit/common'
import type {ChainDefinitionType, Fetch} from '@wharfkit/common'
 
import {
    AbstractLoginPlugin,
    BaseLoginPlugin,
    LoginContext,
    LoginPlugin,
    UserInterfaceWalletPlugin,
} from './login'
import {SerializedSession, Session} from './session'
import {BrowserLocalStorage, SessionStorage} from './storage'
import {
    AbstractTransactPlugin,
    BaseTransactPlugin,
    TransactABIDef,
    TransactPlugin,
    TransactPluginsOptions,
} from './transact'
import {WalletPlugin, WalletPluginLoginResponse, WalletPluginMetadata} from './wallet'
import {UserInterface} from './ui'
import {getFetch} from './utils'
 
export interface LoginOptions {
    chain?: Checksum256Type
    chains?: Checksum256Type[]
    loginPlugins?: LoginPlugin[]
    transactPlugins?: TransactPlugin[]
    transactPluginsOptions?: TransactPluginsOptions
    permissionLevel?: PermissionLevelType | string
    walletPlugin?: string
}
 
export interface LoginResult {
    context: LoginContext
    response: WalletPluginLoginResponse
    session: Session
}
 
export interface RestoreArgs {
    chain: Checksum256Type
    actor?: NameType
    permission?: NameType
    walletPlugin?: Record<string, any>
}
 
export interface SessionKitArgs {
    appName: NameType
    chains: ChainDefinitionType[]
    ui: UserInterface
    walletPlugins: WalletPlugin[]
}
 
export interface SessionKitOptions {
    abis?: TransactABIDef[]
    allowModify?: boolean
    expireSeconds?: number
    fetch?: Fetch
    loginPlugins?: LoginPlugin[]
    storage?: SessionStorage
    transactPlugins?: TransactPlugin[]
    transactPluginsOptions?: TransactPluginsOptions
}
 
/**
 * Request a session from an account.
 */
export class SessionKit {
    readonly abis: TransactABIDef[] = []
    readonly allowModify: boolean = true
    readonly appName: string
    readonly chains: ChainDefinition[]
    readonly expireSeconds: number = 120
    readonly fetch: Fetch
    readonly loginPlugins: AbstractLoginPlugin[]
    readonly storage: SessionStorage
    readonly transactPlugins: AbstractTransactPlugin[]
    readonly transactPluginsOptions: TransactPluginsOptions = {}
    readonly ui: UserInterface
    readonly walletPlugins: WalletPlugin[]
 
    constructor(args: SessionKitArgs, options: SessionKitOptions = {}) {
        // Save the appName to the SessionKit instance
        this.appName = String(args.appName)
        // Map the chains provided to ChainDefinition instances
        this.chains = args.chains.map((chain) => ChainDefinition.from(chain))
        // Save the UserInterface instance to the SessionKit
        this.ui = args.ui
        // Establish default plugins for wallet flow
        this.walletPlugins = args.walletPlugins
        // Override fetch if provided
        Eif (options.fetch) {
            this.fetch = options.fetch
        } else {
            this.fetch = getFetch(options)
        }
        // Add any ABIs manually provided
        if (options.abis) {
            this.abis = [...options.abis]
        }
        // Establish default plugins for login flow
        Iif (options.loginPlugins) {
            this.loginPlugins = options.loginPlugins
        } else {
            this.loginPlugins = [new BaseLoginPlugin()]
        }
        Eif (options.storage) {
            this.storage = options.storage
        } else {
            this.storage = new BrowserLocalStorage()
        }
        // Establish default plugins for transact flow
        if (options.transactPlugins) {
            this.transactPlugins = options.transactPlugins
        } else {
            this.transactPlugins = [new BaseTransactPlugin()]
        }
        // Store options passed on the kit
        if (typeof options.allowModify !== 'undefined') {
            this.allowModify = options.allowModify
        }
        // Override default expireSeconds for all sessions if specified
        if (options.expireSeconds) {
            this.expireSeconds = options.expireSeconds
        }
        // Establish default options for transact plugins
        if (options.transactPluginsOptions) {
            this.transactPluginsOptions = options.transactPluginsOptions
        }
    }
 
    getChainDefinition(id: Checksum256Type, override?: ChainDefinition[]): ChainDefinition {
        const chains = override ? override : this.chains
        const chainId = Checksum256.from(id)
        const chain = chains.find((c) => c.id.equals(chainId))
        if (!chain) {
            throw new Error(`No chain defined with the ID of: ${chainId}`)
        }
        return chain
    }
 
    /**
     * Request a session from an account.
     *
     * @mermaid - Login sequence diagram
     * flowchart LR
     *   A((Login)) --> B{{"Hook(s): beforeLogin"}}
     *   B --> C[Wallet Plugin]
     *   C --> D{{"Hook(s): afterLogin"}}
     *   D --> E[Session]
     */
    async login(options?: LoginOptions): Promise<LoginResult> {
        try {
            // Create LoginContext for this login request.
            const context = new LoginContext({
                appName: this.appName,
                chain: undefined,
                chains:
                    options && options?.chains
                        ? options.chains.map((c) => this.getChainDefinition(c))
                        : this.chains,
                fetch: this.fetch,
                loginPlugins: this.loginPlugins,
                ui: this.ui,
                walletPlugins: this.walletPlugins.map((plugin): UserInterfaceWalletPlugin => {
                    return {
                        config: plugin.config,
                        metadata: WalletPluginMetadata.from(plugin.metadata),
                    }
                }),
            })
 
            // Tell the UI a login request is beginning.
            await context.ui.onLogin()
 
            // Predetermine chain (if possible) to prevent uneeded UI interactions.
            if (options && options.chain) {
                context.chain = this.getChainDefinition(options.chain, context.chains)
                context.uiRequirements.requiresChainSelect = false
            } else if (context.chains.length === 1) {
                context.chain = context.chains[0]
                context.uiRequirements.requiresChainSelect = false
            }
 
            // Predetermine permission (if possible) to prevent uneeded UI interactions.
            if (options?.permissionLevel) {
                context.permissionLevel = PermissionLevel.from(options.permissionLevel)
                context.uiRequirements.requiresPermissionSelect = false
            }
 
            // Predetermine WalletPlugin (if possible) to prevent uneeded UI interactions.
            let walletPlugin: WalletPlugin | undefined = undefined
            if (this.walletPlugins.length === 1) {
                walletPlugin = this.walletPlugins[0] // Default to first when only one.
                context.uiRequirements.requiresWalletSelect = false
            } else Iif (options?.walletPlugin) {
                walletPlugin = this.walletPlugins.find((p) => p.id === options.walletPlugin)
                if (walletPlugin) {
                    context.uiRequirements.requiresWalletSelect = false
                }
            }
 
            // Determine if the login process requires any user interaction.
            if (
                context.uiRequirements.requiresChainSelect ||
                context.uiRequirements.requiresPermissionSelect ||
                context.uiRequirements.requiresPermissionEntry ||
                context.uiRequirements.requiresWalletSelect
            ) {
                // Perform UserInterface.login() flow to get determine the chain, permission, and WalletPlugin.
                const uiLoginResponse = await context.ui.login(context)
 
                // Attempt to set the current WalletPlugin to the index the UI requested
                Eif (uiLoginResponse.walletPluginIndex !== undefined) {
                    walletPlugin = this.walletPlugins[uiLoginResponse.walletPluginIndex]
                }
 
                if (!walletPlugin) {
                    throw new Error('UserInterface did not return a valid WalletPlugin index.')
                }
 
                // Attempt to set the current chain to match the UI response
                Eif (uiLoginResponse.chainId) {
                    // Ensure the chain ID returned by the UI is in the list of chains
                    Iif (!context.chains.some((c) => c.id.equals(uiLoginResponse.chainId!))) {
                        throw new Error(
                            'UserInterface did not return a chain ID matching the subset of chains.'
                        )
                    }
 
                    // Set the context.chain definition from the new chain ID
                    context.chain = this.getChainDefinition(uiLoginResponse.chainId, context.chains)
                }
 
                // Set the PermissionLevel from the UI response to the context
                Eif (uiLoginResponse.permissionLevel) {
                    context.permissionLevel = PermissionLevel.from(uiLoginResponse.permissionLevel)
                }
            }
 
            Iif (!walletPlugin) {
                throw new Error('No WalletPlugin available to perform the login.')
            }
 
            // Ensure the wallet plugin supports the chain that was selected
            const {supportedChains} = walletPlugin.config
            if (
                context.chain &&
                supportedChains &&
                supportedChains.length &&
                !supportedChains.includes(String(context.chain.id))
            ) {
                throw new Error(
                    `The wallet plugin '${walletPlugin.metadata.name}' does not support the chain '${context.chain.id}'`
                )
            }
 
            // Call the `beforeLogin` hooks that were registered by the LoginPlugins
            for (const hook of context.hooks.beforeLogin) await hook(context)
 
            // Perform the login request against the selected walletPlugin
            const response: WalletPluginLoginResponse = await walletPlugin.login(context)
 
            // Create a session from the resulting login response
            const session = new Session(
                {
                    chain: this.getChainDefinition(response.chain),
                    permissionLevel: response.permissionLevel,
                    walletPlugin,
                },
                this.getSessionOptions(options)
            )
 
            // Call the `afterLogin` hooks that were registered by the LoginPlugins
            for (const hook of context.hooks.afterLogin) await hook(context)
 
            // Save the session to storage if it has a storage instance.
            this.persistSession(session)
 
            // Notify the UI that the login request has completed.
            await context.ui.onLoginComplete()
 
            // Return the results of the login request.
            return {
                context,
                response,
                session,
            }
        } catch (error: any) {
            await this.ui.onError(error)
            throw new Error(error)
        }
    }
 
    async logout(session?: Session | SerializedSession) {
        Iif (!this.storage) {
            throw new Error('An instance of Storage must be provided to utilize the logout method.')
        }
        await this.storage.remove('session')
        if (session) {
            const sessions = await this.getSessions()
            Eif (sessions) {
                let serialized = session
                if (session instanceof Session) {
                    serialized = session.serialize()
                }
                const other = sessions.filter((s: Record<string, any>) => {
                    return (
                        !Checksum256.from(s.chain).equals(
                            Checksum256.from(String(serialized.chain))
                        ) ||
                        !Name.from(s.actor).equals(Name.from(serialized.actor)) ||
                        !Name.from(s.permission).equals(Name.from(serialized.permission))
                    )
                })
                await this.storage.write('sessions', JSON.stringify(other))
            }
        } else {
            await this.storage.remove('sessions')
        }
    }
 
    async restore(args?: RestoreArgs, options?: LoginOptions): Promise<Session | undefined> {
        // If no args were provided, attempt to default restore the session from storage.
        if (!args) {
            const data = await this.storage.read('session')
            Iif (data) {
                args = JSON.parse(data)
            } else {
                return
            }
        }
 
        Iif (!args) {
            throw new Error('Either a RestoreArgs object or a Storage instance must be provided.')
        }
 
        let serializedSession: SerializedSession
 
        // Retrieve all sessions from storage
        const data = await this.storage.read('sessions')
 
        Eif (data) {
            // If sessions exist, restore the session that matches the provided args
            const sessions = JSON.parse(data)
            Eif (args.actor && args.permission) {
                // If all args are provided, return exact match
                serializedSession = sessions.find((s: SerializedSession) => {
                    return (
                        args &&
                        s.chain === args.chain &&
                        s.actor === args.actor &&
                        s.permission === args.permission
                    )
                })
            } else {
                // If no actor/permission defined, return based on chain
                serializedSession = sessions.find((s: SerializedSession) => {
                    return args && s.chain === args.chain && s.default
                })
            }
        } else {
            // If no sessions were found, but the args contains all the data for a serialized session, use args
            if (args.actor && args.permission && args.walletPlugin) {
                serializedSession = {
                    chain: args.chain,
                    actor: args.actor,
                    permission: args.permission,
                    walletPlugin: {
                        id: args.walletPlugin.id,
                        data: args.walletPlugin.data,
                    },
                }
            } else {
                // Otherwise throw an error since we can't establish the session data
                throw new Error('No sessions found in storage. A wallet plugin must be provided.')
            }
        }
 
        // Ensure a WalletPlugin was found with the provided ID.
        const walletPlugin = this.walletPlugins.find((p) => {
            Iif (!args) {
                return false
            }
            return p.id === serializedSession.walletPlugin.id
        })
 
        if (!walletPlugin) {
            throw new Error(
                `No WalletPlugin found with the ID of: '${serializedSession.walletPlugin.id}'`
            )
        }
 
        // Set the wallet data from the serialized session
        Eif (serializedSession.walletPlugin.data) {
            walletPlugin.data = serializedSession.walletPlugin.data
        }
 
        // If walletPlugin data was provided by args, override
        if (args.walletPlugin && args.walletPlugin.data) {
            walletPlugin.data = args.walletPlugin.data
        }
 
        // Create a new session from the provided args.
        const session = new Session(
            {
                chain: this.getChainDefinition(serializedSession.chain),
                permissionLevel: PermissionLevel.from({
                    actor: serializedSession.actor,
                    permission: serializedSession.permission,
                }),
                walletPlugin,
            },
            this.getSessionOptions(options)
        )
 
        // Save the session to storage if it has a storage instance.
        this.persistSession(session)
 
        // Return the session
        return session
    }
 
    async restoreAll(): Promise<Session[]> {
        const sessions: Session[] = []
        const serializedSessions = await this.getSessions()
        Eif (serializedSessions) {
            for (const s of serializedSessions) {
                const session = await this.restore(s)
                Eif (session) {
                    sessions.push(session)
                }
            }
        }
        return sessions
    }
 
    async persistSession(session: Session, setAsDefault = true) {
        // TODO: Allow disabling of session persistence via kit options
 
        // If no storage exists, do nothing.
        Iif (!this.storage) {
            return
        }
 
        // Serialize session passed in
        const serialized = session.serialize()
 
        // Specify whether or not this is now the default for the given chain
        serialized.default = setAsDefault
 
        // Set this as the current session for all chains
        this.storage.write('session', JSON.stringify(serialized))
 
        // Add the current session to the list of sessions, preventing duplication.
        const existing = await this.storage.read('sessions')
        if (existing) {
            const stored = JSON.parse(existing)
            const sessions: SerializedSession[] = stored
                // Filter out any matching session to ensure no duplicates
                .filter((s: SerializedSession): boolean => {
                    return (
                        !Checksum256.from(s.chain).equals(Checksum256.from(serialized.chain)) ||
                        !Name.from(s.actor).equals(Name.from(serialized.actor)) ||
                        !Name.from(s.permission).equals(Name.from(serialized.permission))
                    )
                })
                // Remove the default status from all other sessions for this chain
                .map((s: SerializedSession): SerializedSession => {
                    if (session.chain.id.equals(s.chain)) {
                        s.default = false
                    }
                    return s
                })
 
            // Merge arrays
            const orderedSessions = [...sessions, serialized]
 
            // Sort sessions by chain, actor, and permission
            orderedSessions.sort((a: SerializedSession, b: SerializedSession) => {
                const chain = String(a.chain).localeCompare(String(b.chain))
                const actor = String(a.actor).localeCompare(String(b.actor))
                const permission = String(a.permission).localeCompare(String(b.permission))
                return chain || actor || permission
            })
 
            this.storage.write('sessions', JSON.stringify(orderedSessions))
        } else {
            this.storage.write('sessions', JSON.stringify([serialized]))
        }
    }
 
    async getSessions(): Promise<SerializedSession[]> {
        Iif (!this.storage) {
            throw new Error('No storage instance is available to retrieve sessions from.')
        }
        const data = await this.storage.read('sessions')
        if (!data) return []
        try {
            const parsed = JSON.parse(data)
            // Only return sessions that have a wallet plugin that is currently registered.
            const filtered = parsed.filter((s: SerializedSession) =>
                this.walletPlugins.some((p) => {
                    return p.id === s.walletPlugin.id
                })
            )
            return filtered
        } catch (e) {
            throw new Error(`Failed to parse sessions from storage (${e})`)
        }
    }
 
    getSessionOptions(options?: LoginOptions) {
        return {
            abis: this.abis,
            allowModify: this.allowModify,
            appName: this.appName,
            expireSeconds: this.expireSeconds,
            fetch: this.fetch,
            storage: this.storage,
            transactPlugins: options?.transactPlugins || this.transactPlugins,
            transactPluginsOptions: options?.transactPluginsOptions || this.transactPluginsOptions,
            ui: this.ui,
        }
    }
}