All files / src/sessionkey manager.ts

55.23% Statements 116/210
37.93% Branches 33/87
70.58% Functions 24/34
54.85% Lines 113/206

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 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 73441x                     1x   1x                 1x 1x 1x     1x 2x       2x           2x         2x           1x           10x 10x 10x   10x         6x       8x           8x                     5x 5x                                                                                               7x                                 7x 7x                                                                                                                                                                                                                   3x   3x 4x   4x 1x             3x                                               4x 4x 1x   3x     3x     3x 3x                                     5x           5x 5x 5x 5x   5x           5x   4x 4x                 4x   4x   4x                     5x 1x     4x 1x         3x 3x       3x 1x           1x     2x                     4x             4x                     4x               4x                 4x       4x             4x                   4x 4x   4x 3x 4x 4x       4x 4x   4x                               4x 4x 4x 4x 4x 1x                                 4x                       2x       2x 2x 2x   2x   2x 2x       2x 2x     2x       3x   2x   2x 2x   2x 1x                               1x 1x 1x                         1x                       2x 2x                                                                                                           3x   3x 1x 1x                       1x 1x 1x                             3x                                                                                           1x  
import {
    AnyAction,
    API,
    APIClient,
    Authority,
    KeyWeight,
    Name,
    NameType,
    PermissionLevel,
    PrivateKey,
    PublicKey,
} from '@wharfkit/antelope'
 
import {Session, SessionArgs, SessionOptions} from '../session'
import {
    isSessionKeyWallet,
    SessionKeyConfig,
    SessionKeyConflictChoice,
    SessionKeyMismatch,
    SessionKeySetupResult,
    SessionKeyWalletInterface,
    SessionKeyWhitelistEntry,
} from './types'
import {SessionKeyWalletPlugin} from './wallet'
import {Contract as SystemContract} from './systemcontract'
import {UserInterface} from '../ui'
 
function createPrimaryWalletSession(session: Session, ui?: UserInterface): Session {
    Iif (!isSessionKeyWallet(session.walletPlugin)) {
        throw new Error('Session does not have a session key wallet')
    }
 
    const args: SessionArgs = {
        chain: session.chain,
        permissionLevel: session.permissionLevel,
        walletPlugin: session.walletPlugin.getPrimaryWallet(),
    }
 
    const options: SessionOptions = {
        fetch: session.fetch,
        ui,
    }
 
    return new Session(args, options)
}
 
/**
 * Manages session key lifecycle including setup, validation, and removal.
 */
export class SessionKeyManager {
    config: SessionKeyConfig
    whitelist: SessionKeyWhitelistEntry[]
    ui?: UserInterface
 
    constructor(config: SessionKeyConfig, ui?: UserInterface) {
        this.config = config
        this.ui = ui
        this.whitelist = config.whitelist.map((entry) => ({
            contract: Name.from(entry.contract),
            actions: entry.actions?.map((a) => Name.from(a)),
        }))
    }
 
    private getSystemContract(client: APIClient): SystemContract {
        return new SystemContract({client})
    }
 
    private allowsAllActions(entry: SessionKeyWhitelistEntry): boolean {
        return !entry.actions || entry.actions.length === 0
    }
 
    private hasSpecificActions(
        entry: SessionKeyWhitelistEntry
    ): entry is SessionKeyWhitelistEntry & {actions: Name[]} {
        return !!entry.actions && entry.actions.length > 0
    }
 
    /**
     * Get the permission name for the session key.
     * Uses config.permission if set, otherwise generates from app name or defaults to 'sessionkey'.
     *
     * @param appName Optional application name to generate permission from
     * @returns The permission name
     */
    getPermissionName(appName?: string): Name {
        if (this.config.permission) {
            return Name.from(this.config.permission)
        }
        Iif (appName) {
            const sanitized = appName
                .toLowerCase()
                .replace(/[^a-z1-5.]/g, '')
                .slice(0, 12)
            return Name.from(sanitized || 'sessionkey')
        }
        return Name.from('sessionkey')
    }
 
