Skip to content

Hook kinds ​

@jr2/orchestrator/hooks is the interface of a Hook kind, and the kinds that jr2 ships. jr2.config.ts imports a kind to declare a Hook, and a workflow module imports a kind's types for the handlers of a Gate slot or a Source. It is part of @jr2/orchestrator, so an Instance installs nothing more. A kind from another package has a peer dependency on @jr2/orchestrator and states api: 1. Each group of this page is one module that you import.

Contents ​

@jr2/orchestrator/hooks ​

The interface between the door of a Hook and a kind: defineHookKind, which makes a kind, the types of a kind, the helpers that read a request, and HookKinds, to which each kind adds its id and its payloads.

Each name in this group is declared in @jr2/orchestrator/src/hook-kinds/index.ts.

HookRequest ​

Type.

ts
type HookRequest = {
  readonly headers: { readonly [name: string]: string | undefined };
  readonly body: Uint8Array;
  readonly text: string;
};

One delivery, as the door got it. All of it is data. Header names are lowercase.

For a kind with a token verifier, headers does not hold the token's header: the door removes it before it calls the kind. For mac and ed25519, no part of the request is secret: a signature cannot make another signature.

Fields

  • headers: object

  • body: Uint8Array

    The raw body. A mac or ed25519 signature covers these bytes.

  • text: string

    The raw body as UTF-8.

Json ​

Type.

ts
type Json = null | boolean | number | string | readonly Json[] | { readonly [k: string]: Json };

A JSON value: what a kind puts in an answer.

json ​

Function.

ts
function json(req: HookRequest): unknown

The body as JSON. It throws when the body is not JSON. A throw from read is a 400, and the hook log keeps the error.

Parameters

form ​

Function.

ts
function form(req: HookRequest): { readonly [field: string]: string | undefined }

The body as application/x-www-form-urlencoded fields. When a field occurs more than one time, the first value is the field's value.

Parameters

at ​

Function.

ts
function at(value: unknown, path: string): unknown

The value at a dotted path (sender.login, actions.0.action_id) of a decoded body, or undefined. It reads own properties only.

Parameters

  • value
  • path

Signed ​

Type.

ts
type Signed = {
  readonly bytes: readonly (string | Uint8Array)[];
  readonly signature: { readonly hex: string } | { readonly base64: string };
  readonly at?: number;
};

What the service signed, from one request.

The door makes the checks. For mac, it first checks at against its clock, then sends the bytes, the signature, the algorithm and the NAME of the Hook's secret to the Instance Effector, which answers "match" or "no match" (ADR-0068). For ed25519, it checks at, then the signature against the Hook's public key, in the Orchestrator.

Fields

  • bytes: readonly (string | Uint8Array)[]

    The bytes that the service signed, in sequence. The door joins them. A string is UTF-8. GitHub: [req.body]. Slack: ["v0:", timestamp, ":", req.body].

  • signature: { readonly hex: string; } | { readonly base64: string; }

    The signature, with no prefix (sha256=, v0=): the kind removes the prefix.

  • at (optional): number

    The service's time of the delivery, in seconds since the epoch. Give it ONLY when the signature covers it (Slack, Discord). The door refuses a delivery whose at is more than 300 s from its clock: 401. A kind cannot change the window.

Unsigned ​

Type.

ts
type Unsigned = { readonly unsigned: string };

The request does not hold what the verifier needs. The door answers 401 and logs unsigned.

Fields

  • unsigned: string

MacAlg ​

Type.

ts
type MacAlg = "sha256" | "sha1" | "sha512";

The HMAC algorithms that a mac verifier can name.

Verify ​

Type.

ts
type Verify =
  | {
      readonly mac: {
        readonly alg: MacAlg;
        readonly signed: (req: HookRequest) => Signed | Unsigned;
      };
    }
  | { readonly ed25519: { readonly signed: (req: HookRequest) => Signed | Unsigned } }
  | { readonly token: { readonly header: string } };

How the service signs. One of three.

Forms: it is one of these objects.

  • Form 1: mac

    • mac: object

      • alg: MacAlg
      • signed: (req: HookRequest) => Signed | Unsigned
  • Form 2: ed25519

    • ed25519: object

      • signed: (req: HookRequest) => Signed | Unsigned
  • Form 3: token

    • token: object

      • header: string

