@deliverd/sdk 0.32.0 → 0.34.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/README.md +45 -0
- package/dist/adapters/index.d.ts +2 -0
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +1 -0
- package/dist/adapters/ui-sdk.d.ts +116 -0
- package/dist/adapters/ui-sdk.d.ts.map +1 -0
- package/dist/adapters/ui-sdk.js +164 -0
- package/dist/decision-token.d.ts +28 -1
- package/dist/decision-token.d.ts.map +1 -1
- package/dist/decision-token.js +33 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +2958 -0
- package/dist/verify.d.ts +77 -0
- package/dist/verify.d.ts.map +1 -0
- package/dist/verify.js +114 -0
- package/package.json +5 -1
- package/src/adapters/index.ts +2 -0
- package/src/adapters/ui-sdk.ts +263 -0
- package/src/decision-token.ts +51 -3
- package/src/index.ts +3 -0
- package/src/released.ts +2960 -0
- package/src/verify.ts +146 -0
package/dist/verify.d.ts
ADDED
|
@@ -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":"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"}
|
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.
|
|
3
|
+
"version": "0.34.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": [
|
package/src/adapters/index.ts
CHANGED
|
@@ -30,5 +30,7 @@ export type {
|
|
|
30
30
|
MuseToolMessage,
|
|
31
31
|
MuseToolRunner,
|
|
32
32
|
} from "./muse-spark.js";
|
|
33
|
+
export { deliverdAllow, describeStep, uiSdkApprovalRoute, UI_SDK_DEFAULT_TIMEOUT } from "./ui-sdk.js";
|
|
34
|
+
export type { DeliverdAllowOptions, UiSdkApprovalAnswer, UiSdkApprovalRouteOptions, UiSdkStep } from "./ui-sdk.js";
|
|
33
35
|
export { defaultDescription, DEFAULT_TOOL_EXPIRY } from "./shared.js";
|
|
34
36
|
export type { Approver, CallDescription, CallOutcome, ToolApprovalOptions } from "./shared.js";
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import type { Duration } from "../duration.js";
|
|
2
|
+
import { askAboutCall, type CallDescription, type ToolApprovalOptions } from "./shared.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Vercel's UI SDK (`@ui-sdk/*`): a person approves what an agent does in your
|
|
6
|
+
* interface, through Deliverd.
|
|
7
|
+
*
|
|
8
|
+
* UI SDK's agent bridge lets an agent press buttons and fill fields in an app
|
|
9
|
+
* built with its components. Controls marked `data-agent-confirm="…"` wait for
|
|
10
|
+
* the bridge's `allow` hook. These two functions make that hook a Deliverd
|
|
11
|
+
* approval: the browser half asks your server, and your server, which holds the
|
|
12
|
+
* agent key, asks Deliverd and waits for the person.
|
|
13
|
+
*
|
|
14
|
+
* In the browser, where the bridge is created:
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* import { createAgent } from "@ui-sdk/react/agent";
|
|
18
|
+
* import { deliverdAllow } from "@deliverd/sdk/adapters";
|
|
19
|
+
*
|
|
20
|
+
* const agent = createAgent({
|
|
21
|
+
* allow: deliverdAllow({ endpoint: "/api/deliverd/ui-approval" }),
|
|
22
|
+
* timeout: 15 * 60_000,
|
|
23
|
+
* });
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* On the server, as a fetch-style route (Next.js `app/api/deliverd/ui-approval/route.ts`):
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* import { Deliverd } from "@deliverd/sdk";
|
|
30
|
+
* import { uiSdkApprovalRoute } from "@deliverd/sdk/adapters";
|
|
31
|
+
*
|
|
32
|
+
* export const maxDuration = 800;
|
|
33
|
+
* export const POST = uiSdkApprovalRoute({ deliverd: new Deliverd(), approvers: ["ops"], timeout: "13m" });
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* The browser never sees the agent key, and the agent never sees the answer
|
|
37
|
+
* until a person gives it. Each ask is its own request: an approval is for
|
|
38
|
+
* that one step, then, and is never reused for a later one. A wait that runs
|
|
39
|
+
* out is a no, and the request expires with it, so nobody approves a step the
|
|
40
|
+
* agent has stopped waiting for.
|
|
41
|
+
*
|
|
42
|
+
* Shapes follow `AgentAction` and `createAgent`'s `allow` option in
|
|
43
|
+
* `@ui-sdk/core`'s agent docs (0.1.0-beta.1).
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/** The step UI SDK hands to `allow`: its `AgentAction`. */
|
|
47
|
+
export interface UiSdkStep {
|
|
48
|
+
ref: string;
|
|
49
|
+
component: string;
|
|
50
|
+
label?: string;
|
|
51
|
+
action: string;
|
|
52
|
+
args?: unknown[];
|
|
53
|
+
/** The sentence from a `data-agent-confirm` mark on the target, when it has one. */
|
|
54
|
+
confirm?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** What the server route answers. */
|
|
58
|
+
export type UiSdkApprovalAnswer = { allowed: true; decidedBy: string | null } | { allowed: false; reason: string };
|
|
59
|
+
|
|
60
|
+
export interface DeliverdAllowOptions {
|
|
61
|
+
/** Your server route that calls `uiSdkApprovalRoute`. */
|
|
62
|
+
endpoint: string;
|
|
63
|
+
/**
|
|
64
|
+
* Which steps go to a person. Default: those on a `data-agent-confirm`
|
|
65
|
+
* mark. Steps outside it are allowed without asking.
|
|
66
|
+
*/
|
|
67
|
+
when?: (step: UiSdkStep) => boolean;
|
|
68
|
+
/** Headers for the call to your route, such as a CSRF token. */
|
|
69
|
+
headers?: Record<string, string> | (() => Record<string, string>);
|
|
70
|
+
/** Told each answer, so the page can show a person's reason. */
|
|
71
|
+
onAnswer?: (answer: UiSdkApprovalAnswer, step: UiSdkStep) => void;
|
|
72
|
+
fetch?: typeof globalThis.fetch;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* UI SDK's `allow` hook, answered by a person through Deliverd.
|
|
77
|
+
*
|
|
78
|
+
* Anything other than a clear yes from your route is a no: a network failure,
|
|
79
|
+
* an error status, an answer it cannot read. UI SDK then tells the agent the
|
|
80
|
+
* person said no, and the control is not touched.
|
|
81
|
+
*/
|
|
82
|
+
export function deliverdAllow(
|
|
83
|
+
options: DeliverdAllowOptions
|
|
84
|
+
): (step: UiSdkStep, context?: { signal?: AbortSignal }) => Promise<boolean> {
|
|
85
|
+
const needsPerson = options.when ?? ((step: UiSdkStep) => Boolean(step.confirm));
|
|
86
|
+
return async (step, context) => {
|
|
87
|
+
if (!needsPerson(step)) return true;
|
|
88
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
89
|
+
const headers = typeof options.headers === "function" ? options.headers() : options.headers;
|
|
90
|
+
let answer: UiSdkApprovalAnswer;
|
|
91
|
+
try {
|
|
92
|
+
const response = await doFetch(options.endpoint, {
|
|
93
|
+
method: "POST",
|
|
94
|
+
headers: { "content-type": "application/json", ...headers },
|
|
95
|
+
body: JSON.stringify({ step: pickStep(step), nonce: nonce() }),
|
|
96
|
+
signal: context?.signal,
|
|
97
|
+
});
|
|
98
|
+
const body = (await response.json().catch(() => null)) as Partial<UiSdkApprovalAnswer> | null;
|
|
99
|
+
answer =
|
|
100
|
+
response.ok && body?.allowed === true
|
|
101
|
+
? { allowed: true, decidedBy: typeof body.decidedBy === "string" ? body.decidedBy : null }
|
|
102
|
+
: {
|
|
103
|
+
allowed: false,
|
|
104
|
+
reason:
|
|
105
|
+
body && body.allowed === false && typeof body.reason === "string"
|
|
106
|
+
? body.reason
|
|
107
|
+
: `The approval route answered ${response.status}, so the step was not run.`,
|
|
108
|
+
};
|
|
109
|
+
} catch {
|
|
110
|
+
if (context?.signal?.aborted) return false;
|
|
111
|
+
answer = { allowed: false, reason: "The approval route could not be reached, so the step was not run." };
|
|
112
|
+
}
|
|
113
|
+
options.onAnswer?.(answer, step);
|
|
114
|
+
return answer.allowed;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface UiSdkApprovalRouteOptions extends Omit<ToolApprovalOptions, "when" | "describe"> {
|
|
119
|
+
/**
|
|
120
|
+
* Which steps go to a person, decided on the server. Default: those on a
|
|
121
|
+
* `data-agent-confirm` mark. A step outside it is refused, not allowed:
|
|
122
|
+
* the browser only sends steps it wants a person for, so anything else
|
|
123
|
+
* arriving here was not sent by `deliverdAllow`.
|
|
124
|
+
*/
|
|
125
|
+
when?: (step: UiSdkStep, request: Request) => boolean | Promise<boolean>;
|
|
126
|
+
/** What the approver reads. Built from the mark's sentence, the control and its values when omitted. */
|
|
127
|
+
describe?: (step: UiSdkStep) => CallDescription;
|
|
128
|
+
/**
|
|
129
|
+
* How long to wait for the person. Default four minutes, inside UI SDK's
|
|
130
|
+
* own five-minute wait and a typical function limit. Raise all three together.
|
|
131
|
+
*/
|
|
132
|
+
timeout?: Duration;
|
|
133
|
+
/** How long the request stays open. Default: the same as `timeout`. */
|
|
134
|
+
expiresIn?: Duration;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export const UI_SDK_DEFAULT_TIMEOUT: Duration = "4m";
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The server half: a fetch-style `POST` handler (Next.js route handlers, Hono,
|
|
141
|
+
* Remix, Workers) that asks Deliverd about one UI SDK step and waits.
|
|
142
|
+
*
|
|
143
|
+
* Set `timeout` below both your platform's function limit and the bridge's
|
|
144
|
+
* own `timeout`, or the function is cut off before it can answer. The
|
|
145
|
+
* request's abort signal cancels the wait when the page stops asking.
|
|
146
|
+
*/
|
|
147
|
+
export function uiSdkApprovalRoute(options: UiSdkApprovalRouteOptions): (request: Request) => Promise<Response> {
|
|
148
|
+
const needsPerson = options.when ?? ((step: UiSdkStep) => Boolean(step.confirm));
|
|
149
|
+
const describe = options.describe ?? describeStep;
|
|
150
|
+
const timeout = options.timeout ?? UI_SDK_DEFAULT_TIMEOUT;
|
|
151
|
+
return async (request) => {
|
|
152
|
+
if (request.method !== "POST") return json({ allowed: false, reason: "Use POST." }, 405);
|
|
153
|
+
let raw: unknown;
|
|
154
|
+
try {
|
|
155
|
+
const text = await request.text();
|
|
156
|
+
if (text.length > BODY_MAX) return json({ allowed: false, reason: "The step is too large to ask about." }, 413);
|
|
157
|
+
raw = JSON.parse(text);
|
|
158
|
+
} catch {
|
|
159
|
+
return json({ allowed: false, reason: "The step could not be read." }, 400);
|
|
160
|
+
}
|
|
161
|
+
const parsed = readBody(raw);
|
|
162
|
+
if (!parsed) return json({ allowed: false, reason: "The step could not be read." }, 400);
|
|
163
|
+
const { step, nonce: id } = parsed;
|
|
164
|
+
if (!(await needsPerson(step, request))) {
|
|
165
|
+
return json({ allowed: false, reason: "This step is not one this route asks a person about." }, 403);
|
|
166
|
+
}
|
|
167
|
+
const name = stepName(step);
|
|
168
|
+
const outcome = await askAboutCall(
|
|
169
|
+
name,
|
|
170
|
+
{ component: step.component, ref: step.ref, action: step.action, args: step.args ?? [] },
|
|
171
|
+
`ui-sdk:${await sha256(canonical({ step, id }))}`,
|
|
172
|
+
{
|
|
173
|
+
...options,
|
|
174
|
+
when: undefined,
|
|
175
|
+
describe: () => describe(step),
|
|
176
|
+
timeout,
|
|
177
|
+
expiresIn: options.expiresIn ?? timeout,
|
|
178
|
+
metadata: { ...options.metadata, source: "ui-sdk" },
|
|
179
|
+
},
|
|
180
|
+
request.signal
|
|
181
|
+
);
|
|
182
|
+
return json(
|
|
183
|
+
outcome.allowed ? { allowed: true, decidedBy: outcome.decidedBy } : { allowed: false, reason: outcome.reason },
|
|
184
|
+
200
|
|
185
|
+
);
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** What an approver reads about a step, when the app did not write it. */
|
|
190
|
+
export function describeStep(step: UiSdkStep): CallDescription {
|
|
191
|
+
const target = step.label ? `"${step.label}"` : `the ${step.component}`;
|
|
192
|
+
const verb = step.action === "press" ? "press" : step.action === "setValue" ? "set" : step.action;
|
|
193
|
+
const values = (step.args ?? []).map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg))).join(", ");
|
|
194
|
+
const lines = [
|
|
195
|
+
step.confirm ? `The app says this: ${step.confirm}` : undefined,
|
|
196
|
+
`An agent wants to ${verb} ${target}${values ? ` (${truncate(values, 500)})` : ""} in the app.`,
|
|
197
|
+
].filter(Boolean);
|
|
198
|
+
return {
|
|
199
|
+
title: truncate(step.confirm ?? `Let the agent ${verb} ${target}`, 200),
|
|
200
|
+
description: lines.join("\n\n"),
|
|
201
|
+
risk: step.confirm ? "high" : "medium",
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const BODY_MAX = 16_000;
|
|
206
|
+
|
|
207
|
+
function stepName(step: UiSdkStep): string {
|
|
208
|
+
return step.label ? `${step.action} "${step.label}"` : `${step.action} ${step.component}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Only the fields `AgentAction` documents, so nothing else on the object leaves the page. */
|
|
212
|
+
function pickStep(step: UiSdkStep): UiSdkStep {
|
|
213
|
+
return {
|
|
214
|
+
ref: step.ref,
|
|
215
|
+
component: step.component,
|
|
216
|
+
...(step.label !== undefined ? { label: step.label } : {}),
|
|
217
|
+
action: step.action,
|
|
218
|
+
args: step.args ?? [],
|
|
219
|
+
...(step.confirm !== undefined ? { confirm: step.confirm } : {}),
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function readBody(raw: unknown): { step: UiSdkStep; nonce: string } | null {
|
|
224
|
+
if (typeof raw !== "object" || raw === null) return null;
|
|
225
|
+
const { step, nonce: id } = raw as { step?: unknown; nonce?: unknown };
|
|
226
|
+
if (typeof id !== "string" || id.length === 0 || id.length > 100) return null;
|
|
227
|
+
if (typeof step !== "object" || step === null) return null;
|
|
228
|
+
const s = step as Record<string, unknown>;
|
|
229
|
+
const str = (v: unknown) => typeof v === "string" && v.length <= 1000;
|
|
230
|
+
if (!str(s.ref) || !str(s.component) || !str(s.action)) return null;
|
|
231
|
+
if (s.label !== undefined && !str(s.label)) return null;
|
|
232
|
+
if (s.confirm !== undefined && !str(s.confirm)) return null;
|
|
233
|
+
if (s.args !== undefined && !Array.isArray(s.args)) return null;
|
|
234
|
+
return { step: pickStep(s as unknown as UiSdkStep), nonce: id };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function json(body: UiSdkApprovalAnswer | { allowed: false; reason: string }, status: number): Response {
|
|
238
|
+
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function truncate(text: string, max: number): string {
|
|
242
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function nonce(): string {
|
|
246
|
+
const c = globalThis.crypto;
|
|
247
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
248
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function canonical(value: unknown): string {
|
|
252
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
|
|
253
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
254
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
255
|
+
.filter(([, v]) => v !== undefined)
|
|
256
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
257
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function sha256(text: string): Promise<string> {
|
|
261
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
262
|
+
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
263
|
+
}
|
package/src/decision-token.ts
CHANGED
|
@@ -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
|
-
|
|
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> {
|