Adds packages/search1api as @magpie-community/tools-search1api 0.1.0
(fatwang2, replacing #340). It has six tools: search, news, ask, crawl,
sitemap and trending. Sign-in is one account by API key or OAuth: PKCE
S256, dynamic client registration and a loopback callback. Tokens refresh
through auth.refresh and on a 401. scripts/check.mjs now accepts a tools
plugin with auth and no loader, as long as its config gives the provider
no npm and no models.
Run at 7cf6a5c merged onto main, in a sandbox HOME, with HTTPS_PROXY
pointed at a dead port:
- bun test packages/search1api scripts/check.test.mjs: 19 pass.
- node --test on the package's own tests: 16 pass.
- tests/host.integration.mjs against main magpie's host.js: 2 pass.
- bun test across the whole repo: 2647 pass, 0 fail. This needs 017f05c.
Before it, gcp-ai's fetch guard refused this package's loopback
fixtures in the shared bun process.
- bun scripts/check.mjs: all ok.
Broken by hand, each one red:
- Dropping the SAME_SESSION check before a refresh: 1 test.
- Never refreshing an expired token: 3 tests.
- Ignoring the apiKey option: 4 tests.
- Not red: dropping the second check, which catches a logout during an
in-flight refresh. The first check covers it in the logout test.
Real use:
- A sandbox magpie took the package with `plugin add`. `plugin list`
shows its 6 tools. `plugin login search1api 2` with a key showed
Providers as "Search1API · signed in as API key …-384 · no models
exposed".
- The search tool ran against the real api.search1api.com with a fake
key and got 401.
- OAuth discovery is live: oauth-protected-resource points to
clerk.s1.dev, which has a registration endpoint and S256.
Not tried:
- A real OAuth consent, or a search with a real key. There is no
Search1API account here.
Notes:
- The plugin reads the signed-in record from
`<directory>/plugin-auth.json` itself, since tools get no getAuth.
magpie writes that file by temp-and-rename, so a read never sees half a
write.
- magpie's login line says "its models are search1api/<model>" for a
provider with no models. That is magpie's wording, not this PR's.
192 lines
5.6 KiB
JavaScript
192 lines
5.6 KiB
JavaScript
import { createHash } from "node:crypto";
|
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
import { createServer } from "node:http";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
|
|
export async function fixture(t) {
|
|
const directory = await mkdtemp(join(tmpdir(), "magpie-search1api-test-"));
|
|
const calls = [];
|
|
const state = {
|
|
refreshes: 0,
|
|
grants: 0,
|
|
decline: false,
|
|
rejectRefresh: false,
|
|
rejectAccess: false,
|
|
refreshDelay: 0,
|
|
};
|
|
let registration;
|
|
let authorization;
|
|
let baseUrl;
|
|
const server = createServer(async (req, res) => {
|
|
const url = new URL(req.url, baseUrl);
|
|
let raw = "";
|
|
for await (const chunk of req) raw += chunk;
|
|
const form = new URLSearchParams(raw);
|
|
const json = (value, status = 200) => {
|
|
res.writeHead(status, { "Content-Type": "application/json" });
|
|
res.end(JSON.stringify(value));
|
|
};
|
|
calls.push({
|
|
path: url.pathname,
|
|
method: req.method,
|
|
headers: req.headers,
|
|
raw,
|
|
});
|
|
if (url.pathname === "/.well-known/oauth-protected-resource")
|
|
return json({ authorization_servers: [baseUrl] });
|
|
if (url.pathname === "/.well-known/oauth-authorization-server")
|
|
return json({
|
|
issuer: baseUrl,
|
|
authorization_endpoint: `${baseUrl}/authorize`,
|
|
token_endpoint: `${baseUrl}/token`,
|
|
registration_endpoint: `${baseUrl}/register`,
|
|
code_challenge_methods_supported: ["S256"],
|
|
});
|
|
if (url.pathname === "/register") {
|
|
registration = JSON.parse(raw);
|
|
return json({
|
|
client_id: "test-public-client",
|
|
token_endpoint_auth_method: "none",
|
|
});
|
|
}
|
|
if (url.pathname === "/authorize") {
|
|
authorization = url;
|
|
const redirect = new URL(url.searchParams.get("redirect_uri"));
|
|
redirect.searchParams.set("state", url.searchParams.get("state"));
|
|
redirect.searchParams.set("iss", baseUrl);
|
|
redirect.searchParams.set(
|
|
state.decline ? "error" : "code",
|
|
state.decline ? "access_denied" : "test-authorization-code",
|
|
);
|
|
res.writeHead(302, { location: redirect.href }).end();
|
|
return;
|
|
}
|
|
if (url.pathname === "/token") {
|
|
if (form.get("grant_type") === "authorization_code") {
|
|
if (
|
|
form.get("client_id") !== "test-public-client" ||
|
|
form.get("code") !== "test-authorization-code" ||
|
|
form.get("redirect_uri") !== registration.redirect_uris[0] ||
|
|
createHash("sha256")
|
|
.update(form.get("code_verifier") ?? "")
|
|
.digest("base64url") !==
|
|
authorization.searchParams.get("code_challenge")
|
|
) {
|
|
return json({ error: "invalid_grant" }, 400);
|
|
}
|
|
state.grants++;
|
|
return json({
|
|
access_token: "test-access-0",
|
|
refresh_token: "test-refresh-0",
|
|
expires_in: 3600,
|
|
token_type: "Bearer",
|
|
});
|
|
}
|
|
if (state.refreshDelay)
|
|
await new Promise((r) => setTimeout(r, state.refreshDelay));
|
|
if (
|
|
state.rejectRefresh ||
|
|
form.get("client_id") !== "test-public-client" ||
|
|
form.get("refresh_token") !== `test-refresh-${state.refreshes}`
|
|
) {
|
|
return json(
|
|
{ error: "invalid_grant", private: "must-not-appear-in-errors" },
|
|
400,
|
|
);
|
|
}
|
|
state.refreshes++;
|
|
return json({
|
|
access_token: `test-access-${state.refreshes}`,
|
|
refresh_token: `test-refresh-${state.refreshes}`,
|
|
expires_in: 3600,
|
|
});
|
|
}
|
|
if (
|
|
state.rejectAccess &&
|
|
req.headers.authorization === "Bearer test-access-0"
|
|
)
|
|
return json({ message: "expired" }, 401);
|
|
return json({
|
|
query: "fixture",
|
|
intent: { sources: ["github"], time_range: "week" },
|
|
results: [
|
|
{
|
|
title: "Example",
|
|
link: "https://example.com",
|
|
snippet: "Result",
|
|
published_date: "2026-10-23",
|
|
source: "github",
|
|
relevance: 0.9,
|
|
metadata: { stars: 0 },
|
|
},
|
|
],
|
|
errors: [],
|
|
});
|
|
});
|
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
baseUrl = `http://127.0.0.1:${server.address().port}`;
|
|
t.after(async () => {
|
|
server.closeAllConnections();
|
|
await new Promise((resolve) => server.close(resolve));
|
|
await rm(directory, { recursive: true, force: true });
|
|
});
|
|
const authPath = join(directory, "plugin-auth.json");
|
|
const readAuth = async () => {
|
|
try {
|
|
return JSON.parse(await readFile(authPath, "utf8"));
|
|
} catch (e) {
|
|
if (e.code === "ENOENT") return {};
|
|
throw e;
|
|
}
|
|
};
|
|
const save = async (auth) => {
|
|
const all = await readAuth();
|
|
all.search1api = auth;
|
|
await writeFile(authPath, JSON.stringify(all), { mode: 0o600 });
|
|
};
|
|
const input = {
|
|
directory,
|
|
client: {
|
|
auth: {
|
|
set: async ({ path, body }) => {
|
|
const all = await readAuth();
|
|
all[path.id] = body;
|
|
await writeFile(authPath, JSON.stringify(all), { mode: 0o600 });
|
|
return { data: true };
|
|
},
|
|
},
|
|
},
|
|
};
|
|
return {
|
|
directory,
|
|
input,
|
|
calls,
|
|
state,
|
|
baseUrl,
|
|
authPath,
|
|
save,
|
|
readAuth,
|
|
oauth: () => ({
|
|
type: "oauth",
|
|
access: "test-access-0",
|
|
refresh: "test-refresh-0",
|
|
expires: Date.now() + 3600_000,
|
|
clientId: "test-public-client",
|
|
tokenEndpoint: `${baseUrl}/token`,
|
|
issuer: baseUrl,
|
|
}),
|
|
};
|
|
}
|
|
|
|
export const context = (signal) => ({
|
|
sessionID: "test",
|
|
messageID: "test",
|
|
agent: "test",
|
|
directory: "",
|
|
worktree: "",
|
|
abort: signal ?? new AbortController().signal,
|
|
metadata() {},
|
|
async ask() {},
|
|
});
|