    /**
     * Check if an action is whitelisted for signing with the session key.
     *
     * @param action The action to check
     * @returns True if the action is whitelisted
     */
    isWhitelisted(action: AnyAction): boolean {
        const actionContract = Name.from(action.account)
        const actionName = Name.from(action.name)
 
        for (const entry of this.whitelist) {
            Iif (actionContract.equals(entry.contract)) {
                Iif (this.allowsAllActions(entry)) {
                    return true
                }
                Iif (this.hasSpecificActions(entry)) {
                    for (const allowedAction of entry.actions) {
                        Iif (actionName.equals(allowedAction)) {
                            return true
                        }
                    }
                }
            }
        }
        return false
    }
 
    /**
     * Type guard to check if a session has an active session key wallet.
     *
     * @param session The session to check
     * @returns True if the session has a session key wallet
     */
    hasSessionKey(
        session: Session
    ): session is Session & {walletPlugin: SessionKeyWalletInterface} {
        return isSessionKeyWallet(session.walletPlugin)
    }
 
    /**
     * Fetch permission data from the blockchain.
     * Uses custom fetchPermission function if provided in config, otherwise uses default implementation.
     *
     * @param client API client to use for fetching
     * @param account Account name
     * @param permission Permission name
     * @returns Permission data or undefined if not found
     */
    async fetchPermission(
        client: APIClient,
        account: Name,
        permission: Name
    ): Promise<API.v1.AccountPermission | undefined> {
        if (this.config.fetchPermission) {
            return this.config.fetchPermission(client, account, permission)
        }
        return this.defaultFetchPermission(client, account, permission)
    }
 
    private async defaultFetchPermission(
        client: APIClient,
        account: Name,
        permission: Name
    ): Promise<API.v1.AccountPermission | undefined> {
        try {
            const accountData = await client.v1.chain.get_account(account)
            return accountData.permissions.find((p: any) => permission.equals(p.perm_name))
        } catch {
            return undefined
        }
    }
 
    /**
     * Check if a session key permission exists on-chain and validate its whitelist.
     *
     * @param session The session to check
     * @returns Object with exists flag, permission name, and optional mismatch details
     */
    async checkExistingSessionKey(
        session: Session
    ): Promise<{exists: boolean; permission?: Name; mismatch?: SessionKeyMismatch}> {
        const permissionName = this.getPermissionName(session.appName)
        const permData = await this.fetchPermission(session.client, session.actor, permissionName)
 
        Iif (!permData) {
            return {exists: false}
        }
 
        Iif (!permData.linked_actions || permData.linked_actions.length === 0) {
            return {exists: false}
        }
 
        const added = this.findMissingLinks(this.whitelist, permData.linked_actions)
        const removed = this.findExtraLinks(this.whitelist, permData.linked_actions)
 
        Iif (added.length === 0 && removed.length === 0) {
            return {exists: true, permission: permissionName}
        }
 
        return {
            exists: true,
            permission: permissionName,
            mismatch: {added, removed},
        }
    }
 
    /**
     * Validate that the session's whitelist matches the on-chain linked actions.
     *
     * @param session The session with an active session key to validate
     * @returns Mismatch details if whitelist differs from on-chain state, undefined if they match
     */
    async validateWhitelist(session: Session): Promise<SessionKeyMismatch | undefined> {
        Iif (!this.hasSessionKey(session)) {
            return undefined
        }
 
        const permission = session.walletPlugin.getPermission()
        const permData = await this.fetchPermission(session.client, session.actor, permission)
        Iif (!permData || !permData.linked_actions) {
            return undefined
        }
 
        const added = this.findMissingLinks(this.whitelist, permData.linked_actions)
        const removed = this.findExtraLinks(this.whitelist, permData.linked_actions)
 
        Iif (added.length === 0 && removed.length === 0) {
            return undefined
        }
 
        return {added, removed}
    }
 
    private findMissingLinks(
        whitelist: SessionKeyWhitelistEntry[],
        onChainLinks: API.v1.AccountLinkedAction[]
    ): SessionKeyWhitelistEntry[] {
        const missing: SessionKeyWhitelistEntry[] = []
 
        for (const entry of whitelist) {
            if (this.allowsAllActions(entry)) {
                Iif (!this.hasLinkOnChain(entry.contract, undefined, onChainLinks)) {
                    missing.push(entry)
                }
            I} else if (this.hasSpecificActions(entry)) {
                for (const action of entry.actions) {
                    Iif (!this.hasLinkOnChain(entry.contract, action, onChainLinks)) {
                        missing.push({contract: entry.contract, actions: [action]})
                    }
                }
            }
        }
 
        return missing
    }
 