HookSecret ​

Type.

ts
type HookSecret = { readonly secret: string };

A named secret: the value of secret("NAME") from @jr2/orchestrator. The config holds the name only. The value is in the Instance Effector (mac), or its digest is in the Orchestrator (token).

Fields

  • secret: string

CredentialOf ​

Type.

ts
type CredentialOf<V extends Verify> = V extends { readonly ed25519: unknown }
  ? { readonly publicKey: string }
  : { readonly secret: HookSecret };

What the Hook's config gives for each verifier. The kind never gets it.

HookCredential ​

Type.

ts
type HookCredential = { readonly secret: HookSecret } | { readonly publicKey: string };

The credential of a Hook, for each of the three verifiers.

Forms: it is one of these objects.

  • Form 1: secret

  • Form 2: publicKey

    • publicKey: string

Answer ​

Type.

ts
type Answer = {
  readonly body: Json;
  readonly then?: { readonly post: `https://${string}`; readonly json: Json };
};

An answer that the kind writes. Its status is always 200: the door owns every other status. body: an object or an array is JSON, a string is text/plain, null is an empty body. then: one POST that the door makes AFTER the answer, through the Instance Effector's http, with no secret, one time (the response_url of a Slack click). Its url must start with one of the kind's posts. A failed post is a line in the hook log.

Fields

  • body: Json

  • then (optional): object

    • post: `https://${string}`
    • json: Json

Handshake ​

Type.

ts
type Handshake = { readonly handshake: Answer };

The service's handshake (Slack url_verification, Discord PING, GitHub ping). It comes after the verifier and gets this answer. It reaches no handler, and the hook log keeps it as handshake.

Fields

Delivery ​

Type.

ts
type Delivery = {
  readonly key: string;
  readonly id: string;
  readonly payload: unknown;
  readonly onBehalfOf?: string;
  readonly readBy?: "service" | "person";
};

One delivery, which the door gives to the Gates and the Sources whose handlers hear its kind and key. The kind's events gives the schema for each key. A key that events does not name is still a delivery: the door does not parse it, and no handler can hear it, so it reaches nothing.

Fields

  • key: string

    The event key. GitHub: pull_request_review.submitted.

  • id: string

    The delivery id. The door's repeat check uses it AND the digest of the body.

  • payload: unknown

    The decoded body. The signature covers it. The door parses it with the kind's schema for key (see events), and a handler gets the schema's output.

  • onBehalfOf (optional): string

    The party that the service says acted. The signature covers it, so jr2 marks it checked.

  • readBy (optional): "service" | "person"

    Who reads the answer. "service" (the default): the answer is the outcome JSON with the status that ADR-0011 gives (429, 503). "person" (a chat command or a click): the door joins the reply texts, cuts them to maxText, and calls the kind's answer. The status is 200.

HookKindApi ​

Type.

ts
type HookKindApi = 1;

The version of this interface. jr2 1.x calls each kind of api: 1 as this module says.

HOOK_KIND_APIS ​

Constant.

ts
const HOOK_KIND_APIS: readonly HookKindApi[]

The versions of the interface that this copy of @jr2/orchestrator/hooks knows.

Events ​

Type.

ts
type Events = { readonly [key: string]: z.ZodType };

