@deliverd/sdk 0.32.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.
@@ -0,0 +1,77 @@
1
+ import { type DecisionTokenExpectation, type DecisionTokenResult, type ReplayGuard } from "./decision-token.js";
2
+ import type { KeyObject } from "node:crypto";
3
+ /**
4
+ * Drop-in checks for the service that performs an action, so "the action
5
+ * cannot happen without a yes" takes a few lines instead of a project.
6
+ *
7
+ * The agent sends the gate's `decisionToken` in the `Deliverd-Decision`
8
+ * header (or wherever you choose). Your service says which action the route
9
+ * performs and what input it is about to act on; the check refuses anything
10
+ * Deliverd did not agree to, exactly, for that action, before your handler
11
+ * runs.
12
+ *
13
+ * ```ts
14
+ * import { requireDecision, memoryReplayGuard } from "@deliverd/sdk/verify";
15
+ *
16
+ * const refunds = requireDecision({
17
+ * deliverd: "https://deliverd.dev",
18
+ * action: "finance.refund",
19
+ * input: (req) => ({ customer_id: req.body.customer_id, amount: req.body.amount, currency: req.body.currency }),
20
+ * replay: memoryReplayGuard(),
21
+ * });
22
+ * app.post("/refunds", express.json(), refunds, handler); // Express, Connect
23
+ * fastify.post("/refunds", { preHandler: refunds.fastify }, handler); // Fastify
24
+ * ```
25
+ *
26
+ * For fetch-style handlers (Next.js route handlers, Hono, Workers, Bun),
27
+ * `checkDecision(request, options)` returns null when the request may go
28
+ * ahead, or a `403` Response to send back.
29
+ */
30
+ export declare const DECISION_HEADER = "deliverd-decision";
31
+ export interface RequireDecisionOptions<Req> {
32
+ /** The Deliverd deployment you trust, e.g. `https://deliverd.dev`. Its public key is fetched once. */
33
+ deliverd?: string;
34
+ /** Or a key you already hold, with the issuer origin it must name. */
35
+ key?: {
36
+ publicKey: string | KeyObject;
37
+ issuer: string;
38
+ };
39
+ /** The action this route performs. */
40
+ action: string | ((req: Req) => string);
41
+ /** The input it is about to act on, exactly as the gate was asked. */
42
+ input: (req: Req) => unknown | Promise<unknown>;
43
+ destination?: (req: Req) => DecisionTokenExpectation["destination"];
44
+ artifactSha256?: (req: Req) => string | null | undefined;
45
+ /** The Deliverd agent id that must have asked. */
46
+ agent?: string | ((req: Req) => string | undefined);
47
+ /** Refuse a token seen before. Use one shared store when you run more than one instance. */
48
+ replay?: ReplayGuard;
49
+ /** Where the token is. Default: the `Deliverd-Decision` header, then `Authorization: Deliverd <token>`. */
50
+ token?: (req: Req) => string | null | undefined;
51
+ }
52
+ type Headerish = {
53
+ headers?: Record<string, string | string[] | undefined> | Headers;
54
+ };
55
+ export declare function tokenFrom(req: Headerish): string | null;
56
+ /** The check itself, for any request shape. */
57
+ export declare function decisionChecker<Req>(options: RequireDecisionOptions<Req>): (req: Req) => Promise<DecisionTokenResult>;
58
+ type NodeRes = {
59
+ statusCode?: number;
60
+ setHeader?(k: string, v: string): void;
61
+ end?(body: string): void;
62
+ status?(code: number): NodeRes;
63
+ json?(body: unknown): void;
64
+ };
65
+ /** Express/Connect middleware, with `.fastify` for a Fastify preHandler. */
66
+ export declare function requireDecision<Req = any>(options: RequireDecisionOptions<Req>): ((req: Req, res: NodeRes, next: (err?: unknown) => void) => Promise<void>) & {
67
+ fastify: (req: Req, reply: {
68
+ code(n: number): {
69
+ send(b: unknown): unknown;
70
+ };
71
+ }) => Promise<unknown>;
72
+ check: (req: Req) => Promise<DecisionTokenResult>;
73
+ };
74
+ /** For fetch-style handlers: null to go ahead, or the 403 Response to return. */
75
+ export declare function checkDecision(request: Request, options: RequireDecisionOptions<Request>): Promise<Response | null>;
76
+ export { memoryReplayGuard, type ReplayGuard } from "./decision-token.js";
77
+ //# sourceMappingURL=verify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,wBAAwB,EAC7B,KAAK,mBAAmB,EACxB,KAAK,WAAW,EACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM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GAAG,EAAE,OAAO,EAAE,sBAAsB,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK,OAAO,CAAC,mBAAmB,CAAC,CAiBrH;AAWD,KAAK,OAAO,GAAG;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,MAAM,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAAC,IAAI,CAAC,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAA;CAAE,CAAC;AAErK,4EAA4E;AAC5E,wBAAgB,eAAe,CAAC,GAAG,GAAG,GAAG,EAAE,OAAO,EAAE,sBAAsB,CAAC,GAAG,CAAC,UAE9C,GAAG,OAAO,OAAO,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,IAAI;mBAgBnD,GAAG,SAAS;QAAE,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG;YAAE,IAAI,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAA;SAAE,CAAA;KAAE;yBAjDF,OAAO,CAAC,mBAAmB,CAAC;EA0DrH;AAED,iFAAiF;AACjF,wBAAsB,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,sBAAsB,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAIxH;AAED,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/verify.js ADDED
@@ -0,0 +1,114 @@
1
+ import { claimOnce, verifyDecisionToken, DecisionTokens, } from "./decision-token.js";
2
+ /**
3
+ * Drop-in checks for the service that performs an action, so "the action
4
+ * cannot happen without a yes" takes a few lines instead of a project.
5
+ *
6
+ * The agent sends the gate's `decisionToken` in the `Deliverd-Decision`
7
+ * header (or wherever you choose). Your service says which action the route
8
+ * performs and what input it is about to act on; the check refuses anything
9
+ * Deliverd did not agree to, exactly, for that action, before your handler
10
+ * runs.
11
+ *
12
+ * ```ts
13
+ * import { requireDecision, memoryReplayGuard } from "@deliverd/sdk/verify";
14
+ *
15
+ * const refunds = requireDecision({
16
+ * deliverd: "https://deliverd.dev",
17
+ * action: "finance.refund",
18
+ * input: (req) => ({ customer_id: req.body.customer_id, amount: req.body.amount, currency: req.body.currency }),
19
+ * replay: memoryReplayGuard(),
20
+ * });
21
+ * app.post("/refunds", express.json(), refunds, handler); // Express, Connect
22
+ * fastify.post("/refunds", { preHandler: refunds.fastify }, handler); // Fastify
23
+ * ```
24
+ *
25
+ * For fetch-style handlers (Next.js route handlers, Hono, Workers, Bun),
26
+ * `checkDecision(request, options)` returns null when the request may go
27
+ * ahead, or a `403` Response to send back.
28
+ */
29
+ export const DECISION_HEADER = "deliverd-decision";
30
+ function headerOf(req, name) {
31
+ const h = req.headers;
32
+ if (!h)
33
+ return null;
34
+ if (typeof h.get === "function")
35
+ return h.get(name);
36
+ const v = h[name] ?? h[name.toLowerCase()];
37
+ return Array.isArray(v) ? (v[0] ?? null) : (v ?? null);
38
+ }
39
+ export function tokenFrom(req) {
40
+ const direct = headerOf(req, DECISION_HEADER);
41
+ if (direct)
42
+ return direct.trim();
43
+ const auth = headerOf(req, "authorization");
44
+ const m = auth?.match(/^Deliverd\s+(\S+)$/i);
45
+ return m ? m[1] : null;
46
+ }
47
+ /** The check itself, for any request shape. */
48
+ export function decisionChecker(options) {
49
+ if (!options.deliverd && !options.key)
50
+ throw new Error("requireDecision needs `deliverd` (the deployment URL) or `key`.");
51
+ const tokens = options.deliverd ? new DecisionTokens(options.deliverd) : null;
52
+ return async (req) => {
53
+ const token = options.token ? options.token(req) : tokenFrom(req);
54
+ if (!token)
55
+ return { ok: false, reason: "missing" };
56
+ const agent = typeof options.agent === "function" ? options.agent(req) : options.agent;
57
+ const expected = {
58
+ action: typeof options.action === "function" ? options.action(req) : options.action,
59
+ input: await options.input(req),
60
+ destination: options.destination?.(req) ?? null,
61
+ artifactSha256: options.artifactSha256?.(req) ?? null,
62
+ ...(agent !== undefined ? { agent } : {}),
63
+ };
64
+ if (tokens)
65
+ return tokens.verify(token, expected, { replay: options.replay });
66
+ return claimOnce(verifyDecisionToken(token, expected, options.key), options.replay);
67
+ };
68
+ }
69
+ const MESSAGE = {
70
+ missing: "This action needs a Deliverd decision token, and none was sent.",
71
+ replayed: "This decision token has already been used.",
72
+ };
73
+ function refusal(result) {
74
+ return { error: "decision_required", reason: result.reason, message: MESSAGE[result.reason] ?? `The Deliverd decision token does not authorise this request (${result.reason}).` };
75
+ }
76
+ /** Express/Connect middleware, with `.fastify` for a Fastify preHandler. */
77
+ export function requireDecision(options) {
78
+ const check = decisionChecker(options);
79
+ const middleware = async (req, res, next) => {
80
+ try {
81
+ const result = await check(req);
82
+ if (result.ok) {
83
+ req.deliverdDecision = result.claims;
84
+ return next();
85
+ }
86
+ const body = refusal(result);
87
+ if (typeof res.status === "function" && typeof res.json === "function")
88
+ return res.status(403).json(body);
89
+ res.statusCode = 403;
90
+ res.setHeader?.("content-type", "application/json");
91
+ res.end?.(JSON.stringify(body));
92
+ }
93
+ catch (err) {
94
+ next(err);
95
+ }
96
+ };
97
+ const fastify = async (req, reply) => {
98
+ const result = await check(req);
99
+ if (result.ok) {
100
+ req.deliverdDecision = result.claims;
101
+ return;
102
+ }
103
+ return reply.code(403).send(refusal(result));
104
+ };
105
+ return Object.assign(middleware, { fastify, check });
106
+ }
107
+ /** For fetch-style handlers: null to go ahead, or the 403 Response to return. */
108
+ export async function checkDecision(request, options) {
109
+ const result = await decisionChecker(options)(request);
110
+ if (result.ok)
111
+ return null;
112
+ return new Response(JSON.stringify(refusal(result)), { status: 403, headers: { "content-type": "application/json" } });
113
+ }
114
+ export { memoryReplayGuard } from "./decision-token.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deliverd/sdk",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "description": "Add human approval to any AI agent. Ask a person, wait for the answer, act on it. Start free at deliverd.dev.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -13,6 +13,10 @@
13
13
  "./adapters": {
14
14
  "types": "./dist/adapters/index.d.ts",
15
15
  "default": "./dist/adapters/index.js"
16
+ },
17
+ "./verify": {
18
+ "types": "./dist/verify.d.ts",
19
+ "default": "./dist/verify.js"
16
20
  }
