@deliverd/sdk 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/types.ts CHANGED
@@ -860,7 +860,11 @@ export interface WebhookEvent {
860
860
  * webhook, or a Discord embed with a link button for a channel webhook. The
861
861
  * signature headers are sent with all four.
862
862
  */
863
- export type WebhookEndpointFormat = "json" | "slack" | "teams" | "discord";
863
+ /**
864
+ * `workspace_studio` fires a Google Workspace Studio starter. The Deliverd
865
+ * add-on makes those, with `runAs`; you will see them in a list.
866
+ */
867
+ export type WebhookEndpointFormat = "json" | "slack" | "teams" | "discord" | "workspace_studio";
864
868
 
865
869
  /** An organisation's webhook endpoint, as `deliverd.webhookEndpoints` reads it. Never its secret. */
866
870
  export interface WebhookEndpoint {
@@ -909,6 +913,8 @@ export interface CreateWebhookEndpointInput {
909
913
  description?: string | null;
910
914
  /** Default `"json"`. */
911
915
  format?: WebhookEndpointFormat;
916
+ /** `workspace_studio` only: the Google address of the person whose flow the starter belongs to. */
917
+ runAs?: string;
912
918
  }
913
919
 
914
920
  /** Only what you send changes; send at least one. The secret cannot be changed. */
@@ -1748,7 +1754,7 @@ export interface SubmitEvidenceInput {
1748
1754
  /**
1749
1755
  * Read the results from the organisation's connected Langfuse, LangSmith,
1750
1756
  * Braintrust or Weave, with its key, which you never hold. Instead of `results` or `report`.
1751
- * Connected by an owner or an administrator in Admin → Integrations.
1757
+ * Connected by an owner or an administrator in Organisation → Integrations & webhooks.
1752
1758
  */
1753
1759
  pull?: EvidencePull;
1754
1760
  /** The release the results tested, with results, a report or a pull. Results of another release than the system runs now do not count. */
package/src/verify.ts ADDED
@@ -0,0 +1,146 @@
1
+ import {
2
+ claimOnce,
3
+ verifyDecisionToken,
4
+ DecisionTokens,
5
+ type DecisionTokenExpectation,
6
+ type DecisionTokenResult,
7
+ type ReplayGuard,
8
+ } from "./decision-token.js";
9
+ import type { KeyObject } from "node:crypto";
10
+
11
+ /**
12
+ * Drop-in checks for the service that performs an action, so "the action
13
+ * cannot happen without a yes" takes a few lines instead of a project.
14
+ *
15
+ * The agent sends the gate's `decisionToken` in the `Deliverd-Decision`
16
+ * header (or wherever you choose). Your service says which action the route
17
+ * performs and what input it is about to act on; the check refuses anything
18
+ * Deliverd did not agree to, exactly, for that action, before your handler
19
+ * runs.
20
+ *
21
+ * ```ts
22
+ * import { requireDecision, memoryReplayGuard } from "@deliverd/sdk/verify";
23
+ *
24
+ * const refunds = requireDecision({
25
+ * deliverd: "https://deliverd.dev",
26
+ * action: "finance.refund",
27
+ * input: (req) => ({ customer_id: req.body.customer_id, amount: req.body.amount, currency: req.body.currency }),
28
+ * replay: memoryReplayGuard(),
29
+ * });
30
+ * app.post("/refunds", express.json(), refunds, handler); // Express, Connect
31
+ * fastify.post("/refunds", { preHandler: refunds.fastify }, handler); // Fastify
32
+ * ```
33
+ *
34
+ * For fetch-style handlers (Next.js route handlers, Hono, Workers, Bun),
35
+ * `checkDecision(request, options)` returns null when the request may go
36
+ * ahead, or a `403` Response to send back.
37
+ */
38
+
39
+ export const DECISION_HEADER = "deliverd-decision";
40
+
41
+ export interface RequireDecisionOptions<Req> {
42
+ /** The Deliverd deployment you trust, e.g. `https://deliverd.dev`. Its public key is fetched once. */
43
+ deliverd?: string;
44
+ /** Or a key you already hold, with the issuer origin it must name. */
45
+ key?: { publicKey: string | KeyObject; issuer: string };
46
+ /** The action this route performs. */
47
+ action: string | ((req: Req) => string);
48
+ /** The input it is about to act on, exactly as the gate was asked. */
49
+ input: (req: Req) => unknown | Promise<unknown>;
50
+ destination?: (req: Req) => DecisionTokenExpectation["destination"];
51
+ artifactSha256?: (req: Req) => string | null | undefined;
52
+ /** The Deliverd agent id that must have asked. */
53
+ agent?: string | ((req: Req) => string | undefined);
54
+ /** Refuse a token seen before. Use one shared store when you run more than one instance. */
55
+ replay?: ReplayGuard;
56
+ /** Where the token is. Default: the `Deliverd-Decision` header, then `Authorization: Deliverd <token>`. */
57
+ token?: (req: Req) => string | null | undefined;
58
+ }
59
+
60
+ type Headerish = { headers?: Record<string, string | string[] | undefined> | Headers };
61
+
62
+ function headerOf(req: Headerish, name: string): string | null {
63
+ const h = req.headers;
64
+ if (!h) return null;
65
+ if (typeof (h as Headers).get === "function") return (h as Headers).get(name);
66
+ const v = (h as Record<string, string | string[] | undefined>)[name] ?? (h as Record<string, string | string[] | undefined>)[name.toLowerCase()];
67
+ return Array.isArray(v) ? (v[0] ?? null) : (v ?? null);
68
+ }
69
+
70
+ export function tokenFrom(req: Headerish): string | null {
71
+ const direct = headerOf(req, DECISION_HEADER);
72
+ if (direct) return direct.trim();
73
+ const auth = headerOf(req, "authorization");
74
+ const m = auth?.match(/^Deliverd\s+(\S+)$/i);
75
+ return m ? m[1]! : null;
76
+ }
77
+
78
+ /** The check itself, for any request shape. */
79
+ export function decisionChecker<Req>(options: RequireDecisionOptions<Req>): (req: Req) => Promise<DecisionTokenResult> {
80
+ if (!options.deliverd && !options.key) throw new Error("requireDecision needs `deliverd` (the deployment URL) or `key`.");
81
+ const tokens = options.deliverd ? new DecisionTokens(options.deliverd) : null;
82
+ return async (req) => {
83
+ const token = options.token ? options.token(req) : tokenFrom(req as Headerish);
84
+ if (!token) return { ok: false, reason: "missing" };
85
+ const agent = typeof options.agent === "function" ? options.agent(req) : options.agent;
86
+ const expected: DecisionTokenExpectation = {
87
+ action: typeof options.action === "function" ? options.action(req) : options.action,
88
+ input: await options.input(req),
89
+ destination: options.destination?.(req) ?? null,
90
+ artifactSha256: options.artifactSha256?.(req) ?? null,
91
+ ...(agent !== undefined ? { agent } : {}),
92
+ };
93
+ if (tokens) return tokens.verify(token, expected, { replay: options.replay });
94
+ return claimOnce(verifyDecisionToken(token, expected, options.key!), options.replay);
95
+ };
96
+ }
97
+
98
+ const MESSAGE: Record<string, string> = {
99
+ missing: "This action needs a Deliverd decision token, and none was sent.",
100
+ replayed: "This decision token has already been used.",
101
+ };
102
+
103
+ function refusal(result: Extract<DecisionTokenResult, { ok: false }>) {
104
+ return { error: "decision_required", reason: result.reason, message: MESSAGE[result.reason] ?? `The Deliverd decision token does not authorise this request (${result.reason}).` };
105
+ }
106
+
107
+ type NodeRes = { statusCode?: number; setHeader?(k: string, v: string): void; end?(body: string): void; status?(code: number): NodeRes; json?(body: unknown): void };
108
+
109
+ /** Express/Connect middleware, with `.fastify` for a Fastify preHandler. */
110
+ export function requireDecision<Req = any>(options: RequireDecisionOptions<Req>) {
111
+ const check = decisionChecker(options);
112
+ const middleware = async (req: Req, res: NodeRes, next: (err?: unknown) => void) => {
113
+ try {
114
+ const result = await check(req);
115
+ if (result.ok) {
116
+ (req as { deliverdDecision?: unknown }).deliverdDecision = result.claims;
117
+ return next();
118
+ }
119
+ const body = refusal(result);
120
+ if (typeof res.status === "function" && typeof res.json === "function") return res.status(403)!.json!(body);
121
+ res.statusCode = 403;
122
+ res.setHeader?.("content-type", "application/json");
123
+ res.end?.(JSON.stringify(body));
124
+ } catch (err) {
125
+ next(err);
126
+ }
127
+ };
128
+ const fastify = async (req: Req, reply: { code(n: number): { send(b: unknown): unknown } }) => {
129
+ const result = await check(req);
130
+ if (result.ok) {
131
+ (req as { deliverdDecision?: unknown }).deliverdDecision = result.claims;
132
+ return;
133
+ }
134
+ return reply.code(403).send(refusal(result));
135
+ };
136
+ return Object.assign(middleware, { fastify, check });
137
+ }
138
+
139
+ /** For fetch-style handlers: null to go ahead, or the 403 Response to return. */
140
+ export async function checkDecision(request: Request, options: RequireDecisionOptions<Request>): Promise<Response | null> {
141
+ const result = await decisionChecker(options)(request);
142
+ if (result.ok) return null;
143
+ return new Response(JSON.stringify(refusal(result)), { status: 403, headers: { "content-type": "application/json" } });
144
+ }
145
+
146
+ export { memoryReplayGuard, type ReplayGuard } from "./decision-token.js";