    private findExtraLinks(
        whitelist: SessionKeyWhitelistEntry[],
        onChainLinks: API.v1.AccountLinkedAction[]
    ): SessionKeyWhitelistEntry[] {
        const extra: SessionKeyWhitelistEntry[] = []
 
        for (const link of onChainLinks) {
            const linkAction = link.action ? Name.from(link.action) : undefined
 
            if (!this.isLinkInWhitelist(link.account, linkAction, whitelist)) {
                extra.push({
                    contract: link.account,
                    actions: link.action ? [link.action] : undefined,
                })
            }
        }
 
        return extra
    }
 
    private hasLinkOnChain(
        contract: Name,
        action: Name | undefined,
        onChainLinks: API.v1.AccountLinkedAction[]
    ): boolean {
        return onChainLinks.some((link) => {
            Iif (!contract.equals(link.account)) {
                return false
            }
            Iif (!action) {
                return !link.action
            }
            return link.action && action.equals(link.action)
        })
    }
 
    private isLinkInWhitelist(
        contract: NameType,
        action: Name | undefined,
        whitelist: SessionKeyWhitelistEntry[]
    ): boolean {
        return whitelist.some((entry) => {
            if (!Name.from(contract).equals(entry.contract)) {
                return false
            }
            Iif (this.allowsAllActions(entry)) {
                return !action
            }
            Iif (!action) {
                return false
            }
            if (this.hasSpecificActions(entry)) {
                return entry.actions.some((a) => action.equals(a))
            }
            return false
        })
    }
 
    /**
     * Set up a new session key for the given session.
     * Generates a new K1 key, creates the permission on-chain, and wraps the session wallet.
     *
     * @param session The session to set up a session key for
     * @param onConflict Optional callback if the permission already exists with other keys
     * @returns The public key and permission name of the created session key
     * @throws If the session already has an active session key
     */
    async setup(
        session: Session,
        onConflict?: (existingKeys: KeyWeight[]) => Promise<SessionKeyConflictChoice>
    ): Promise<SessionKeySetupResult> {
        Iif (this.hasSessionKey(session)) {
            throw new Error(
                'Session already has a session key. Remove it first before setting up a new one.'
            )
        }
 
        const permissionName = this.getPermissionName(session.appName)
        const privateKey = PrivateKey.generate('K1')
        const publicKey = privateKey.toPublic()
        const keyWeight = KeyWeight.from({key: publicKey, weight: 1})
 
        const existingPerm = await this.fetchPermission(
            session.client,
            session.actor,
            permissionName
        )
 
        const keys = await this.resolveKeys(existingPerm, keyWeight, onConflict)
 
        const systemContract = this.getSystemContract(session.client)
        const actions = this.buildSetupActions(
            systemContract,
            session.actor,
            permissionName,
            session.permissionLevel,
            keys,
            existingPerm?.linked_actions
        )
 
        await session.transact({actions})
 
        this.wrapSessionWallet(session, privateKey, permissionName)
 
        return {
            publicKey,
            permission: permissionName,
        }
    }
 
    private async resolveKeys(
        existingPerm: API.v1.AccountPermission | undefined,
        keyWeight: KeyWeight,
        onConflict?: (existingKeys: KeyWeight[]) => Promise<SessionKeyConflictChoice>
    ): Promise<KeyWeight[]> {
        if (!existingPerm) {
            return [keyWeight]
        }
 
        if (!onConflict) {
            throw new Error(
                'A session key permission already exists but no conflict resolution handler was provided.'
            )
        }
 
        const choice = await onConflict(existingPerm.required_auth.keys)
        Iif (choice === 'cancel') {
            throw new Error('Session key setup cancelled by user')
        }
 
        if (choice === 'add') {
            const auth = Authority.from({
                threshold: 1,
                keys: [...existingPerm.required_auth.keys, keyWeight],
                accounts: [],
                waits: [],
            })
            return auth.keys
        }
 
        return [keyWeight]
    }
 