17
21
  },
18
22
  "files": [
@@ -48,6 +48,10 @@ export interface DecisionTokenClaims {
48
48
  artifact: string | null;
49
49
  iat: number;
50
50
  exp: number;
51
+ /** The Deliverd agent that asked. Absent on tokens issued before it was added. */
52
+ agent?: string | null;
53
+ /** This token's id, for a replay guard. Absent on tokens issued before it was added. */
54
+ jti?: string;
51
55
  }
52
56
 
53
57
  export interface DecisionTokenExpectation {
@@ -59,6 +63,35 @@ export interface DecisionTokenExpectation {
59
63
  destination?: { type: string; id: string } | null;
60
64
  /** The SHA-256 of what you are sending, when the gate named an artifact. */
61
65
  artifactSha256?: string | null;
66
+ /**
67
+ * The Deliverd agent id you expect to have asked. When set, a token another
68
+ * agent earned is refused, and so is one that names no agent.
69
+ */
70
+ agent?: string;
71
+ }
72
+
73
+ /**
74
+ * Refuses a token seen before, so one yes cannot be replayed at your service
75
+ * without a call to Deliverd. `claim` returns false when the id was already
76
+ * claimed; keep each id until `expiresAt` (unix seconds). Back it with Redis
77
+ * (`SET jti 1 NX EXAT exp`) when you run more than one instance.
78
+ */
79
+ export interface ReplayGuard {
80
+ claim(jti: string, expiresAt: number): boolean | Promise<boolean>;
81
+ }
82
+
83
+ /** A replay guard for one process. Ids are dropped once their token has expired. */
84
+ export function memoryReplayGuard(): ReplayGuard {
85
+ const seen = new Map<string, number>();
86
+ return {
87
+ claim(jti, expiresAt) {
88
+ const now = Math.floor(Date.now() / 1000);
89
+ if (seen.size > 10_000) for (const [k, exp] of seen) if (exp < now) seen.delete(k);
90
+ if (seen.has(jti)) return false;
91
+ seen.set(jti, expiresAt);
92
+ return true;
93
+ },
94
+ };
62
95
  }
63
96
 
64
97
  export type DecisionTokenFailure =
@@ -70,7 +103,9 @@ export type DecisionTokenFailure =
70
103
  | "wrong_action"
71
104
  | "input_mismatch"
72
105
  | "destination_mismatch"
73
- | "artifact_mismatch";
106
+ | "artifact_mismatch"
107
+ | "wrong_agent"
108
+ | "replayed";
74
109
 
75
110
  export type DecisionTokenResult =
76
111
  | { ok: true; claims: DecisionTokenClaims }
@@ -139,9 +174,21 @@ export function verifyDecisionToken(
139
174
  if (!d || !sameDestination(d, claims.dest)) return { ok: false, reason: "destination_mismatch" };
140
175
  }
141
176
  if (claims.artifact && expected.artifactSha256 !== claims.artifact) return { ok: false, reason: "artifact_mismatch" };
177
+ if (expected.agent !== undefined && claims.agent !== expected.agent) return { ok: false, reason: "wrong_agent" };
142
178
  return { ok: true, claims };
143
179
  }
144
180
 
181
+ /**
182
+ * Spend a verified token's id with a replay guard. A token with no id (issued
183
+ * before ids were added) cannot be guarded and is refused, so turning a guard
184
+ * on never quietly lets an unguardable token through.
185
+ */
186
+ export async function claimOnce(result: DecisionTokenResult, guard: ReplayGuard | undefined): Promise<DecisionTokenResult> {
187
+ if (!result.ok || !guard) return result;
188
+ if (!result.claims.jti) return { ok: false, reason: "replayed" };
189
+ return (await guard.claim(result.claims.jti, result.claims.exp)) ? result : { ok: false, reason: "replayed" };
190
+ }
191
+
145
192
  /**
146
193
  * `deliverd.decisionTokens`: verification against the deployment this client
147
194
  * talks to. The key comes from that deployment's own well-known address and
@@ -159,11 +206,12 @@ export class DecisionTokens {
159
206
  async verify(
160
207
  token: string | null | undefined,
161
208
  expected: DecisionTokenExpectation,
162
- options: { now?: Date; skewSeconds?: number } = {}
209
+ options: { now?: Date; skewSeconds?: number; replay?: ReplayGuard } = {}
163
210
  ): Promise<DecisionTokenResult> {
164
211
  if (!token) return { ok: false, reason: "missing" };
165
212
  const publicKey = await this.publicKey();
166
- return verifyDecisionToken(token, expected, { publicKey, issuer: new URL(this.baseUrl).origin, ...options });
213
+ const { replay, ...clock } = options;
214
+ return claimOnce(verifyDecisionToken(token, expected, { publicKey, issuer: new URL(this.baseUrl).origin, ...clock }), replay);
167
215
  }
168
216
 
169
217
  private publicKey(): Promise<KeyObject> {
package/src/index.ts CHANGED
@@ -45,6 +45,9 @@ export {
45
45
  DecisionTokens,
46
46
  EVIDENCE_KEY_PATH,
47
47
  verifyDecisionToken,
48
+ claimOnce,
49
+ memoryReplayGuard,
50
+ type ReplayGuard,
48
51
  type DecisionTokenClaims,
49
52
  type DecisionTokenExpectation,
50
53
  type DecisionTokenFailure,