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:HookRequest,Json,json,form,at,Signed,Unsigned,MacAlg,Verify,HookSecret,CredentialOf,HookCredential,Answer,Handshake,Delivery,HookKindApi,HOOK_KIND_APIS,Events,HandlerKey,Named,Payloads,HookKind,HookMay,HookParts,Hook,HookKindOf,defineHookKind,HookKinds,EventsOf,NoWildcardKeys,PayloadOf,KindHooks@jr2/orchestrator/hooks/github:githubEvents,github@jr2/orchestrator/hooks/gitlab:gitlabEvents,gitlab@jr2/orchestrator/hooks/slack:slackEvents,slack@jr2/orchestrator/hooks/discord:discordEvents,discord@jr2/orchestrator/hooks/webhook:Field,WebhookVerify,webhook
@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.
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:objectbody:Uint8ArrayThe raw body. A
macored25519signature covers these bytes.text:stringThe raw body as UTF-8.
Json
Type.
type Json = null | boolean | number | string | readonly Json[] | { readonly [k: string]: Json };A JSON value: what a kind puts in an answer.
json
Function.
function json(req: HookRequest): unknownThe 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
req(HookRequest)
form
Function.
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
req(HookRequest)
at
Function.
function at(value: unknown, path: string): unknownThe value at a dotted path (sender.login, actions.0.action_id) of a decoded body, or undefined. It reads own properties only.
Parameters
valuepath
Signed
Type.
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):numberThe 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
atis more than 300 s from its clock: 401. A kind cannot change the window.
Unsigned
Type.
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.
type MacAlg = "sha256" | "sha1" | "sha512";The HMAC algorithms that a mac verifier can name.
Verify
Type.
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:
macmac:objectalg:MacAlgsigned:(req: HookRequest) => Signed | Unsigned
Form 2:
ed25519ed25519:objectsigned:(req: HookRequest) => Signed | Unsigned
Form 3:
tokentoken:objectheader:string
HookSecret
Type.
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.
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.
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:
secretsecret:HookSecret
Form 2:
publicKeypublicKey:string
Answer
Type.
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
Handshake
Type.
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
handshake:Answer
Delivery
Type.
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:stringThe event key. GitHub:
pull_request_review.submitted.id:stringThe delivery id. The door's repeat check uses it AND the digest of the body.
payload:unknownThe decoded body. The signature covers it. The door parses it with the kind's schema for
key(seeevents), and a handler gets the schema's output.onBehalfOf(optional):stringThe 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 thereplytexts, cuts them tomaxText, and calls the kind'sanswer. The status is 200.
HookKindApi
Type.
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.
const HOOK_KIND_APIS: readonly HookKindApi[]The versions of the interface that this copy of @jr2/orchestrator/hooks knows.
Events
Type.
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-refusedline 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.looseObjectfor 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'sstate) is a string, not an enum. - A key that ends in
.*is the schema of each key with that prefix:"block_actions.*"typesblock_actions.approveandblock_actions.reject. An exact key comes first, then the longest prefix.
HandlerKey
Type.
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.
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.
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.
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. Only1exists.id: the key of thehooksof 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 withreadBy: "person". The door gives the joined text, already cut tomaxText. The kind escapes it. A kind with noanswercannot givereadBy: "person": the type ofreadrefuses it (defineHookKind).maxText: the service's limit on the length of the text (Discord: 2000).posts: the url prefixes ofAnswer.then.jr2 upadds them to the Instance Effector's fence for each Hook of this kind (ADR-0068). The door refuses athento another url.
Fields
api:HookKindApiid:Idevents:Everify:Vread:(req: HookRequest) => Handshake | Deliveryanswer(optional):(text: string, delivery: Delivery) => AnswermaxText(optional):numberposts(optional):readonly `https://${string}/`[]
HookMay
Type.
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.
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
kind:Kcredential:HookCredentialmay:HookMay
Hook
Type.
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.
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
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
kindapi:HookKindApiid:Idevents:Everify:Vread:(req: HookRequest) => Handshake | Deliveryanswer:(text: string, delivery: Delivery) => AnswermaxText(optional):numberposts(optional):readonly `https://${string}/`[]
Overload 2
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
kindid:Idapi:HookKindApievents:Everify:Vread:(req: HookRequest) => Handshake | (Delivery & { readonly readBy?: "service"; })
HookKinds
Type.
Overload 1
interface HookKinds {}Each kind module adds its id and its kind here by declaration merging.
Overload 2
interface HookKinds {
github: typeof github;
}Fields
github:typeof github
Overload 3
interface HookKinds {
gitlab: typeof gitlab;
}Fields
gitlab:typeof gitlab
Overload 4
interface HookKinds {
slack: typeof slack;
}Fields
slack:typeof slack
Overload 5
interface HookKinds {
discord: typeof discord;
}Fields
discord:typeof discord
EventsOf
Type.
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.
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.
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.
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 githubgitlab(optional):typeof gitlabslack(optional):typeof slackdiscord(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.
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.
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
pingevent (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.
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.
const gitlab: HookKindOf<…>Type: HookKindOf.
A GitLab project or group webhook.
- verifier:
token, the secret token inX-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 isobject_attributes.noteable_typefor anote, and elseobject_attributes.action, thenobject_attributes.status:merge_request.approved,note.MergeRequest,pipeline.success. - delivery id:
Idempotency-Key(the same on a retry), elseX-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.
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.
const slack: HookKindOf<…>Type: HookKindOf.
- verifier:
mac, HMAC-SHA256 ofv0:<X-Slack-Request-Timestamp>:<raw body>,X-Slack-Signature: v0=<hex>. The signature covers the timestamp, so the kind gives it asat, and the door's 300 s window applies (Slack asks for 5 minutes). - handshake:
url_verificationgets{ 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_idfor an event,trigger_idfor a command or a click. (Slack's docs do not say that atrigger_idis 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_urlas the answer'sthen. - 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 aresponse_urlpost.)
@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.
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.
const discord: HookKindOf<…>Type: HookKindOf.
- verifier:
ed25519over<X-Signature-Timestamp><raw body>,X-Signature-Ed25519in hex, checked against the application's PUBLIC key in the Orchestrator. The signature covers the timestamp, so the kind gives it asat. Discord states no window; the door's 300 s window applies to each signedat, 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 keyinteraction.<type>, which has no schema, so it reaches nothing. - delivery id: the interaction's
id.onBehalfOf:member.user.id, oruser.idin 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.
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:
headerheader:string
Form 2:
jsonjson:string
WebhookVerify
Type.
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:
macmac:objectheader:stringThe header of the signature (lowercase).
alg(optional):MacAlgsha256when it is not given.prefix(optional):stringThe text before the signature in the header's value, such as
sha256=.encoding(optional):"hex" | "base64"hexwhen it is not given.
Form 2:
tokentoken:objectheader:string
webhook
Function.
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 (Eventsin@jr2/orchestrator/hooks).verify:macover the raw body (the header, its prefix, the algorithm, the encoding), ortokenin 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
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
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: fromzodz.output: fromzod