Agora

Crypto 1.x is a release candidate. npm's latest tag still installs 0.x, so install these docs' version from the rc tag:

npm i @adonis-agora/crypto@rc
node ace configure @adonis-agora/crypto

The same goes for every @adonis-agora/* package these docs install: add @rc, and where a page says node ace add, install with @rc first and then run node ace configure. On 0.x? Read the 0.x docs.

Getting started

Install the package, choose where keys live, and create the first key.

node ace add @adonis-agora/crypto

The installer registers the provider and the commands, publishes config/crypto.ts, and writes a migration for the three tables this package owns (crypto_keys, crypto_key_versions, crypto_audit). The provider creates them at boot too (autoCreateSchema: true), so a first local run needs no migration.

It also writes add_crypto_audit_filter_indexes: one index per audit filter (key, operation, result, actor), so the console's Audit page and GET /v1/audit stay fast on a long trail. On Postgres it builds them CONCURRENTLY, so writes go on while it runs.

Audit indexes on an existing install

Installed before these indexes existed? Run the migration once:

node ace make:migration add_crypto_audit_filter_indexes
database/migrations/xxxx_add_crypto_audit_filter_indexes.ts
import { BaseSchema } from '@adonisjs/lucid/schema'

/**
 * Indexes for the console's Audit page and the tenant 'GET /v1/audit': each filter (key,
 * operation, result, actor) seeks straight to its newest rows and pages by '(at, id)' instead of
 * reading every row of the app. Run it once on an existing install; new rows need nothing else.
 *
 * On Postgres the indexes are built CONCURRENTLY (writes go on while they build, which is why this
 * migration runs outside a transaction).
 */
/**
 * The database schema the table lives in: the same value as 'schema' in the crypto store config.
 * Leave it undefined to use the connection's current schema. On MySQL a schema is a database.
 */
const schema: string | undefined = undefined

const INDEXES: Array<[string, string[]]> = [
  ['crypto_audit_app_at_id_idx', ['app', 'at', 'id']],
  ['crypto_audit_app_key_at_idx', ['app', 'key_name', 'at', 'id']],
  ['crypto_audit_app_operation_at_idx', ['app', 'operation', 'at', 'id']],
  ['crypto_audit_app_result_at_idx', ['app', 'result', 'at', 'id']],
  ['crypto_audit_app_actor_at_idx', ['app', 'actor', 'at', 'id']],
]

export default class extends BaseSchema {
  static disableTransactions = true

  protected tableName = 'crypto_audit'

  async up() {
    const table = schema ? schema + '.' + this.tableName : this.tableName
    if (this.db.dialect.name === 'postgres') {
      this.defer(async (db) => {
        for (const [name, columns] of INDEXES) {
          await db.rawQuery(
            'CREATE INDEX CONCURRENTLY IF NOT EXISTS ?? ON ?? (' + columns.map(() => '??').join(', ') + ')',
            [name, table, ...columns]
          )
        }
      })
      return
    }
    this.builder().alterTable(this.tableName, (t) => {
      for (const [name, columns] of INDEXES) t.index(columns, name)
    })
  }

  async down() {
    if (this.db.dialect.name === 'postgres') {
      this.defer(async (db) => {
        for (const [name] of INDEXES) {
          await db.rawQuery('DROP INDEX CONCURRENTLY IF EXISTS ??', [schema ? schema + '.' + name : name])
        }
      })
      return
    }
    this.builder().alterTable(this.tableName, (t) => {
      for (const [name, columns] of INDEXES) t.dropIndex(columns, name)
    })
  }

  /** The schema builder, pointed at 'schema' when it is set. */
  private builder() {
    return schema ? this.schema.withSchema(schema) : this.schema
  }
}

Set schema to the value of schema in config/crypto.ts when you use one.

A schema of its own

On Postgres (or a MySQL database), keep the crypto tables out of public:

config/crypto.ts
export default defineConfig({
  topology: 'control-plane',
  verifyTenant,
  schema: 'crypto',
})

The schema is written into every statement — DDL and queries alike name the table as "crypto"."crypto_keys" — so nothing depends on the connection's search_path. That is what makes it safe behind PgBouncer in transaction mode, where a SET search_path would not survive the connection swap. Create the schema yourself (CREATE SCHEMA crypto); crypto only uses it, and it refuses SQLite, where a schema is a file, not a namespace.

Where the keys live

config/crypto.ts
import { defineConfig, stores } from '@adonis-agora/crypto'

export default defineConfig({
  topology: 'standalone',
  app: 'streaming',
  // The default: Postgres, MySQL or SQLite through Lucid.
  store: stores.lucid(),
  // For a throwaway local app, keep everything in process memory:
  // store: stores.memory(),
})

Only sealed key material reaches the store. What seals it is the root keyring:

  1. crypto.keys in this file (newest first), when this package should own the root keys;
  2. otherwise the app's own encryption service (config/encryption.ts and APP_KEY) — the default;
  3. otherwise APP_KEY alone.

A cloud KMS can be the root instead: see KMS.

config/crypto.ts (root keys owned by this package)
export default defineConfig({
  topology: 'standalone',
  app: 'streaming',
  crypto: {
    // The first key seals new material; every key opens. Rotate by prepending a new one.
    keys: [env.get('CRYPTO_ROOT_KEY')],
  },
})

The first key

node ace crypto:keys:create media --type aes256-gcm --description "media URLs"
node ace crypto:keys:list
import crypto from '@adonis-agora/crypto/services/main'

const { ciphertext } = await crypto.encrypt({ key: 'media', plaintext: 'https://cdn/x.mp4' })
const { plaintext, version } = await crypto.decrypt({ key: 'media', ciphertext })

The ciphertext is self-describing (agora:ct1:media:1:…): it names the key and the version that sealed it, so decrypt needs nothing else, and a later rotate does not break it.

A central server

On the server, switch topology to control-plane and add a verifier; on every app, switch to tenant and point it at the server. Nothing else in the app changes.

config/crypto.ts (server)
export default defineConfig({
  topology: 'control-plane',
  verifyTenant: authkitTenantVerifier({ issuer: env.get('AUTHKIT_ISSUER'), resource: 'urn:agora:crypto' }),
})
config/crypto.ts (app)
export default defineConfig({
  topology: 'tenant',
  tenant: {
    url: env.get('CRYPTO_URL'),
    partition: 'streaming',
    token: authkitTenantToken({
      issuer: env.get('AUTHKIT_ISSUER'),
      clientId: env.get('AUTHKIT_CLIENT_ID'),
      clientSecret: env.get('AUTHKIT_CLIENT_SECRET'),
      resource: 'urn:agora:crypto',
    }),
  },
})

The tenant's first boot asks the server whoami and logs the answer; a wrong token or URL is a warning, not a boot failure, so a deploy during an outage still starts.

Health check

node ace agora:doctor --lib crypto --deep

See Doctor for what each check looks at.

On this page

Partner

Your product as the official integration for Crypto, right here.

Become a partner →