The schema of each event key: { "pull_request_review.submitted": z.looseObject({ … }) }.

  • The door parses the payload of a delivery with the schema of its key, after the verifier and before the fan-out. A failed parse reaches no handler: the hook log keeps a payload-refused line with zod's issues, and the answer names the kind and the key. The status is 200, because a second try fails in the same way.
  • Use z.looseObject for each object. A loose object keeps the fields that it does not name, so a new field from the service breaks nothing. A named field that is missing, or that has the wrong type, fails the parse. Name only the fields that handlers need. A value that the service can extend (a review's state) is a string, not an enum.
  • A key that ends in .* is the schema of each key with that prefix: "block_actions.*" types block_actions.approve and block_actions.reject. An exact key comes first, then the longest prefix.

HandlerKey ​

Type.

ts
type HandlerKey<K> = K extends `${infer P}.*` ? `${P}.${string}` : K;

A key of events as a handler's key: "block_actions.*" → `block_actions.${string}`.

Named ​

Type.

ts
type Named<T> = T extends readonly unknown[]
  ? { readonly [I in keyof T]: Named<T[I]> }
  : T extends object
    ? { readonly [K in keyof T as string extends K ? never : K]: Named<T[K]> }
    : T;

The schema's output with only its named fields. The output of a loose object also has [field: string]: unknown. The fields that it does not name stay in the value, but this type removes the index signature, so a handler cannot read a field that its schema does not name.

Payloads ​

Type.

ts
type Payloads<E extends Events> = {
  readonly [K in keyof E & string as HandlerKey<K>]: Named<z.output<E[K]>>;
};

The payload type of each handler key of events.

HookKind ​

Type.

ts
type HookKind<Id extends string = string, E extends Events = Events, V extends Verify = Verify> = {
  readonly api: HookKindApi;
  readonly id: Id;
  readonly events: E;
  readonly verify: V;
  readonly read: (req: HookRequest) => Handshake | Delivery;
  readonly answer?: (text: string, delivery: Delivery) => Answer;
  readonly maxText?: number;
  readonly posts?: readonly `https://${string}/`[];
};

A Hook kind: one outside service's protocol.

  • api: the version of this interface that the kind was written for. Only 1 exists.
  • id: the key of the hooks of a Gate or a Source. One id is one kind in an Assembly. Lowercase letters, digits and -, and it starts with a letter.
  • events: a zod schema for each event key that a handler can hear (Events).
  • verify: one of the three verifiers, and what the service signed.
  • read: the verified request, as a handshake or a delivery. A throw is 400, and the hook log keeps the error.
  • answer: the envelope of the text for a delivery with readBy: "person". The door gives the joined text, already cut to maxText. The kind escapes it. A kind with no answer cannot give readBy: "person": the type of read refuses it (defineHookKind).
  • maxText: the service's limit on the length of the text (Discord: 2000).
  • posts: the url prefixes of Answer.then. jr2 up adds them to the Instance Effector's fence for each Hook of this kind (ADR-0068). The door refuses a then to another url.

Fields

  • api: HookKindApi
  • id: Id
  • events: E
  • verify: V
  • read: (req: HookRequest) => Handshake | Delivery
  • answer (optional): (text: string, delivery: Delivery) => Answer
  • maxText (optional): number
  • posts (optional): readonly `https://${string}/`[]

HookMay ​

Type.

ts
type HookMay = { readonly answer: "all" | readonly string[] };

The Workflows whose Gates a Hook may answer (ADR-0078). The default is "all". A Hook never starts a run.

Fields

  • answer: "all" | readonly string[]

HookParts ​

Type.

ts
type HookParts<K extends HookKind = HookKind> = {
  readonly kind: K;
  readonly credential: HookCredential;
  readonly may: HookMay;
};

The parts of a Hook, which only the door reads.

Fields

Hook ​

Type.

ts
type Hook<K extends HookKind = HookKind> = { readonly [HOOK]: HookParts<K> };

A Hook: a kind, a credential and may. It is the value of one entry of hooks in jr2.config.ts, and the entry's key is its name, the last segment of POST /hooks/:name. Only the door reads it.

Fields

  • [HOOK]: HookParts<K>

HookKindOf ​

Type.

ts
type HookKindOf<Id extends string, E extends Events, V extends Verify> = HookKind<Id, E, V> &
  ((hook: CredentialOf<V> & { readonly may?: HookMay }) => Hook<HookKind<Id, E, V>>);

A kind is also the constructor of its Hooks: github({ secret: secret("GH_HOOK"), may }).

defineHookKind ​

Function.

Overload 1 ​

ts
function defineHookKind<
  const Id extends string,
  const E extends Events,
  const V extends Verify,
>(
  kind: HookKind<Id, E, V> & { readonly answer: NonNullable<HookKind["answer"]> },
): HookKindOf<Id, E, V>

Define a kind. jr2 makes the constructor, so the credential goes from the config to the door and never through code of the kind.

It throws on an api that it does not know, an id that is not lowercase, an events entry that is not a schema, a verifier that is not one of the three, a posts entry that is not an https:// url that ends in /, and a maxText that is not a positive integer. Two different kinds with one id fail the typecheck (HookKinds) and jr2 up.

Two overloads: a kind with answer can give readBy: "person"; a kind with no answer cannot.

Parameters

  • kind

    • api: HookKindApi
    • id: Id
    • events: E
    • verify: V
    • read: (req: HookRequest) => Handshake | Delivery
    • answer: (text: string, delivery: Delivery) => Answer
    • maxText (optional): number
    • posts (optional): readonly `https://${string}/`[]

Overload 2 ​

ts
function defineHookKind<
  const Id extends string,
  const E extends Events,
  const V extends Verify,
>(
  kind: Omit<HookKind<Id, E, V>, "read" | "answer" | "maxText" | "posts"> & {
    readonly read: (req: HookRequest) => Handshake | (Delivery & { readonly readBy?: "service" });
  },
): HookKindOf<Id, E, V>

Parameters

  • kind

    • id: Id
    • api: HookKindApi
    • events: E
    • verify: V
    • read: (req: HookRequest) => Handshake | (Delivery & { readonly readBy?: "service"; })

HookKinds ​

Type.

Overload 1 ​

ts
interface HookKinds {}

Each kind module adds its id and its kind here by declaration merging.

Overload 2 ​

ts
interface HookKinds {
    github: typeof github;
  }

Fields

  • github: typeof github

Overload 3 ​

ts
interface HookKinds {
    gitlab: typeof gitlab;
  }

Fields

  • gitlab: typeof gitlab

Overload 4 ​

ts
interface HookKinds {
    slack: typeof slack;
  }

Fields

  • slack: typeof slack

Overload 5 ​

ts
interface HookKinds {
    discord: typeof discord;
  }

Fields

  • discord: typeof discord

EventsOf ​

Type.

ts
type EventsOf<K> = K extends HookKind<string, infer E, Verify> ? Payloads<E> : never;

The payload map of a kind: handler key → the output of its schema.

NoWildcardKeys ​

Type.

ts
type NoWildcardKeys<K> =
  K extends HookKind<string, infer E, Verify>
    ? { readonly [Key in keyof E & string as Key extends `${string}*${string}` ? Key : never]?: never }
    : never;

A kind's events keys with *, which take no handler: the door matches a key exactly (ADR-0011).

PayloadOf ​

Type.

ts
type PayloadOf<Id extends keyof HookKinds, Key extends keyof EventsOf<HookKinds[Id]>> = EventsOf<
  HookKinds[Id]
>[Key];

The payload of one handler key of a kind in HookKinds: PayloadOf<"github", "issue_comment.created">. A forge part types its handlers with it.

KindHooks ​

Type.

ts
type KindHooks<In, Out> = {
  readonly [Id in keyof HookKinds as HookKinds[Id] extends { readonly id: Id } ? Id : never]?: {
    readonly [Key in keyof EventsOf<HookKinds[Id]>]?: (
      d: In & { readonly payload: EventsOf<HookKinds[Id]>[Key] },
    ) => Out;
  } & NoWildcardKeys<HookKinds[Id]>;
};

Handlers by kind id, then by event key. An entry of HookKinds whose key is not its kind's id is left out, so no handler is keyed by a name that the door never matches. In is what the Gate or the Source gives a handler beside payload; Out is what the handler gives. A key that the kind's payloads do not name is an excess property: it does not compile. A key that holds * does not compile (NoWildcardKeys).

Fields

  • github (optional): typeof github
  • gitlab (optional): typeof gitlab
  • slack (optional): typeof slack
  • discord (optional): typeof discord

@jr2/orchestrator/hooks/github ​

The kind of GitHub. It verifies with mac, over the raw body.

Each name in this group is declared in @jr2/orchestrator/src/hook-kinds/github.ts.

githubEvents ​

Constant.

ts
const githubEvents: { "pull_request_review.submitted": …; "issue_comment.created": …; "check_suite.completed": … }

The schema of each event key. Each names only the fields that handlers read; a loose object keeps the rest. A value that GitHub can extend (a review's state) is a string, not an enum, so a new value fails no parse.

github ​

Constant.

ts
const github: HookKindOf<…>

Type: HookKindOf.

A GitHub repository, organization or App webhook, with the content type application/json. (A webhook with the content type application/x-www-form-urlencoded gets 400.)

  • verifier: mac, HMAC-SHA256 of the raw body, X-Hub-Signature-256: sha256=<hex>.
  • handshake: the ping event (sent when the webhook is made) gets an empty 200.
  • event key: <X-GitHub-Event>.<action>, or <X-GitHub-Event> when the body has no action.
  • delivery id: X-GitHub-Delivery. onBehalfOf: sender.login.
  • answer: the outcome (the default). No person reads it.

@jr2/orchestrator/hooks/gitlab ​

The kind of GitLab. It verifies with token, in the header X-Gitlab-Token.

Each name in this group is declared in @jr2/orchestrator/src/hook-kinds/gitlab.ts.

gitlabEvents ​

Constant.

ts
const gitlabEvents: { "merge_request.approved": …; "note.MergeRequest": …; "pipeline.success": …; "pipeline.failed": … }

The schema of each event key: the fields that handlers read, in loose objects.

gitlab ​

Constant.

ts
const gitlab: HookKindOf<…>

Type: HookKindOf.

A GitLab project or group webhook.

  • verifier: token, the secret token in X-Gitlab-Token.
  • handshake: none. A "Test" delivery from GitLab's settings is an ordinary delivery.
  • event key: <object_kind>.<the second part>, or <object_kind> when it has no second part. The second part is object_attributes.noteable_type for a note, and else object_attributes.action, then object_attributes.status: merge_request.approved, note.MergeRequest, pipeline.success.
  • delivery id: Idempotency-Key (the same on a retry), else X-Gitlab-Event-UUID. (From GitLab's docs; not checked against a real delivery.)
  • onBehalfOf: user.username.
  • answer: the outcome (the default). No person reads it.

@jr2/orchestrator/hooks/slack ​

The kind of one Slack app: its slash commands, its clicks and its Events API. It verifies with mac, over the signed time and the body.

Each name in this group is declared in @jr2/orchestrator/src/hook-kinds/slack.ts.

slackEvents ​

Constant.

ts
const slackEvents: { "slash_command.*": …; "block_actions.*": …; "event_callback.app_mention": … }

The schema of each event key. A key with .* covers a family: the command or the action id is part of the key, so one schema types block_actions.approve and block_actions.reject.

slack ​

Constant.

ts
const slack: HookKindOf<…>

Type: HookKindOf.

  • verifier: mac, HMAC-SHA256 of v0:<X-Slack-Request-Timestamp>:<raw body>, X-Slack-Signature: v0=<hex>. The signature covers the timestamp, so the kind gives it as at, and the door's 300 s window applies (Slack asks for 5 minutes).
  • handshake: url_verification gets { challenge }. The door verifies it first. (Slack's docs do not say that Slack signs it; check it at the first real setup.)
  • body: a command is a form; a click is a form with JSON in payload; an event is JSON.
  • event keys: slash_command./jr2, block_actions.<action_id>, event_callback.<event.type>.
  • delivery id: event_id for an event, trigger_id for a command or a click. (Slack's docs do not say that a trigger_id is unique for each request; the door's repeat check also uses the digest of the body.)
  • onBehalfOf: the Slack user id, never a display name.
  • who reads the answer: a person for a command or a click; Slack for an event (so a 503 stays a 503, and Slack sends the event again).
  • answer: ephemeral text. The answer to a click can only be an empty 200 (Block Kit), so the text goes to the click's response_url as the answer's then.
  • text limit: 4000 characters, the length that Slack's docs advise for a message's text. (Not checked for the answer to a command or a response_url post.)

@jr2/orchestrator/hooks/discord ​

The kind of a Discord application's Interactions Endpoint URL. It verifies with ed25519, over the signed time and the body.

Each name in this group is declared in @jr2/orchestrator/src/hook-kinds/discord.ts.

discordEvents ​

Constant.

ts
const discordEvents: { "application_command.*": …; message_component: … }

The schema of each event key. A command's name is part of its key, so .* covers them all.

discord ​

Constant.

ts
const discord: HookKindOf<…>

Type: HookKindOf.

  • verifier: ed25519 over <X-Signature-Timestamp><raw body>, X-Signature-Ed25519 in hex, checked against the application's PUBLIC key in the Orchestrator. The signature covers the timestamp, so the kind gives it as at. Discord states no window; the door's 300 s window applies to each signed at, so it applies here too.
  • handshake: PING (type 1) gets { type: 1 } (PONG).
  • event keys: application_command.<data.name> (type 2), message_component (type 3). Another type (an autocomplete, a modal) gets the key interaction.<type>, which has no schema, so it reaches nothing.
  • delivery id: the interaction's id. onBehalfOf: member.user.id, or user.id in a direct message. (Discord's docs do not say that Discord sends an interaction again.)
  • who reads the answer: a person, always.
  • answer: { type: 4, data: { content, flags: 64 } }, an ephemeral message. Discord shows markdown, not HTML, so the text needs no escape. Text limit: 2000 characters.

@jr2/orchestrator/hooks/webhook ​

webhook() makes a kind from data, for a service that has no kind: a verifier over the raw body, the event key, the delivery id, onBehalfOf, and a schema for each event.

Each name in this group is declared in @jr2/orchestrator/src/hook-kinds/webhook.ts.

Field ​

Type.

ts
type Field = { readonly header: string } | { readonly json: string };

Where a value is in a delivery: a header (lowercase), or a dotted path in the JSON body.

Forms: it is one of these objects.

  • Form 1: header

    • header: string
  • Form 2: json

    • json: string

WebhookVerify ​

Type.

ts
type WebhookVerify =
  | {
      readonly mac: {
        readonly header: string;
        readonly alg?: MacAlg;
        readonly prefix?: string;
        readonly encoding?: "hex" | "base64";
      };
    }
  | { readonly token: { readonly header: string } };

How the general kind verifies. mac is over the raw body only.

Forms: it is one of these objects.

  • Form 1: mac

    • mac: object

      • header: string

        The header of the signature (lowercase).

      • alg (optional): MacAlg

        sha256 when it is not given.

      • prefix (optional): string

        The text before the signature in the header's value, such as sha256=.

      • encoding (optional): "hex" | "base64"

        hex when it is not given.

  • Form 2: token

    • token: object

      • header: string

webhook ​

Function.

ts
function webhook<
  const Id extends string,
  const E extends Events,
  const W extends WebhookVerify,
>(
  spec: {
    readonly id: Id;
    readonly events: E;
    readonly verify: W;
    readonly key: Field | { readonly name: Field; readonly action?: Field };
    readonly delivery: Field;
    readonly onBehalfOf?: Field;
  },
): HookKindOf<Id, E, VerifyOf<W>>

A kind from data.

  • id: the kind's id. The Instance chooses it; it must not be the id of another kind.
  • events: a zod schema for each event key that a handler can hear. The door parses with it, as for each kind (Events in @jr2/orchestrator/hooks).
  • verify: mac over the raw body (the header, its prefix, the algorithm, the encoding), or token in a header.
  • key: the event key, from one field; or { name, action }, which gives <name>.<action>, or <name> when the delivery has no action.
  • delivery: the delivery id. onBehalfOf: optional.

The answer is the outcome JSON.

Parameters

  • spec

    • id: Id
    • events: E
    • verify: W
    • key: Field | { readonly name: Field; readonly action?: Field; }
    • delivery: Field
    • onBehalfOf (optional): Field

Types these signatures name ​

A signature above names these types, or a type here names them. They are not exports of @jr2/orchestrator, so a workflow module does not import them by name. With them, each kit type that this page shows has a definition on a Reference page.

VerifyOf ​

ts
type VerifyOf<W extends WebhookVerify> = W extends { readonly mac: unknown }
  ? Extract<Verify, { readonly mac: unknown }>
  : Extract<Verify, { readonly token: unknown }>;

These names come from a dependency:

  • z.ZodType: from zod
  • z.output: from zod

The docs of Kit version 0.8.0. Each page is also at its .md URL.