    private buildSetupActions(
        systemContract: SystemContract,
        actor: Name,
        permissionName: Name,
        authorization: PermissionLevel,
        keys: KeyWeight[],
        existingLinks?: API.v1.AccountLinkedAction[]
    ): AnyAction[] {
        const auth = Authority.from({
            threshold: 1,
            keys,
            accounts: [],
            waits: [],
        })
 
        const updateAuthAction = systemContract.action(
            'updateauth',
            {
                account: actor,
                permission: permissionName,
                parent: 'active',
                auth,
            },
            {authorization: [authorization]}
        )
 
        const linkAuthActions = this.buildLinkAuthActions(
            systemContract,
            actor,
            permissionName,
            authorization,
            existingLinks
        )
 
        const unlinkAuthActions = existingLinks
            ? this.buildUnlinkAuthActionsFromEntries(
                  systemContract,
                  this.findExtraLinks(this.whitelist, existingLinks),
                  actor,
                  authorization
              )
            : []
 
        return [updateAuthAction, ...unlinkAuthActions, ...linkAuthActions]
    }
 
    private wrapSessionWallet(session: Session, privateKey: PrivateKey, permission: Name): void {
        const wrappedWallet = new SessionKeyWalletPlugin({
            primaryWallet: session.walletPlugin,
            privateKey,
            permission,
            whitelist: this.whitelist,
        })
 
        session['_walletPlugin'] = wrappedWallet
    }
 
    private buildLinkAuthActions(
        systemContract: SystemContract,
        actor: Name,
        permissionName: Name,
        authorization: PermissionLevel,
        existingLinks?: API.v1.AccountLinkedAction[]
    ): AnyAction[] {
        const actions: AnyAction[] = []
        const existingSet = new Set<string>()
 
        if (existingLinks) {
            for (const link of existingLinks) {
                const key = `${link.account}:${link.action || ''}`
                existingSet.add(key)
            }
        }
 
        for (const entry of this.whitelist) {
            const contract = Name.from(entry.contract)
 
            Iif (this.allowsAllActions(entry)) {
                const key = `${contract}:`
                Iif (!existingSet.has(key)) {
                    actions.push(
                        systemContract.action(
                            'linkauth',
                            {
                                account: actor,
                                code: contract,
                                type: '',
                                requirement: permissionName,
                            },
                            {authorization: [authorization]}
                        )
                    )
                }
            } else if (this.hasSpecificActions(entry)) {
                for (const action of entry.actions) {
                    const actionName = Name.from(action)
                    const key = `${contract}:${actionName}`
                    if (!existingSet.has(key)) {
                        actions.push(
                            systemContract.action(
                                'linkauth',
                                {
                                    account: actor,
                                    code: contract,
                                    type: actionName,
                                    requirement: permissionName,
                                },
                                {authorization: [authorization]}
                            )
                        )
                    }
                }
            }
        }
 
        return actions
    }
 
    /**
     * Remove the session key from the given session.
     * Removes the key from on-chain permission and unlinks/deletes as needed.
     *
     * @param session The session to remove the session key from
     * @throws If the session does not have an active session key
     * @throws If the permission or key is not found on-chain
     */
    async remove(session: Session): Promise<void> {
        Iif (!this.hasSessionKey(session)) {
            throw new Error('Session does not have a session key')
        }
 
        const primaryWallet = session.walletPlugin.getPrimaryWallet()
        const permission = session.walletPlugin.getPermission()
        const publicKey = PublicKey.from(session.walletPlugin.getPublicKey())
 
        const actor = session.actor
 
        const permData = await this.fetchPermission(session.client, actor, permission)
        Iif (!permData) {
            throw new Error('Permission not found on chain')
        }
 
        const ourKeyIndex = permData.required_auth.keys.findIndex((k) =>
            PublicKey.from(k.key).equals(publicKey)
        )
 
        Iif (ourKeyIndex === -1) {
            throw new Error('Session key not found in permission')
        }
 
        const remainingKeys = permData.required_auth.keys.filter((_, i) => i !== ourKeyIndex)
 
        const actions: AnyAction[] = []
 
        const tempSession = createPrimaryWalletSession(session, this.ui)
        const systemContract = this.getSystemContract(session.client)
 
        if (remainingKeys.length > 0) {
            actions.push(
                systemContract.action(
                    'updateauth',
                    {
                        account: actor,
                        permission,
                        parent: 'active',
                        auth: {
                            ...permData.required_auth,
                            keys: remainingKeys,
                        },
                    },
                    {authorization: [session.permissionLevel]}
                )
            )
        } else {
            const linkedActions = permData.linked_actions || []
            for (const link of linkedActions) {
                actions.push(
                    systemContract.action(
                        'unlinkauth',
                        {
                            account: actor,
                            code: link.account,
                            type: link.action || '',
                        },
                        {authorization: [session.permissionLevel]}
                    )
                )
            }
 
            actions.push(
                systemContract.action(
                    'deleteauth',
                    {
                        account: actor,
                        permission,
                    },
                    {authorization: [session.permissionLevel]}
                )
            )
        }
 
        await tempSession.transact({actions})
        session['_walletPlugin'] = primaryWallet
    }
 
