keybase-bot

repository·master·Indexed 42 days ago

https://github.com/keybase/keybase-bot

A TypeScript Node.js library for scripting Keybase commands. It enables automation of tasks such as sending and reading messages, managing team memberships, handling attachments, and interacting with Stellar wallet balances and transactions. Version 4.0.0.

Tokens
42K
Snippets
171
Records
199
Agent score
48%

What's inside keybase-bot

  1. Initialize your bot

    master

    There are two primary ways to initialize a Bot instance depending on your use case:

    1. Background Bot (Recommended for long-running processes): Initialize with a specific username and paper key. This runs an independent instance of Keybase that does not interfere with the local Keybase GUI or other logged-in users.
    2. Acting as the local user: Use initFromRunningService() to connect to the existing Keybase service running on the machine. The bot will act as the user currently logged into the Keybase app. No credentials are required for this method, but the Keybase app must be logged in first.
    const Bot = require('keybase-bot')
    
    // Method 1: Background Bot
    async function mainBackground() {
      const bot = new Bot()
      await bot.init('usernameX', 'some paper key...')
      /* ... */
      await bot.deinit()
    }
    
    // Method 2: Act as local user
    async function mainLocal() {
      const bot = new Bot()
      await bot.initFromRunningService()
      /* ... */
      await bot.deinit()
    }
  2. Run keybase-bot using Docker

    master

    You can containerize your bot using the keybaseio/client:nightly-node base image.

    1. Create an index.js that reads credentials from environment variables (KB_USERNAME, KB_PAPERKEY, and optionally KB_TARGET).
    2. Create a package.json including keybase-bot as a dependency.
    3. Use a Dockerfile to set up the working directory and install dependencies.
    4. Build and run the image, passing the required credentials as environment variables via docker run.
    FROM keybaseio/client:nightly-node
    RUN mkdir /app && chown keybase:keybase /app
    WORKDIR /app
    COPY package*.json ./
    RUN npm install
    COPY . .
    CMD node /app/index.js

    Build command:

    docker build -t "keybase-docker-test" .

    Run command:

    docker run \
      --rm \
      -e KB_USERNAME="yourbotname" \
      -e KB_PAPERKEY="your_paper_key" \
      -e KB_TARGET="yourusername" \
      keybase-docker-test
  3. Use environment variables for bot credentials

    master

    To avoid hard-coding sensitive paper keys in your source code, use environment variables. This is a best practice for security and deployment.

    const username = process.env.KB_USERNAME
    const paperkey = process.env.KB_PAPERKEY
    await bot.init(username, paperkey)

    Run your program with:

    KB_USERNAME=foo KB_PAPERKEY="foo bar car" node my-awesome-program.js
  4. Install keybase-bot

    master

    To use keybase-bot, ensure you have Node.js 12 or above and that the Keybase client is installed and running on your machine. You can install the package via npm or yarn.

    npm install keybase-bot
    # or
    yarn add keybase-bot
  5. Generate TypeScript types from Keybase protocol

    master

    The bot's types are generated from the Keybase client's protocol/ definitions to ensure consistency with the API. This process requires cloning the Keybase client repository and having Go and Node.js/Yarn installed.

    Steps to generate types:

    1. Clone the Keybase client repo.
    2. Fetch the keybase package in your GOPATH:
      go get github.com/keybase/client/go/keybase
    3. Install protocol dependencies:
      cd client/protocol
      yarn install
    4. Navigate to the keybase-bot directory and run make to generate the types.

    To remove all generated types, run make clean.

    go get github.com/keybase/client/go/keybase
    cd client/protocol
    yarn install
    cd path/to/keybase-bot
    make
  6. Set up the keybase-bot development environment

    master

    To develop on keybase-bot, ensure you have Node, Yarn, and the Keybase application installed. The project uses EditorConfig, ESLint, Flow, and Prettier for code quality.

    Follow these steps to set up the source code:

    1. Clone the repository.
    2. Install dependencies using yarn.
    3. Make changes in the src/ directory.
    4. Build the bot in watch mode using yarn dev.
    5. Build the bot for production using yarn build (this updates the lib/ directory).
    6. Build the documentation using yarn docs.
    yarn
    yarn dev
    yarn build
    yarn docs
  7. Run tests for keybase-bot

    master

    The project uses Jest for testing. Tests interact with actual Keybase processes and the Keybase server (sending messages, XLM, etc.).

    Prerequisites:

    • Three test Keybase accounts.
    • Two teams.
    • Some Stellar Lumens.

    Setup steps:

    1. Copy __tests__/test.config.example.ts to __tests__/test.config.ts. Warning: Do NOT commit __tests__/test.config.ts to version control as it contains sensitive paper keys.
    2. Edit __tests__/test.config.ts with your actual usernames, paperkeys, and team names.
    3. Run the tests.
    yarn test
  8. Understand Proof Status and States

    master

    Keybase uses proofs to verify identities. When checking a proof, you will encounter two distinct concepts: ProofState and ProofStatus.

    • ProofState: Represents the lifecycle or current standing of a proof (e.g., OK, LOOKING, POSTED, REVOKED, DELETED, UNCHECKED).
    • ProofStatus: Represents the result of an attempt to verify a proof, including specific error categories (e.g., OK, HOST_UNREACHABLE, PERMISSION_DENIED, DNS_ERROR, AUTH_FAILED, HTTP_429, NOT_FOUND).

    Errors in ProofStatus are categorized by severity:

    • 1xx: Retryable soft errors.
    • 2xx: Likely hard errors if repeated.
    • 3xx: Hard final errors.
    export enum ProofState {
      NONE = 'none',
      OK = 'ok',
      TEMP_FAILURE = 'temp_failure',
      PERM_FAILURE = 'perm_failure',
      LOOKING = 'looking',
      SUPERSEDED = 'superseded',
      POSTED = 'posted',
      REVOKED = 'revoked',
      DELETED = 'deleted',
      UNKNOWN_TYPE = 'unknown_type',
      SIG_HINT_MISSING = 'sig_hint_missing',
      UNCHECKED = 'unchecked',
    }
    
    export enum ProofStatus {
      // ... (various error codes like DNS_ERROR, AUTH_FAILED, etc.)
    }
  9. The Bot class

    master

    The Bot class is the primary entry point for the keybase-bot library. It manages the lifecycle of the Keybase service and provides access to specialized clients for different Keybase features.

    Sub-clients available on the bot instance:

    • bot.chat: For interacting with chats and messages.
    • bot.wallet: For managing the Keybase wallet.
    • bot.team: For managing teams.
    • bot.helpers: For general Keybase helper utilities.
    • bot.kvstore: For interacting with the Key-Value store.
  10. Manage Team details and data

    master

    Keybase provides two primary ways to view team information: TeamDetails for a comprehensive view and TeamData for the underlying raw data.

    TeamDetails

    Used for high-level information including members, key generation settings, active invites, and team showcase settings.

    TeamData

    Contains the low-level state of a team, such as:

    • name: The TeamName.
    • chain: The TeamSigChainState.
    • latestSeqnoHint: The latest sequence number.
    • tlfCryptKeys: A mapping of keys to CryptKey[].
    export type TeamDetails = {
      name: string
      members: TeamMembersDetails
      keyGeneration: PerTeamKeyGeneration
      annotatedActiveInvites: {[key: string]: AnnotatedTeamInvite}
      settings: TeamSettings
      showcase: TeamShowcase
    }
    
    export type TeamData = {
      v: number
      frozen: boolean
      tombstoned: boolean
      secretless: boolean
      name: TeamName
      chain: TeamSigChainState
      perTeamKeySeedsUnverified: {[key: string]: PerTeamKeySeedItem}
      readerKeyMasks: {[key: string]: {[key: string]: MaskB64}}
      latestSeqnoHint: Seqno
      cachedAt: Time
      tlfCryptKeys: {[key: string]: CryptKey[] | null}
    }
  11. Handle different message types using MsgContent and MessageBody

    master

    Messages are polymorphic. The MsgContent type acts as a container for various message payloads. To correctly process a message, you must check the type or messageType and then access the corresponding payload.

    Common message types include:

    • TEXT: Contains MessageText (the message body string).
    • ATTACHMENT: Contains MessageAttachment (files/assets).
    • EDIT: Contains MessageEdit (updates to previous text).
    • DELETE: Contains MessageDelete information.
    • SYSTEM: Contains MessageSystem (e.g., ADDEDTOTEAM, NEWCHANNEL).
    • REACTION: Contains MessageReaction data.
    • UNFURL: Contains MessageUnfurl (link previews).
    • FLIP: Contains MessageFlip (coin flip game data).