Write a Hook kind
Write a Hook kind for an outside service that jr2 ships no kind for, and that webhook() cannot read.
webhook() reads a service that sends JSON and signs only the raw body. Write a kind with defineHookKind() when the service does one of these:
- It signs more than the body, such as a time and the body.
- It sends a body that is not JSON, such as a form.
- It sends a handshake that needs an answer.
- A person reads the answer, as in a chat command.
The example is a kind for Stripe. Stripe signs <t>.<raw body> with the signing secret of the endpoint, and sends the time t and the signature in the header Stripe-Signature: t=<seconds>,v1=<hex>. The type of the event is the event key, and the id of the event is the id of the delivery.
The interface of a kind is @jr2/orchestrator/hooks. It is part of @jr2/orchestrator, so your Instance installs nothing more.
Write the kind
Save the kind as hooks/stripe.ts, beside workflows/. A kind is not a Workflow, so it does not go in workflows/:
import { z } from "zod";
import { defineHookKind, json } from "@jr2/orchestrator/hooks";
// The payload of each event key that a handler hears. Name only the fields that the handlers read:
// a loose object keeps the other fields, so a new field from Stripe breaks nothing.
const invoice = z.looseObject({
data: z.looseObject({ object: z.looseObject({ id: z.string(), customer: z.string() }) }),
});
export const stripeEvents = {
"invoice.paid": invoice,
"invoice.payment_failed": invoice,
};
export const stripe = defineHookKind({
api: 1,
id: "stripe",
events: stripeEvents,
verify: {
mac: {
alg: "sha256",
// Stripe-Signature: t=<seconds>,v1=<hex>. Stripe signs "<t>.<raw body>". The door checks t
// against its clock, and the Instance Effector checks the HMAC.
signed: (req) => {
const fields = (req.headers["stripe-signature"] ?? "").split(",").map((f) => f.split("="));
const t = fields.find(([name]) => name === "t")?.[1];
const v1 = fields.find(([name]) => name === "v1")?.[1];
if (!t || !/^\d+$/.test(t) || !v1) return { unsigned: "no t and v1 in the Stripe-Signature header" };
return { bytes: [t, ".", req.body], signature: { hex: v1 }, at: Number(t) };
},
},
},
// The event's type is the event key, and the event's id is the id of the delivery.
read: (req) => {
const event = json(req) as { readonly id?: unknown; readonly type?: unknown } | null;
if (typeof event?.id !== "string" || typeof event.type !== "string") {
throw new Error("the body is not a Stripe event");
}
return { key: event.type, id: event.id, payload: event };
},
});
// The kind's id and payloads, for the types of the handlers.
declare module "@jr2/orchestrator/hooks" {
interface HookKinds {
stripe: typeof stripe;
}
}A kind has these parts:
api: 1: the version of the interface of a kind.id: the key of the kind in thehooksof a Gate or a Source. It is lowercase letters, digits and-, and it starts with a letter. One id is one kind in an Assembly.events: a zod schema for each event key that a handler can hear. The door parses each payload with the schema of its key before a handler gets it. Usez.looseObject, and name only the fields that the handlers read. A key that ends in.*gives the schema of each key with that prefix.verify: one ofmac,tokenored25519. Formacanded25519,signedgives the bytes that the service signed, the signature without its prefix, andat, the time of the delivery in seconds. Giveatonly when the signature covers it. The door refuses a time that is more than 300 seconds from its clock. When the request does not have a signature, give{ unsigned: "<why>" }. Fortoken, give the header of the token.read: the request after the verifier, as a delivery or as a handshake. A delivery has the event key, the id, the payload, andonBehalfOfwhen the service names the party that acted. A handshake is{ handshake: { body } }, and goes to no handler. A throw is the status 400.
A kind whose answer a person reads also has answer, the envelope of the text, and maxText, the limit of the service on its length. Its read gives readBy: "person". When the answer gives a follow-up post, posts lists the URLs that the post can go to. See the slack kind.
A kind is pure and synchronous: it does no I/O, gives no Promise, and reads no clock. It never gets the secret. The declare module block adds the kind to HookKinds, so that the handlers of a Gate or a Source get the types of its payloads.
Declare a Hook of the kind
Add the Hook to jr2.config.ts, and its secret to the secrets list:
import { defineConfig, secret } from "@jr2/orchestrator";
import { stripe } from "./hooks/stripe.ts";
export default defineConfig({
// The signing secret of the Stripe endpoint. jr2 up places it in the Instance Effector.
secrets: [{ name: "STRIPE_HOOK", value: process.env.STRIPE_HOOK }],
hooks: {
// POST /hooks/billing. The Hook may answer the Gates of dunning alone.
billing: stripe({ secret: secret("STRIPE_HOOK"), may: { answer: ["dunning"] } }),
},
});The kind is also the constructor of its Hooks. It takes the credential and may.answer. For a mac kind, jr2 up puts the secret in the Instance Effector only, which checks each signature. Put the value in .env:
STRIPE_HOOK=<signing secret><signing secret> is the signing secret that Stripe shows for the endpoint. Give the endpoint the URL https://<host>/hooks/billing.
Hear it at a Gate
Import the kind's types in the workflow module, and give the Gate slot a handler for each event key that it hears:
import { z } from "zod";
import { defineEvent, fail, gate, jr2Setup } from "@jr2/orchestrator";
import type {} from "../hooks/stripe.ts";
const paid = defineEvent({
name: "paid",
description: "The customer paid the invoice.",
input: z.object({}),
});
// The Gate hears the stripe kind. A payment of another invoice is not for this Gate.
const payment = gate({
meta: z.object({ invoice: z.string() }),
delivers: [paid],
hooks: {
stripe: {
"invoice.paid": ({ payload, meta }) => (payload.data.object.id === meta.invoice ? { type: "paid" } : undefined),
},
},
});
export const machine = jr2Setup({
types: {} as { input: { invoice: string }; context: { invoice: string } },
events: [paid],
actors: { payment, fail: fail() },
}).createMachine({
id: "dunning",
input: z.object({ invoice: z.string() }),
context: ({ input }) => ({ invoice: input.invoice }),
initial: "waiting",
states: {
waiting: {
invoke: { src: "payment", input: ({ context }) => ({ meta: { invoice: context.invoice } }) },
on: { paid: "paid" },
// After seven days with no payment, the run stops waiting. A lost delivery cannot stop the
// run for longer than that.
after: { 604800000: "unpaid" },
},
paid: { type: "final" },
// Not a final state: the run ends `failed`, with the reason.
unpaid: { invoke: { src: "fail", input: () => ({ reason: "the invoice is not paid after seven days" }) } },
},
});A handler for a key that the kind does not give does not compile, and a handler reads only the fields that the schema names. Answer a Gate from a forge tells the other parts of a Gate slot, such as the look. A Source hears a kind in the same way (Start a run for each alert).
Put the kind in a package
A kind in a package of its own uses the same interface. Its package has a peer dependency on @jr2/orchestrator and states api: 1, and its jr2.config.ts and its workflow modules import it as they import a local file. jr2 up bundles the kind into the Assembly. jr2 finds no kind in a folder, and loads none while the Instance runs.
Rules
defineHookKind()refuses anidof another form:a Hook kind's id is lowercase letters, digits and "-", and starts with a letter: <id>defineHookKind()refuses anapithat it does not know:Hook kind <id> states api <api>; this @jr2/orchestrator/hooks knows api 1 onlydefineHookKind()refuses an event key with no zod schema:Hook kind <id>: the event key <key> has no zod schemadefineHookKind()refuses averifythat is not one of the three:Hook kind <id>: verify is one of mac, ed25519 or tokendefineHookKind()refuses amacverifier without an algorithm or asignedfunction:Hook kind <id>: a mac verifier has an alg (sha256, sha1, sha512) and a signed functiondefineHookKind()refuses atokenheader that is not lowercase:Hook kind <id>: a token verifier names its header in lowercasedefineHookKind()refuses apostsentry that is not anhttps://URL that ends in/:Hook kind <id>: a posts entry is an https:// url that ends in "/": <entry>defineHookKind()refuses amaxTextthat is not a positive integer:Hook kind <id>: maxText is a positive integer- The constructor of a
macortokenkind refuses a credential that is not a named secret:a <id> Hook takes secret: a named secret, secret("NAME") - The constructor of an
ed25519kind refuses a public key that is not 64 hex characters:a <id> Hook takes publicKey: the Ed25519 public key in hex (64 characters) - The constructor refuses a
may.answerthat is not"all"or a list of Workflow names:a <id> Hook's may.answer is "all" or a list of Workflow names - Two kinds with one id do not compile (
Subsequent property declarations must have the same type), and the config load refuses them:<file> at hooks: two different Hook kinds have the id <id>: one id is one kind in an Assembly (ADR-0078) - The type of
readrefusesreadBy: "person"in a kind that has noanswer. - A request that
signedgivesunsignedfor, or whose signature does not match, gets 401. A request thatreadthrows for gets 400:the <kind> kind cannot read the delivery: <error> jr2 uprefuses amacHook whose secret is not in thesecretslist:hooks.<name> names secret("<NAME>"), which the `secrets` list does not hold — add it: secrets: [{ name: "<NAME>", value: process.env.<NAME> }] (ADR-0068)
Read next
- Callers and Hooks
- Answer a Gate from a forge and Start a run for each alert
- Reference:
@jr2/orchestrator/hooks,HookKind,Signed,Deliveryand thehooksfield ofjr2.config.ts - ADR-0078: a Hook kind, the three verifiers, and the window
- ADR-0068: the Instance Effector holds a
macsecret