@powerhousedao/switchboard 6.2.3-dev.85 → 6.2.3-dev.86
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/.tsbuild/test/ai-gateway.test.d.ts +2 -0
- package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
- package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
- package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
- package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
- package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
- package/.tsbuild/tsconfig.tsbuildinfo +1 -1
- package/CHANGELOG.md +20 -0
- package/README.md +33 -0
- package/dist/boot.d.mts +1 -1
- package/dist/boot.mjs +1 -1
- package/dist/config/from-env.d.mts +1 -1
- package/dist/config/from-env.d.mts.map +1 -1
- package/dist/config/from-env.mjs +3 -3
- package/dist/config/schema.d.mts +1 -1
- package/dist/config/schema.mjs +3 -3
- package/dist/{from-env-BO0n9R02.mjs → from-env-BgyZQAxw.mjs} +79 -7
- package/dist/from-env-BgyZQAxw.mjs.map +1 -0
- package/dist/index.mjs +3 -3
- package/dist/{plugin-host-C1sYEm8g.d.mts → plugin-host-C0bSz1Oe.d.mts} +2 -2
- package/dist/{plugin-host-C1sYEm8g.d.mts.map → plugin-host-C0bSz1Oe.d.mts.map} +1 -1
- package/dist/plugins/ai.d.mts +37 -0
- package/dist/plugins/ai.d.mts.map +1 -0
- package/dist/plugins/ai.mjs +352 -0
- package/dist/plugins/ai.mjs.map +1 -0
- package/dist/plugins/attachments.d.mts +1 -1
- package/dist/plugins/attachments.mjs +3 -3
- package/dist/plugins/mcp.d.mts +1 -1
- package/dist/plugins/privacy.d.mts +1 -1
- package/dist/plugins/workflows.d.mts +2 -2
- package/dist/plugins/workflows.mjs +3 -3
- package/dist/{schema-ivUWPQOn.d.mts → schema-DhempFjb.d.mts} +41 -1
- package/dist/schema-DhempFjb.d.mts.map +1 -0
- package/dist/{schema-0g_QdOWn.mjs → schema-XEZrdmag.mjs} +55 -6
- package/dist/schema-XEZrdmag.mjs.map +1 -0
- package/dist/{server-YNY3Qw9a.mjs → server-BRVMofWD.mjs} +102 -14
- package/dist/server-BRVMofWD.mjs.map +1 -0
- package/dist/server.d.mts +7 -3
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +5 -5
- package/dist/{workflow-runtime-7GaJ13c9.d.mts → workflow-runtime-CF5pc8mt.d.mts} +5 -2
- package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
- package/dist/{workflows-DkIrfmdn.mjs → workflows-C_pWcP2u.mjs} +4 -3
- package/dist/{workflows-DkIrfmdn.mjs.map → workflows-C_pWcP2u.mjs.map} +1 -1
- package/package.json +22 -16
- package/test/ai-gateway.test.ts +555 -0
- package/test/config-from-env.test.ts +184 -0
- package/test/config-schema.test.ts +28 -0
- package/test/goldens/supergraph.graphql +122 -0
- package/test/keyframe-reclaim-store.test.ts +156 -0
- package/test/processor-timing-log.test.ts +109 -0
- package/tsdown.config.ts +1 -0
- package/dist/from-env-BO0n9R02.mjs.map +0 -1
- package/dist/schema-0g_QdOWn.mjs.map +0 -1
- package/dist/schema-ivUWPQOn.d.mts.map +0 -1
- package/dist/server-YNY3Qw9a.mjs.map +0 -1
- package/dist/workflow-runtime-7GaJ13c9.d.mts.map +0 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/switchboard",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "6.2.3-dev.
|
|
4
|
+
"version": "6.2.3-dev.86",
|
|
5
5
|
"main": "dist/index.mjs",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": {
|
|
@@ -57,6 +57,12 @@
|
|
|
57
57
|
"types": "./dist/plugins/workflows.d.mts",
|
|
58
58
|
"import": "./dist/plugins/workflows.mjs",
|
|
59
59
|
"default": "./dist/plugins/workflows.mjs"
|
|
60
|
+
},
|
|
61
|
+
"./plugins/ai": {
|
|
62
|
+
"source": "./src/plugins/ai.mts",
|
|
63
|
+
"types": "./dist/plugins/ai.d.mts",
|
|
64
|
+
"import": "./dist/plugins/ai.mjs",
|
|
65
|
+
"default": "./dist/plugins/ai.mjs"
|
|
60
66
|
}
|
|
61
67
|
},
|
|
62
68
|
"engines": {
|
|
@@ -88,24 +94,24 @@
|
|
|
88
94
|
"@opentelemetry/sdk-node": "^0.218.0",
|
|
89
95
|
"@opentelemetry/sdk-trace-base": "^2.7.1",
|
|
90
96
|
"@opentelemetry/semantic-conventions": "^1.41.1",
|
|
91
|
-
"@powerhousedao/config": "6.2.3-dev.
|
|
92
|
-
"@powerhousedao/host-core": "6.2.3-dev.
|
|
93
|
-
"@powerhousedao/opentelemetry-instrumentation-reactor": "6.2.3-dev.
|
|
94
|
-
"@powerhousedao/reactor": "6.2.3-dev.
|
|
95
|
-
"@powerhousedao/reactor-api": "6.2.3-dev.
|
|
96
|
-
"@powerhousedao/reactor-attachments": "6.2.3-dev.
|
|
97
|
-
"@powerhousedao/reactor-drive": "6.2.3-dev.
|
|
98
|
-
"@powerhousedao/reactor-group": "6.2.3-dev.
|
|
99
|
-
"@powerhousedao/reactor-privacy": "6.2.3-dev.
|
|
100
|
-
"@powerhousedao/reactor-workflow": "6.2.3-dev.
|
|
101
|
-
"@powerhousedao/shared": "6.2.3-dev.
|
|
102
|
-
"@powerhousedao/vetra": "6.2.3-dev.
|
|
103
|
-
"@powerhousedao/workflow": "6.2.3-dev.
|
|
97
|
+
"@powerhousedao/config": "6.2.3-dev.86",
|
|
98
|
+
"@powerhousedao/host-core": "6.2.3-dev.86",
|
|
99
|
+
"@powerhousedao/opentelemetry-instrumentation-reactor": "6.2.3-dev.86",
|
|
100
|
+
"@powerhousedao/reactor": "6.2.3-dev.86",
|
|
101
|
+
"@powerhousedao/reactor-api": "6.2.3-dev.86",
|
|
102
|
+
"@powerhousedao/reactor-attachments": "6.2.3-dev.86",
|
|
103
|
+
"@powerhousedao/reactor-drive": "6.2.3-dev.86",
|
|
104
|
+
"@powerhousedao/reactor-group": "6.2.3-dev.86",
|
|
105
|
+
"@powerhousedao/reactor-privacy": "6.2.3-dev.86",
|
|
106
|
+
"@powerhousedao/reactor-workflow": "6.2.3-dev.86",
|
|
107
|
+
"@powerhousedao/shared": "6.2.3-dev.86",
|
|
108
|
+
"@powerhousedao/vetra": "6.2.3-dev.86",
|
|
109
|
+
"@powerhousedao/workflow": "6.2.3-dev.86",
|
|
104
110
|
"@pyroscope/nodejs": "^0.4.5",
|
|
105
|
-
"@renown/sdk": "6.2.3-dev.
|
|
111
|
+
"@renown/sdk": "6.2.3-dev.86",
|
|
106
112
|
"@sentry/node": "^10.53.1",
|
|
107
113
|
"@sentry/opentelemetry": "^10.53.1",
|
|
108
|
-
"document-model": "6.2.3-dev.
|
|
114
|
+
"document-model": "6.2.3-dev.86",
|
|
109
115
|
"dotenv": "^16.4.7",
|
|
110
116
|
"express": "^4.22.1",
|
|
111
117
|
"graphql": "^16",
|
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
// The AI gateway on a booted Switchboard: real did:key bearers, the real
|
|
2
|
+
// encrypted secret store, and a stub provider that records what it was sent
|
|
3
|
+
// and echoes the credentials back wherever a careless proxy would repeat them.
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
6
|
+
import {
|
|
7
|
+
createServer,
|
|
8
|
+
type IncomingMessage,
|
|
9
|
+
type Server,
|
|
10
|
+
type ServerResponse,
|
|
11
|
+
} from "node:http";
|
|
12
|
+
import type { AddressInfo } from "node:net";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import type { HostPlugin, ResolvedPlugin } from "@powerhousedao/host-core";
|
|
16
|
+
import { MemoryKeyStorage, RenownCryptoBuilder } from "@renown/sdk/node";
|
|
17
|
+
import type { ILogger } from "document-model";
|
|
18
|
+
import {
|
|
19
|
+
afterAll,
|
|
20
|
+
afterEach,
|
|
21
|
+
beforeAll,
|
|
22
|
+
describe,
|
|
23
|
+
expect,
|
|
24
|
+
it,
|
|
25
|
+
vi,
|
|
26
|
+
} from "vitest";
|
|
27
|
+
import { maskKey } from "../src/ai/key-store.mjs";
|
|
28
|
+
import { redactSecrets } from "../src/ai/routes.mjs";
|
|
29
|
+
import { createAiPlugin } from "../src/plugins/ai.mjs";
|
|
30
|
+
import { workflowsPlugin } from "../src/plugins/workflows.mjs";
|
|
31
|
+
import type { SwitchboardReactor } from "../src/types.js";
|
|
32
|
+
import { bootSwitchboard } from "./boot-helpers.js";
|
|
33
|
+
|
|
34
|
+
const ADMIN = "0x1111111111111111111111111111111111111111";
|
|
35
|
+
const USER = "0x2222222222222222222222222222222222222222";
|
|
36
|
+
const KEY = `sk-or-v1-${randomBytes(24).toString("hex")}`;
|
|
37
|
+
const OTHER_KEY = `sk-or-v1-${randomBytes(24).toString("hex")}`;
|
|
38
|
+
const BAD_KEY = `sk-or-v1-${randomBytes(24).toString("hex")}`;
|
|
39
|
+
const DEFAULT_MODEL = "qwen/test-vision";
|
|
40
|
+
const MODELS = { data: [{ id: DEFAULT_MODEL }, { id: "qwen/other" }] };
|
|
41
|
+
const GATEWAY = "/api/@powerhousedao/switchboard/ai";
|
|
42
|
+
|
|
43
|
+
const ENV_KEYS = [
|
|
44
|
+
"PH_REACTOR_DATABASE_URL",
|
|
45
|
+
"PH_WORKFLOWS_SECRETS_MASTER_KEY",
|
|
46
|
+
"MCP_ENABLED",
|
|
47
|
+
"FEATURE_PLUGIN_HOST_ENABLED",
|
|
48
|
+
"AUTH_ENABLED",
|
|
49
|
+
"ADMINS",
|
|
50
|
+
"RESOLVE_CALLER_IDENTITY",
|
|
51
|
+
"SKIP_CREDENTIAL_VERIFICATION",
|
|
52
|
+
] as const;
|
|
53
|
+
|
|
54
|
+
const logger = {
|
|
55
|
+
verbose: vi.fn(),
|
|
56
|
+
debug: vi.fn(),
|
|
57
|
+
info: vi.fn(),
|
|
58
|
+
warn: vi.fn(),
|
|
59
|
+
error: vi.fn(),
|
|
60
|
+
child: () => logger,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type Seen = { path: string; authorization?: string; body: string };
|
|
64
|
+
type Stub = (req: IncomingMessage, res: ServerResponse, seen: Seen) => void;
|
|
65
|
+
|
|
66
|
+
const seen: Seen[] = [];
|
|
67
|
+
let answerChat: Stub | undefined;
|
|
68
|
+
let chatClosed: Promise<void> | undefined;
|
|
69
|
+
|
|
70
|
+
/** Echoes the credential in the body, as a careless upstream error might. */
|
|
71
|
+
function echoRefusal(
|
|
72
|
+
res: ServerResponse,
|
|
73
|
+
status: number,
|
|
74
|
+
authorization: string | undefined,
|
|
75
|
+
) {
|
|
76
|
+
res.statusCode = status;
|
|
77
|
+
res.setHeader("content-type", "application/json");
|
|
78
|
+
res.end(
|
|
79
|
+
JSON.stringify({
|
|
80
|
+
error: { message: `Refused ${authorization ?? ""}`, code: "refused" },
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function stubProvider(req: IncomingMessage, res: ServerResponse): void {
|
|
86
|
+
const chunks: Buffer[] = [];
|
|
87
|
+
req.on("data", (chunk: Buffer) => chunks.push(chunk));
|
|
88
|
+
req.on("end", () => {
|
|
89
|
+
const entry: Seen = {
|
|
90
|
+
path: req.url ?? "",
|
|
91
|
+
authorization: req.headers.authorization,
|
|
92
|
+
body: Buffer.concat(chunks).toString("utf8"),
|
|
93
|
+
};
|
|
94
|
+
seen.push(entry);
|
|
95
|
+
if (req.url === "/key") {
|
|
96
|
+
if (req.headers.authorization === `Bearer ${BAD_KEY}`) {
|
|
97
|
+
echoRefusal(res, 401, req.headers.authorization);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
res.setHeader("content-type", "application/json");
|
|
101
|
+
res.end(JSON.stringify({ data: { label: "stub" } }));
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (req.url === "/models") {
|
|
105
|
+
res.setHeader("content-type", "application/json");
|
|
106
|
+
res.end(JSON.stringify(MODELS));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (answerChat) {
|
|
110
|
+
answerChat(req, res, entry);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
res.setHeader("content-type", "text/event-stream");
|
|
114
|
+
res.end('data: {"choices":[]}\n\ndata: [DONE]\n\n');
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
let tempRoot = "";
|
|
119
|
+
let previous: [string, string | undefined][] = [];
|
|
120
|
+
let switchboard: SwitchboardReactor | undefined;
|
|
121
|
+
let provider: Server;
|
|
122
|
+
const tokens: Record<string, string> = {};
|
|
123
|
+
const consoleLines: string[] = [];
|
|
124
|
+
|
|
125
|
+
const resolved = (plugin: HostPlugin, module: string): ResolvedPlugin => ({
|
|
126
|
+
plugin,
|
|
127
|
+
provenance: "built-in",
|
|
128
|
+
entry: { enabled: true, verbs: "*", config: {}, module },
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
async function bearerFor(address: string): Promise<string> {
|
|
132
|
+
const crypto = await new RenownCryptoBuilder()
|
|
133
|
+
.withKeyPairStorage(new MemoryKeyStorage())
|
|
134
|
+
.build();
|
|
135
|
+
return crypto.getBearerToken(address);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
type Caller = typeof ADMIN | typeof USER | "anonymous";
|
|
139
|
+
|
|
140
|
+
function call(
|
|
141
|
+
caller: Caller,
|
|
142
|
+
path: string,
|
|
143
|
+
init: { method?: string; body?: string; signal?: AbortSignal } = {},
|
|
144
|
+
): Promise<Response> {
|
|
145
|
+
return fetch(`http://127.0.0.1:${switchboard!.port}${GATEWAY}${path}`, {
|
|
146
|
+
...init,
|
|
147
|
+
headers: {
|
|
148
|
+
"content-type": "application/json",
|
|
149
|
+
...(caller === "anonymous"
|
|
150
|
+
? {}
|
|
151
|
+
: { authorization: `Bearer ${tokens[caller]}` }),
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const setKey = (value: string) =>
|
|
157
|
+
call(ADMIN, "/key", { method: "PUT", body: JSON.stringify({ value }) });
|
|
158
|
+
|
|
159
|
+
const chat = (body: unknown, signal?: AbortSignal) =>
|
|
160
|
+
call(ADMIN, "/v1/chat/completions", {
|
|
161
|
+
method: "POST",
|
|
162
|
+
body: JSON.stringify(body),
|
|
163
|
+
signal,
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
const lastChat = () => seen.findLast((s) => s.path === "/chat/completions")!;
|
|
167
|
+
|
|
168
|
+
beforeAll(async () => {
|
|
169
|
+
provider = createServer(stubProvider);
|
|
170
|
+
await new Promise<void>((resolve) =>
|
|
171
|
+
provider.listen(0, "127.0.0.1", resolve),
|
|
172
|
+
);
|
|
173
|
+
const upstreamUrl = `http://127.0.0.1:${(provider.address() as AddressInfo).port}`;
|
|
174
|
+
|
|
175
|
+
tempRoot = await mkdtemp(join(tmpdir(), "switchboard-ai-gateway-"));
|
|
176
|
+
previous = ENV_KEYS.map((name) => [name, process.env[name]]);
|
|
177
|
+
for (const name of ENV_KEYS) delete process.env[name];
|
|
178
|
+
process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
|
|
179
|
+
process.env.PH_WORKFLOWS_SECRETS_MASTER_KEY = randomBytes(32).toString("hex");
|
|
180
|
+
process.env.FEATURE_PLUGIN_HOST_ENABLED = "1";
|
|
181
|
+
|
|
182
|
+
for (const method of ["log", "info", "warn", "error"] as const) {
|
|
183
|
+
vi.spyOn(console, method).mockImplementation((...args: unknown[]) => {
|
|
184
|
+
consoleLines.push(args.map(String).join(" "));
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
switchboard = await bootSwitchboard(
|
|
189
|
+
{
|
|
190
|
+
server: { port: 0 },
|
|
191
|
+
storage: { readModel: { url: join(tempRoot, "read-model") } },
|
|
192
|
+
features: { workflows: true, mcp: false },
|
|
193
|
+
packages: { disableLocal: true },
|
|
194
|
+
identity: { keypairPath: join(tempRoot, "identity.json") },
|
|
195
|
+
auth: {
|
|
196
|
+
enabled: true,
|
|
197
|
+
admins: [ADMIN],
|
|
198
|
+
skipCredentialVerification: true,
|
|
199
|
+
renown: { switchboardUrl: "http://127.0.0.1:9/graphql" },
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
{
|
|
203
|
+
logger: logger as unknown as ILogger,
|
|
204
|
+
pluginComposition: [
|
|
205
|
+
resolved(
|
|
206
|
+
workflowsPlugin as HostPlugin,
|
|
207
|
+
"@powerhousedao/switchboard/plugins/workflows",
|
|
208
|
+
),
|
|
209
|
+
resolved(
|
|
210
|
+
createAiPlugin({
|
|
211
|
+
defaultModel: DEFAULT_MODEL,
|
|
212
|
+
maxOutputTokens: 1000,
|
|
213
|
+
upstreamUrl,
|
|
214
|
+
}) as HostPlugin,
|
|
215
|
+
"@powerhousedao/switchboard/plugins/ai",
|
|
216
|
+
),
|
|
217
|
+
],
|
|
218
|
+
},
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
tokens[ADMIN] = await bearerFor(ADMIN);
|
|
222
|
+
tokens[USER] = await bearerFor(USER);
|
|
223
|
+
}, 120_000);
|
|
224
|
+
|
|
225
|
+
afterAll(async () => {
|
|
226
|
+
await switchboard?.shutdown();
|
|
227
|
+
await new Promise((resolve) => provider.close(resolve));
|
|
228
|
+
vi.restoreAllMocks();
|
|
229
|
+
for (const [name, value] of previous) {
|
|
230
|
+
if (value === undefined) delete process.env[name];
|
|
231
|
+
else process.env[name] = value;
|
|
232
|
+
}
|
|
233
|
+
await rm(tempRoot, { recursive: true, force: true });
|
|
234
|
+
}, 60_000);
|
|
235
|
+
|
|
236
|
+
afterEach(() => {
|
|
237
|
+
answerChat = undefined;
|
|
238
|
+
chatClosed = undefined;
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
describe("the gateway on a signed-in host", () => {
|
|
242
|
+
it("answers only admins, on every route", async () => {
|
|
243
|
+
const routes: [string, string][] = [
|
|
244
|
+
["GET", "/status"],
|
|
245
|
+
["PUT", "/key"],
|
|
246
|
+
["DELETE", "/key"],
|
|
247
|
+
["PUT", "/model"],
|
|
248
|
+
["GET", "/v1/models"],
|
|
249
|
+
["POST", "/v1/chat/completions"],
|
|
250
|
+
];
|
|
251
|
+
for (const [method, path] of routes) {
|
|
252
|
+
const body = method === "GET" ? undefined : "{}";
|
|
253
|
+
const anonymous = await call("anonymous", path, { method, body });
|
|
254
|
+
expect([method, path, anonymous.status]).toEqual([method, path, 401]);
|
|
255
|
+
const user = await call(USER, path, { method, body });
|
|
256
|
+
expect([method, path, user.status]).toEqual([method, path, 403]);
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("reports not configured, and the chat refuses until a key is set", async () => {
|
|
261
|
+
const status = await call(ADMIN, "/status");
|
|
262
|
+
expect(status.status).toBe(200);
|
|
263
|
+
expect(await status.json()).toEqual({
|
|
264
|
+
configured: false,
|
|
265
|
+
keyHint: null,
|
|
266
|
+
keySetBy: null,
|
|
267
|
+
keySetAt: null,
|
|
268
|
+
model: DEFAULT_MODEL,
|
|
269
|
+
});
|
|
270
|
+
const refused = await chat({ messages: [] });
|
|
271
|
+
expect(refused.status).toBe(503);
|
|
272
|
+
expect(await refused.text()).toContain("not_configured");
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it("does not store a key the provider refuses, nor repeat it", async () => {
|
|
276
|
+
const answer = await setKey(BAD_KEY);
|
|
277
|
+
expect(answer.status).toBe(400);
|
|
278
|
+
expect(await answer.text()).not.toContain(BAD_KEY);
|
|
279
|
+
const status = (await (await call(ADMIN, "/status")).json()) as {
|
|
280
|
+
configured: boolean;
|
|
281
|
+
};
|
|
282
|
+
expect(status.configured).toBe(false);
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it("does not repeat a malformed body that holds a key", async () => {
|
|
286
|
+
const answer = await call(ADMIN, "/key", {
|
|
287
|
+
method: "PUT",
|
|
288
|
+
body: `${BAD_KEY} is not JSON`,
|
|
289
|
+
});
|
|
290
|
+
expect(answer.status).toBe(400);
|
|
291
|
+
expect(await answer.text()).not.toContain(BAD_KEY);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("stores a key the provider accepts and shows only a hint", async () => {
|
|
295
|
+
const answer = await setKey(KEY);
|
|
296
|
+
expect(answer.status).toBe(200);
|
|
297
|
+
const text = await answer.text();
|
|
298
|
+
expect(text).not.toContain(KEY);
|
|
299
|
+
const status = JSON.parse(text) as Record<string, unknown>;
|
|
300
|
+
expect(status).toMatchObject({
|
|
301
|
+
configured: true,
|
|
302
|
+
keyHint: `sk-or-v1-…${KEY.slice(-4)}`,
|
|
303
|
+
keySetBy: ADMIN,
|
|
304
|
+
model: DEFAULT_MODEL,
|
|
305
|
+
});
|
|
306
|
+
expect(seen.at(-1)).toMatchObject({
|
|
307
|
+
path: "/key",
|
|
308
|
+
authorization: `Bearer ${KEY}`,
|
|
309
|
+
});
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
it("keeps the working key when a replacement is refused", async () => {
|
|
313
|
+
expect((await setKey(BAD_KEY)).status).toBe(400);
|
|
314
|
+
const status = (await (await call(ADMIN, "/status")).json()) as {
|
|
315
|
+
keyHint: string;
|
|
316
|
+
};
|
|
317
|
+
expect(status.keyHint).toContain(KEY.slice(-4));
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
it("forwards a chat with the stored key, the host's model and capped tokens", async () => {
|
|
321
|
+
const answer = await chat({
|
|
322
|
+
model: "someone/expensive",
|
|
323
|
+
provider: { order: ["x"] },
|
|
324
|
+
max_tokens: 999_999,
|
|
325
|
+
stream: true,
|
|
326
|
+
messages: [
|
|
327
|
+
{
|
|
328
|
+
role: "user",
|
|
329
|
+
content: [
|
|
330
|
+
{ type: "text", text: "What is this?" },
|
|
331
|
+
{
|
|
332
|
+
type: "image_url",
|
|
333
|
+
image_url: { url: "data:image/png;base64,AAAA" },
|
|
334
|
+
},
|
|
335
|
+
],
|
|
336
|
+
},
|
|
337
|
+
],
|
|
338
|
+
});
|
|
339
|
+
expect(answer.status).toBe(200);
|
|
340
|
+
expect(answer.headers.get("content-type")).toContain("text/event-stream");
|
|
341
|
+
await answer.text();
|
|
342
|
+
|
|
343
|
+
const forwarded = lastChat();
|
|
344
|
+
expect(forwarded.authorization).toBe(`Bearer ${KEY}`);
|
|
345
|
+
const body = JSON.parse(forwarded.body) as Record<string, unknown>;
|
|
346
|
+
expect(body.model).toBe(DEFAULT_MODEL);
|
|
347
|
+
expect(body.max_tokens).toBe(1000);
|
|
348
|
+
expect(body.provider).toBeUndefined();
|
|
349
|
+
expect(JSON.stringify(body.messages)).toContain(
|
|
350
|
+
"data:image/png;base64,AAAA",
|
|
351
|
+
);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
it("streams the answer through as it is produced", async () => {
|
|
355
|
+
let finish = () => {};
|
|
356
|
+
const finishing = new Promise<void>((resolve) => {
|
|
357
|
+
finish = resolve;
|
|
358
|
+
});
|
|
359
|
+
answerChat = (_req, res) => {
|
|
360
|
+
res.setHeader("content-type", "text/event-stream");
|
|
361
|
+
res.write("data: first\n\n");
|
|
362
|
+
void finishing.then(() => res.end("data: second\n\n"));
|
|
363
|
+
};
|
|
364
|
+
const answer = await chat({ messages: [], stream: true });
|
|
365
|
+
const reader = (answer.body as ReadableStream<Uint8Array>).getReader();
|
|
366
|
+
const first = await reader.read();
|
|
367
|
+
// The first event arrived while the provider is still holding the rest.
|
|
368
|
+
expect(new TextDecoder().decode(first.value)).toContain("first");
|
|
369
|
+
finish();
|
|
370
|
+
let rest = "";
|
|
371
|
+
for (;;) {
|
|
372
|
+
const next = await reader.read();
|
|
373
|
+
if (next.done) break;
|
|
374
|
+
rest += new TextDecoder().decode(next.value);
|
|
375
|
+
}
|
|
376
|
+
expect(rest).toContain("second");
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
it("stops the provider's call when the client goes away", async () => {
|
|
380
|
+
chatClosed = new Promise<void>((resolve) => {
|
|
381
|
+
answerChat = (_req, res) => {
|
|
382
|
+
res.setHeader("content-type", "text/event-stream");
|
|
383
|
+
res.write("data: first\n\n");
|
|
384
|
+
res.on("close", resolve);
|
|
385
|
+
};
|
|
386
|
+
});
|
|
387
|
+
const controller = new AbortController();
|
|
388
|
+
const answer = await chat(
|
|
389
|
+
{ messages: [], stream: true },
|
|
390
|
+
controller.signal,
|
|
391
|
+
);
|
|
392
|
+
await answer.body!.getReader().read();
|
|
393
|
+
controller.abort();
|
|
394
|
+
await chatClosed;
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
it("keeps the provider's status but never echoes the key from an error", async () => {
|
|
398
|
+
answerChat = (req, res) => echoRefusal(res, 429, req.headers.authorization);
|
|
399
|
+
const answer = await chat({ messages: [] });
|
|
400
|
+
expect(answer.status).toBe(429);
|
|
401
|
+
const text = await answer.text();
|
|
402
|
+
expect(text).toContain("Refused");
|
|
403
|
+
expect(text).not.toContain(KEY);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
it("does not pass on an error body that is not JSON", async () => {
|
|
407
|
+
answerChat = (req, res) => {
|
|
408
|
+
res.statusCode = 500;
|
|
409
|
+
res.end(`upstream trace, headers: ${req.headers.authorization}`);
|
|
410
|
+
};
|
|
411
|
+
const answer = await chat({ messages: [] });
|
|
412
|
+
expect(answer.status).toBe(500);
|
|
413
|
+
expect(await answer.text()).not.toContain(KEY);
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
it("lists the provider's models", async () => {
|
|
417
|
+
const answer = await call(ADMIN, "/v1/models");
|
|
418
|
+
expect(answer.status).toBe(200);
|
|
419
|
+
expect(await answer.json()).toEqual(MODELS);
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it("takes only a model the provider has, and chats with it", async () => {
|
|
423
|
+
const unknown = await call(ADMIN, "/model", {
|
|
424
|
+
method: "PUT",
|
|
425
|
+
body: JSON.stringify({ model: "nobody/nothing" }),
|
|
426
|
+
});
|
|
427
|
+
expect(unknown.status).toBe(400);
|
|
428
|
+
|
|
429
|
+
const known = await call(ADMIN, "/model", {
|
|
430
|
+
method: "PUT",
|
|
431
|
+
body: JSON.stringify({ model: "qwen/other" }),
|
|
432
|
+
});
|
|
433
|
+
expect(known.status).toBe(200);
|
|
434
|
+
expect(await known.json()).toMatchObject({ model: "qwen/other" });
|
|
435
|
+
|
|
436
|
+
await (await chat({ messages: [] })).text();
|
|
437
|
+
expect(JSON.parse(lastChat().body)).toMatchObject({ model: "qwen/other" });
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
it("rotates on a second set, so the old key stops being used", async () => {
|
|
441
|
+
expect((await setKey(OTHER_KEY)).status).toBe(200);
|
|
442
|
+
await (await chat({ messages: [] })).text();
|
|
443
|
+
expect(lastChat().authorization).toBe(`Bearer ${OTHER_KEY}`);
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
it("forgets the key on reset", async () => {
|
|
447
|
+
const answer = await call(ADMIN, "/key", { method: "DELETE" });
|
|
448
|
+
expect(answer.status).toBe(200);
|
|
449
|
+
expect(await answer.json()).toMatchObject({
|
|
450
|
+
configured: false,
|
|
451
|
+
keyHint: null,
|
|
452
|
+
});
|
|
453
|
+
expect((await chat({ messages: [] })).status).toBe(503);
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
it("logged no key at any point", () => {
|
|
457
|
+
const logged = [
|
|
458
|
+
...consoleLines,
|
|
459
|
+
...[logger.debug, logger.info, logger.warn, logger.error].flatMap((fn) =>
|
|
460
|
+
fn.mock.calls.map((args) => JSON.stringify(args)),
|
|
461
|
+
),
|
|
462
|
+
].join("\n");
|
|
463
|
+
expect(logged.length).toBeGreaterThan(0);
|
|
464
|
+
for (const key of [KEY, OTHER_KEY, BAD_KEY]) {
|
|
465
|
+
expect(logged).not.toContain(key);
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
describe("the plugin's mount", () => {
|
|
471
|
+
const fakeContext = (policy: string) => {
|
|
472
|
+
const route = vi.fn();
|
|
473
|
+
const warn = vi.fn();
|
|
474
|
+
return {
|
|
475
|
+
route,
|
|
476
|
+
warn,
|
|
477
|
+
ctx: {
|
|
478
|
+
logger: { warn },
|
|
479
|
+
options: {},
|
|
480
|
+
renown: null,
|
|
481
|
+
contributions: {},
|
|
482
|
+
api: {
|
|
483
|
+
authorizationService: {
|
|
484
|
+
config: { policy },
|
|
485
|
+
isSupremeAdmin: () => true,
|
|
486
|
+
},
|
|
487
|
+
httpRoutes: { scopeFor: () => ({ route }) },
|
|
488
|
+
},
|
|
489
|
+
} as never,
|
|
490
|
+
};
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
it("stays off without sign-in, where everyone would be an admin", () => {
|
|
494
|
+
const { ctx, route, warn } = fakeContext("OPEN");
|
|
495
|
+
createAiPlugin({ defaultModel: "m" }).hooks?.onHttpMounting?.(ctx);
|
|
496
|
+
expect(route).not.toHaveBeenCalled();
|
|
497
|
+
expect(warn).toHaveBeenCalledOnce();
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
it("mounts without sign-in only when told to", () => {
|
|
501
|
+
const { ctx, route } = fakeContext("OPEN");
|
|
502
|
+
createAiPlugin({
|
|
503
|
+
defaultModel: "m",
|
|
504
|
+
allowWithoutAuth: true,
|
|
505
|
+
}).hooks?.onHttpMounting?.(ctx);
|
|
506
|
+
expect(route).toHaveBeenCalled();
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
it("answers 503 while the workflow runtime is absent", async () => {
|
|
510
|
+
const { ctx, route } = fakeContext("ADMIN_ONLY");
|
|
511
|
+
createAiPlugin({ defaultModel: "m" }).hooks?.onHttpMounting?.(ctx);
|
|
512
|
+
const status = route.mock.calls
|
|
513
|
+
.map(
|
|
514
|
+
([spec]) =>
|
|
515
|
+
spec as {
|
|
516
|
+
method: string;
|
|
517
|
+
path: string;
|
|
518
|
+
handler: (r: Request, c: unknown) => Promise<Response>;
|
|
519
|
+
},
|
|
520
|
+
)
|
|
521
|
+
.find((spec) => spec.path === "ai/status")!;
|
|
522
|
+
const answer = await status.handler(
|
|
523
|
+
new Request("http://localhost/status"),
|
|
524
|
+
{},
|
|
525
|
+
);
|
|
526
|
+
expect(answer.status).toBe(503);
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
it("requires a default model and rejects a typo'd key", () => {
|
|
530
|
+
expect(() => createAiPlugin({})).toThrow();
|
|
531
|
+
expect(() => createAiPlugin({ defaultModel: "m", modle: "x" })).toThrow();
|
|
532
|
+
});
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
describe("masking", () => {
|
|
536
|
+
it("keeps the provider prefix and the last four", () => {
|
|
537
|
+
expect(maskKey("sk-or-v1-0123456789abcdef0123456789abcd")).toBe(
|
|
538
|
+
"sk-or-v1-…abcd",
|
|
539
|
+
);
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
it("shows no tail of a short value", () => {
|
|
543
|
+
expect(maskKey("sk-or-v1-abcd")).toBe("sk-or-v1-…");
|
|
544
|
+
expect(maskKey("short")).toBe("…");
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
it("removes the key and anything shaped like one", () => {
|
|
548
|
+
expect(
|
|
549
|
+
redactSecrets(
|
|
550
|
+
"a Bearer xyz b sk-or-v1-aaaabbbbcccc c opaque d",
|
|
551
|
+
"opaque",
|
|
552
|
+
),
|
|
553
|
+
).toBe("a Bearer [redacted] b [redacted] c [redacted] d");
|
|
554
|
+
});
|
|
555
|
+
});
|