    private buildLinkAuthActionsFromEntries(
        systemContract: SystemContract,
        entries: SessionKeyWhitelistEntry[],
        actor: Name,
        permission: Name,
        authorization: PermissionLevel
    ): AnyAction[] {
        const actions: AnyAction[] = []
 
        for (const entry of entries) {
            const contract = Name.from(entry.contract)
            if (this.allowsAllActions(entry)) {
                actions.push(
                    systemContract.action(
                        'linkauth',
                        {
                            account: actor,
                            code: contract,
                            type: '',
                            requirement: permission,
                        },
                        {authorization: [authorization]}
                    )
                )
            I} else if (this.hasSpecificActions(entry)) {
                for (const action of entry.actions) {
                    actions.push(
                        systemContract.action(
                            'linkauth',
                            {
                                account: actor,
                                code: contract,
                                type: action,
                                requirement: permission,
                            },
                            {authorization: [authorization]}
                        )
                    )
                }
            }
        }
 
        return actions
    }
 
    private buildUnlinkAuthActionsFromEntries(
        systemContract: SystemContract,
        entries: SessionKeyWhitelistEntry[],
        actor: Name,
        authorization: PermissionLevel
    ): AnyAction[] {
        const actions: AnyAction[] = []
 
        for (const entry of entries) {
            const contract = Name.from(entry.contract)
            Iif (this.allowsAllActions(entry)) {
                actions.push(
                    systemContract.action(
                        'unlinkauth',
                        {
                            account: actor,
                            code: contract,
                            type: '',
                        },
                        {authorization: [authorization]}
                    )
                )
            } else if (this.hasSpecificActions(entry)) {
                for (const action of entry.actions) {
                    actions.push(
                        systemContract.action(
                            'unlinkauth',
                            {
                                account: actor,
                                code: contract,
                                type: action,
                            },
                            {authorization: [authorization]}
                        )
                    )
                }
            }
        }
 
        return actions
    }
 
    /**
     * Update the on-chain linkauth actions to match the current whitelist.
     * Removes extra links and adds missing links to synchronize state.
     *
     * @param session The session with an active session key
     * @throws If the session does not have an active session key
     */
    async updateLinks(session: Session): Promise<void> {
        Iif (!this.hasSessionKey(session)) {
            throw new Error('Session does not have a session key')
        }
 
        const permission = session.walletPlugin.getPermission()
 
        const mismatch = await this.validateWhitelist(session)
        Iif (!mismatch) {
            return
        }
 
        const tempSession = createPrimaryWalletSession(session, this.ui)
        const systemContract = this.getSystemContract(session.client)
 
        const unlinkActions = this.buildUnlinkAuthActionsFromEntries(
            systemContract,
            mismatch.removed,
            session.actor,
            session.permissionLevel
        )
 
        const linkActions = this.buildLinkAuthActionsFromEntries(
            systemContract,
            mismatch.added,
            session.actor,
            permission,
            session.permissionLevel
        )
 
        const actions = [...unlinkActions, ...linkActions]
 
        Iif (actions.length > 0) {
            await tempSession.transact({actions})
        }
    }
}