search1api 0.1.1: Magpie attribution, reused OAuth client, send_feedback through Search1API (#424)

search1api 0.1.1 (fatwang2):
- Sign-ins carry utm_source=magpie and API requests send User-Agent search1api-magpie/0.1.1.
- The registered public OAuth client and its loopback port are saved in search1api-oauth-client.json (mode 600) and reused. A busy port, another issuer, or a sign-in that doesn't finish leads to a new registration.
- A send_feedback tool posts to Search1API's own POST /feedback with the caller's credential, on the same request path as the other tools, including the OAuth refresh on 401. Its description lists what is sent (message, intent, category, request_id, model) and says Search1API stores it on agentback.app, linked to the signed-in account. The plugin contacts no other host. A report that can't be sent returns a note and doesn't fail the task.

Run at the reviewed head d48c8c8 (sandbox HOME/TMPDIR, Bun 1.4.2):
- bun test packages/search1api/tests: 23 pass, 0 fail
- bun scripts/check.mjs search1api: ok
- PR CI (test, on-npm): pass
- grep of the package: the only host is api.search1api.com (plus 127.0.0.1 for the callback). No hard-coded keys. agentback.app appears only in the description, the README and a test.
- Drove the built plugin against my own loopback fake API:
  - OAuth access revoked (401): POST /feedback with the old bearer, then /token refresh_token, then POST /feedback with the new bearer. Got "Feedback recorded (fb_1)" and auth.set with the new token.
  - Bad API key: a 401 gives "not recorded ... (401)" with no refresh, and the error body is not echoed.
  - Body is exactly {message, intent, category, request_id, agent:{name:"Magpie", model}}, with UA search1api-magpie/0.1.1.
  - Unknown args and a non-string model are refused before any request.
- An unauthenticated probe of the real api.search1api.com: POST /feedback gives 401, and an unknown path gives 404. So the endpoint exists.
- The OAuth client reuse (unchanged since 95f236f) was run by hand in the previous review.

Not tried: a real Search1API account (none available).
This commit is contained in:
wang2
2026-10-27 15:44:05 +08:00
committed by GitHub
parent a9779ef864
commit 6a2ade35ef
11 changed files with 344 additions and 55 deletions
+15 -2
View File
@@ -39,6 +39,13 @@ access, then return to Magpie. The plugin uses a dynamically registered public
OAuth client, authorization code flow with PKCE S256, and a temporary loopback OAuth client, authorization code flow with PKCE S256, and a temporary loopback
callback. No client secret or Search1API CLI is required. callback. No client secret or Search1API CLI is required.
The client is registered once and saved, with its callback port, in
`search1api-oauth-client.json` next to `plugin-auth.json`; later sign-ins
reuse it. If that port is busy, or a sign-in with the saved client does not
finish, the plugin registers a new client. The authorization URL carries
`utm_source=magpie` and API requests send `User-Agent: search1api-magpie/<version>`,
so Search1API can tell sign-ups and usage that come from Magpie.
The browser must run on the same computer as Magpie. For a remote or container The browser must run on the same computer as Magpie. For a remote or container
installation, use an API key instead. The callback expires after five minutes. installation, use an API key instead. The callback expires after five minutes.
@@ -71,7 +78,7 @@ magpie plugin login search1api api
``` ```
Magpie prompts privately for the key and saves it in its credential store. Magpie prompts privately for the key and saves it in its credential store.
Get a key at [s1.dev](https://s1.dev/). Get a key at [s1.dev](https://s1.dev/?utm_source=magpie&utm_medium=readme).
For automated deployments, the plugin also accepts an `apiKey` plugin option For automated deployments, the plugin also accepts an `apiKey` plugin option
in Magpie's options editor, or `SEARCH1API_API_KEY` in the environment of the in Magpie's options editor, or `SEARCH1API_API_KEY` in the environment of the
@@ -122,8 +129,14 @@ your Magpie tools endpoint.
- `crawl`: retrieve readable page content. - `crawl`: retrieve readable page content.
- `sitemap`: discover site links. - `sitemap`: discover site links.
- `trending`: GitHub or Hacker News trends. - `trending`: GitHub or Hacker News trends.
- `send_feedback`: report a wrong or empty result, an unresolved error,
mismatched docs or a missing capability to the Search1API team, through
Search1API's `POST /feedback` API. It is free and needs a Search1API sign-in or API key. The report (message,
intent, category, request id and model) goes only to Search1API, which stores
it in its feedback inbox on [Agentback](https://agentback.app), a
third-party host, linked to your Search1API account.
Tool parameters follow the existing OpenCode integration. Search and news Search tool parameters follow the existing OpenCode integration. Search and news
preserve optional `published_date` and per-result `metadata`; Ask preserves preserve optional `published_date` and per-result `metadata`; Ask preserves
`intent`, `source`, `relevance`, and `errors`. Attribute Grokipedia results as `intent`, `source`, `relevance`, and `errors`. Attribute Grokipedia results as
“Powered by xAI”. Results are returned as JSON text. “Powered by xAI”. Results are returned as JSON text.
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@magpie-community/tools-search1api", "name": "@magpie-community/tools-search1api",
"version": "0.1.0", "version": "0.1.1",
"description": "Search1API web search, news, agentic search, pages, sitemaps and trends for Magpie, with OAuth or API key sign-in", "description": "Search1API web search, news, agentic search, pages, sitemaps and trends for Magpie, with OAuth or API key sign-in",
"type": "module", "type": "module",
"main": "./index.mjs", "main": "./index.mjs",
+22
View File
@@ -0,0 +1,22 @@
export const CATEGORIES = ["bug", "feature_request", "docs", "other"];
export const DESCRIPTION =
"Report a problem with Search1API: a wrong, empty or incomplete result, an " +
"error you could not resolve, documentation that did not match behavior, or " +
"a capability you needed but Search1API lacks. The report (message, intent, " +
"category, request_id and model) is sent to Search1API's feedback API, which " +
"stores it in Search1API's feedback inbox on agentback.app, linked to the " +
"signed-in Search1API account. Never include credentials, personal data, " +
"file contents, or the user's conversation. Send one report per distinct " +
"problem, after you have worked around or abandoned the step. Do not report " +
"normal successful results. Reporting is free, optional and must not block " +
"the user's task.";
// Search1API's POST /feedback body; the API attaches the caller's account.
export function feedbackBody(args: Record<string, unknown>) {
const { model, ...report } = args;
return {
...report,
agent: { name: "Magpie", ...(model === undefined ? {} : { model }) },
};
}
+46 -14
View File
@@ -1,4 +1,6 @@
import { join } from "node:path";
import { Credentials } from "./auth.ts"; import { Credentials } from "./auth.ts";
import { CATEGORIES, DESCRIPTION, feedbackBody } from "./feedback.ts";
import { startOAuth } from "./oauth.ts"; import { startOAuth } from "./oauth.ts";
import { AuthenticationError, request } from "./request.ts"; import { AuthenticationError, request } from "./request.ts";
import { filters, maxResults, query, searchBody, validate, type ArgumentsSchema, type Schema } from "./tools.ts"; import { filters, maxResults, query, searchBody, validate, type ArgumentsSchema, type Schema } from "./tools.ts";
@@ -10,6 +12,19 @@ export const Search1APIPlugin = async (input: PluginInput, options: Options = {}
const baseUrl = serviceURL(options.baseUrl ?? API_BASE).href.replace(/\/$/, ""); const baseUrl = serviceURL(options.baseUrl ?? API_BASE).href.replace(/\/$/, "");
const credentials = new Credentials(input, options); const credentials = new Credentials(input, options);
async function send(name: string, payload: Record<string, unknown>, signal: AbortSignal) {
let auth = await credentials.token(signal);
signal.throwIfAborted();
try {
return await request(baseUrl, name, auth.token, payload, signal);
} catch (error) {
if (!(error instanceof AuthenticationError) || !auth.oauth) throw error;
const renewed = await credentials.renew(auth.oauth, signal);
auth = { token: renewed.access, oauth: renewed };
return await request(baseUrl, name, auth.token, payload, signal);
}
}
function tool( function tool(
name: string, name: string,
description: string, description: string,
@@ -22,24 +37,25 @@ export const Search1APIPlugin = async (input: PluginInput, options: Options = {}
description, description,
args, args,
async execute(value: unknown, ctx: { abort: AbortSignal }) { async execute(value: unknown, ctx: { abort: AbortSignal }) {
const payload = body(validate(args, value)); const result = await send(name, body(validate(args, value)), ctx.abort);
const signal = ctx.abort;
let auth = await credentials.token(signal);
signal.throwIfAborted();
let result: unknown;
try {
result = await request(baseUrl, name, auth.token, payload, signal);
} catch (error) {
if (!(error instanceof AuthenticationError) || !auth.oauth) throw error;
const renewed = await credentials.renew(auth.oauth, signal);
auth = { token: renewed.access, oauth: renewed };
result = await request(baseUrl, name, auth.token, payload, signal);
}
return JSON.stringify(result, null, 2); return JSON.stringify(result, null, 2);
}, },
}; };
} }
const feedbackArgs: ArgumentsSchema = {
type: "object",
properties: {
message: { type: "string", minLength: 1, maxLength: 4000, description: "What went wrong or what was missing, in plain language." },
intent: { type: "string", maxLength: 2000, description: "The Search1API call you were making and what you expected from it. Not the user's request or conversation." },
category: { type: "string", enum: CATEGORIES },
request_id: { type: "string", maxLength: 256, description: "Request id of the call that had the problem, if known." },
model: { type: "string", maxLength: 128, description: "Your model name, if you know it." },
},
required: ["message"],
additionalProperties: false,
};
return { return {
config: async (config: { provider?: Record<string, unknown> }) => { config: async (config: { provider?: Record<string, unknown> }) => {
config.provider ??= {}; config.provider ??= {};
@@ -50,7 +66,7 @@ export const Search1APIPlugin = async (input: PluginInput, options: Options = {}
provider: PROVIDER, provider: PROVIDER,
single: true, single: true,
methods: [ methods: [
{ type: "oauth" as const, label: "Sign in to Search1API", authorize: () => startOAuth(baseUrl) }, { type: "oauth" as const, label: "Sign in to Search1API", authorize: () => startOAuth(baseUrl, undefined, join(input.directory, "search1api-oauth-client.json")) },
{ type: "api" as const, label: "Search1API API key" }, { type: "api" as const, label: "Search1API API key" },
], ],
refreshLead: 60_000, refreshLead: 60_000,
@@ -77,6 +93,22 @@ export const Search1APIPlugin = async (input: PluginInput, options: Options = {}
trending: tool("trending", "Find trending repositories on GitHub or stories on Hacker News.", trending: tool("trending", "Find trending repositories on GitHub or stories on Hacker News.",
{ service: { type: "string", enum: ["github", "hackernews"] }, maxResults }, { service: { type: "string", enum: ["github", "hackernews"] }, maxResults },
["service"], ({ service, maxResults }) => ({ search_service: service, max_results: maxResults ?? 10 })), ["service"], ({ service, maxResults }) => ({ search_service: service, max_results: maxResults ?? 10 })),
send_feedback: {
description: DESCRIPTION,
args: feedbackArgs,
async execute(value: unknown, ctx: { abort: AbortSignal }) {
const payload = feedbackBody(validate(feedbackArgs, value));
// A report that cannot be sent must not fail the agent's task.
try {
const receipt = await send("feedback", payload, ctx.abort) as { id?: unknown };
return `Feedback recorded (${typeof receipt?.id === "string" ? receipt.id : "ok"}). Thank you.`;
} catch (error) {
ctx.abort.throwIfAborted();
const reason = error instanceof Error ? error.message : "Search1API feedback failed.";
return `Feedback was not recorded: ${reason} Continue the task.`;
}
},
},
}, },
}; };
}; };
+110 -36
View File
@@ -1,11 +1,16 @@
import { createHash, randomBytes } from "node:crypto"; import { createHash, randomBytes } from "node:crypto";
import { createServer } from "node:http"; import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net"; import type { AddressInfo } from "node:net";
import { dirname } from "node:path";
import { serviceURL, type StoredOAuth } from "./types.ts"; import { serviceURL, type StoredOAuth } from "./types.ts";
const SCOPES = "openid profile email offline_access"; const SCOPES = "openid profile email offline_access";
const NETWORK_TIMEOUT = 15_000; const NETWORK_TIMEOUT = 15_000;
const LOGIN_TIMEOUT = 5 * 60_000; const LOGIN_TIMEOUT = 5 * 60_000;
// Lets Search1API attribute sign-ups to Magpie; authorization ignores it.
const SOURCE = "magpie";
const CALLBACK = /^http:\/\/127\.0\.0\.1:(\d{1,5})\/callback$/;
interface Metadata { interface Metadata {
issuer: string; issuer: string;
@@ -128,8 +133,51 @@ export async function refreshToken(
); );
} }
export async function startOAuth(baseUrl: string, timeoutMs = LOGIN_TIMEOUT) { interface SavedClient {
issuer: string;
clientId: string;
redirectUri: string;
}
// The registered public client and its loopback callback are reused, so each
// sign-in does not register another OAuth application at Search1API.
async function savedClient(
file: string | undefined,
issuer: string,
): Promise<SavedClient | undefined> {
if (!file) return undefined;
try {
const value = JSON.parse(await readFile(file, "utf8")) as SavedClient;
if (
value?.issuer === issuer &&
typeof value.clientId === "string" &&
value.clientId &&
typeof value.redirectUri === "string" &&
CALLBACK.test(value.redirectUri)
)
return value;
} catch {}
return undefined;
}
function listen(server: Server, port: number) {
return new Promise<void>((resolve, reject) => {
const failed = (error: Error) => reject(error);
server.once("error", failed);
server.listen(port, "127.0.0.1", () => {
server.off("error", failed);
resolve();
});
});
}
export async function startOAuth(
baseUrl: string,
timeoutMs = LOGIN_TIMEOUT,
clientFile?: string,
) {
const metadata = await discover(baseUrl); const metadata = await discover(baseUrl);
let saved = await savedClient(clientFile, metadata.issuer);
const state = randomBytes(32).toString("base64url"); const state = randomBytes(32).toString("base64url");
const verifier = randomBytes(48).toString("base64url"); const verifier = randomBytes(48).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url"); const challenge = createHash("sha256").update(verifier).digest("base64url");
@@ -184,10 +232,14 @@ export async function startOAuth(baseUrl: string, timeoutMs = LOGIN_TIMEOUT) {
: "Authorization received. Return to Magpie to finish signing in.", : "Authorization received. Return to Magpie to finish signing in.",
); );
}); });
await new Promise<void>((resolve, reject) => { try {
server.once("error", reject); await listen(server, saved ? Number(CALLBACK.exec(saved.redirectUri)![1]) : 0);
server.listen(0, "127.0.0.1", resolve); } catch (error) {
}); // Its port is taken: sign in through a new client instead.
if (!saved) throw error;
saved = undefined;
await listen(server, 0);
}
server.unref(); server.unref();
const close = () => { const close = () => {
server.close(); server.close();
@@ -200,41 +252,64 @@ export async function startOAuth(baseUrl: string, timeoutMs = LOGIN_TIMEOUT) {
timer.unref(); timer.unref();
try { try {
const redirect = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`; const redirect = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`;
const registration = await json<{ let clientId = saved?.clientId;
client_id: string; if (!clientId) {
token_endpoint_auth_method?: string; const registration = await json<{
}>(metadata.registration_endpoint, { client_id: string;
method: "POST", token_endpoint_auth_method?: string;
headers: { "Content-Type": "application/json" }, }>(metadata.registration_endpoint, {
body: JSON.stringify({ method: "POST",
client_name: "Search1API for Magpie", headers: { "Content-Type": "application/json" },
application_type: "native", body: JSON.stringify({
redirect_uris: [redirect], client_name: "Search1API for Magpie",
token_endpoint_auth_method: "none", application_type: "native",
grant_types: ["authorization_code", "refresh_token"], redirect_uris: [redirect],
response_types: ["code"], token_endpoint_auth_method: "none",
scope: SCOPES, grant_types: ["authorization_code", "refresh_token"],
}), response_types: ["code"],
}); scope: SCOPES,
if ( }),
!registration.client_id || });
(registration.token_endpoint_auth_method && if (
registration.token_endpoint_auth_method !== "none") !registration.client_id ||
) { (registration.token_endpoint_auth_method &&
throw new Error("Search1API OAuth did not register a public client."); registration.token_endpoint_auth_method !== "none")
) {
throw new Error("Search1API OAuth did not register a public client.");
}
clientId = registration.client_id;
if (clientFile) {
const record: SavedClient = {
issuer: metadata.issuer,
clientId,
redirectUri: redirect,
};
// The client is public: losing this file costs one registration.
await mkdir(dirname(clientFile), { recursive: true })
.then(() =>
writeFile(clientFile, JSON.stringify(record), { mode: 0o600 }),
)
.catch(() => {});
}
} }
const url = new URL(metadata.authorization_endpoint); const url = new URL(metadata.authorization_endpoint);
for (const [key, value] of Object.entries({ for (const [key, value] of Object.entries({
response_type: "code", response_type: "code",
client_id: registration.client_id, client_id: clientId,
redirect_uri: redirect, redirect_uri: redirect,
scope: SCOPES, scope: SCOPES,
state, state,
code_challenge: challenge, code_challenge: challenge,
code_challenge_method: "S256", code_challenge_method: "S256",
utm_source: SOURCE,
})) }))
url.searchParams.set(key, value); url.searchParams.set(key, value);
let completed = false; let completed = false;
// A reused client the server no longer knows fails in the browser, so a
// sign-in that does not finish registers afresh next time.
const forget = async () => {
if (saved && clientFile) await unlink(clientFile).catch(() => {});
};
return { return {
url: url.href, url: url.href,
instructions: instructions:
@@ -249,8 +324,10 @@ export async function startOAuth(baseUrl: string, timeoutMs = LOGIN_TIMEOUT) {
completed = true; completed = true;
try { try {
const response = await result; const response = await result;
if (response.error) if (response.error) {
await forget();
return { type: "failed" as const, error: response.error }; return { type: "failed" as const, error: response.error };
}
const tokens = await json<Tokens>(metadata.token_endpoint, { const tokens = await json<Tokens>(metadata.token_endpoint, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" }, headers: { "Content-Type": "application/x-www-form-urlencoded" },
@@ -258,17 +335,14 @@ export async function startOAuth(baseUrl: string, timeoutMs = LOGIN_TIMEOUT) {
grant_type: "authorization_code", grant_type: "authorization_code",
code: response.code!, code: response.code!,
redirect_uri: redirect, redirect_uri: redirect,
client_id: registration.client_id, client_id: clientId,
code_verifier: verifier, code_verifier: verifier,
}), }),
}); });
const { type: _, ...auth } = credential( const { type: _, ...auth } = credential(tokens, clientId, metadata);
tokens,
registration.client_id,
metadata,
);
return { type: "success" as const, ...auth }; return { type: "success" as const, ...auth };
} catch (error) { } catch (error) {
await forget();
return { return {
type: "failed" as const, type: "failed" as const,
error: error:
+3 -2
View File
@@ -1,8 +1,8 @@
import { serviceURL } from "./types.ts"; import { serviceURL, USER_AGENT } from "./types.ts";
export class AuthenticationError extends Error {} export class AuthenticationError extends Error {}
// Only the six reviewed endpoints are exposed. Match the original client's // Only the reviewed endpoints (six tools and feedback) are exposed. Match the original client's
// request bodies and deadlines without adding runtime npm dependencies. // request bodies and deadlines without adding runtime npm dependencies.
export async function request( export async function request(
baseUrl: string, baseUrl: string,
@@ -19,6 +19,7 @@ export async function request(
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
"User-Agent": USER_AGENT,
}, },
body: JSON.stringify(body), body: JSON.stringify(body),
signal: AbortSignal.any([ signal: AbortSignal.any([
+2
View File
@@ -1,5 +1,7 @@
export const PROVIDER = "search1api"; export const PROVIDER = "search1api";
export const API_BASE = "https://api.search1api.com"; export const API_BASE = "https://api.search1api.com";
// Identifies Magpie traffic to Search1API; keep in step with package.json.
export const USER_AGENT = "search1api-magpie/0.1.1";
export interface StoredOAuth { export interface StoredOAuth {
type: "oauth"; type: "oauth";
@@ -0,0 +1,78 @@
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { Search1APIPlugin } from "../index.mjs";
import { context } from "./helpers.mjs";
const baseUrl = "https://search1api.invalid";
const json = (value, status = 200) => new Response(JSON.stringify(value), { status });
// Every fetch is replaced: reports may only go to the Search1API API.
async function stub(t, handler) {
const directory = await mkdtemp(join(tmpdir(), "search1api-feedback-test-"));
const originalFetch = globalThis.fetch;
const originalKey = process.env.SEARCH1API_API_KEY;
delete process.env.SEARCH1API_API_KEY;
const calls = [];
globalThis.fetch = async (url, init) => {
const call = { url: new URL(String(url)), ...init };
calls.push(call);
assert.equal(call.url.origin, baseUrl);
return handler(call);
};
t.after(async () => {
globalThis.fetch = originalFetch;
if (originalKey === undefined) delete process.env.SEARCH1API_API_KEY;
else process.env.SEARCH1API_API_KEY = originalKey;
await rm(directory, { recursive: true, force: true });
});
const input = { directory, client: { auth: { set: async () => {} } } };
return { calls, input };
}
const report = { message: "Empty results for a known page", intent: "search for the docs page, expected it first", category: "bug", model: "fixture-model" };
test("feedback goes to Search1API's feedback API with the caller's credential", async (t) => {
const f = await stub(t, () => json({ id: "fb_fixture", status: "new" }, 201));
const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
// The agent decides what to send from the description alone.
assert.match(plugin.tool.send_feedback.description, /agentback\.app/);
assert.match(plugin.tool.send_feedback.description, /linked to the signed-in Search1API account/);
assert.doesNotMatch(plugin.tool.send_feedback.args.properties.intent.description, /trying to accomplish/);
const text = await plugin.tool.send_feedback.execute(report, context());
assert.equal(text, "Feedback recorded (fb_fixture). Thank you.");
assert.equal(f.calls.length, 1);
assert.equal(f.calls[0].url.pathname, "/feedback");
assert.equal(f.calls[0].method, "POST");
assert.equal(new Headers(f.calls[0].headers).get("authorization"), "Bearer fixture-key");
assert.deepEqual(JSON.parse(f.calls[0].body), {
message: report.message,
intent: report.intent,
category: "bug",
agent: { name: "Magpie", model: "fixture-model" },
});
});
test("a report that cannot be sent never fails the task", async (t) => {
let status = 503;
const f = await stub(t, () => json({ ok: false }, status));
const keyed = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
const message = { message: "Missing capability" };
assert.match(await keyed.tool.send_feedback.execute(message, context()), /not recorded: .*\(503\)/);
status = 429;
assert.match(await keyed.tool.send_feedback.execute(message, context()), /not recorded: .*\(429\)/);
globalThis.fetch = async () => { throw new TypeError("offline"); };
assert.match(await keyed.tool.send_feedback.execute(message, context()), /not recorded/);
const signedOut = await Search1APIPlugin(f.input, { baseUrl });
assert.match(await signedOut.tool.send_feedback.execute(message, context()), /not recorded: Sign in/);
});
test("invalid feedback is refused before any request", async (t) => {
const f = await stub(t, () => json({}));
const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
for (const args of [{}, { message: "" }, { message: "x", category: "praise" }, { message: "x", extra: 1 }])
await assert.rejects(plugin.tool.send_feedback.execute(args, context()));
assert.equal(f.calls.length, 0);
});
+8
View File
@@ -87,6 +87,14 @@ test("fetch stub: all six tools preserve wire bodies, defaults and complete JSON
assert.deepEqual(plugin.auth.methods.map((m) => m.type), ["oauth", "api"]); assert.deepEqual(plugin.auth.methods.map((m) => m.type), ["oauth", "api"]);
}); });
test("fetch stub: API requests identify the plugin version", async (t) => {
const f = await stub(t, () => json({ results: [] }));
const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
await plugin.tool.search.execute({ query: "fixture" }, context());
const { version } = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
assert.equal(new Headers(f.calls[0].headers).get("user-agent"), `search1api-magpie/${version}`);
});
test("fetch stub: invalid arguments are refused before any request", async (t) => { test("fetch stub: invalid arguments are refused before any request", async (t) => {
const f = await stub(t, () => { throw new Error("must not fetch"); }); const f = await stub(t, () => { throw new Error("must not fetch"); });
const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" }); const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
+58
View File
@@ -1,13 +1,24 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { access, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { join } from "node:path";
import test from "node:test"; import test from "node:test";
import { startOAuth } from "../src/oauth.ts"; import { startOAuth } from "../src/oauth.ts";
import { fixture } from "./helpers.mjs"; import { fixture } from "./helpers.mjs";
const registrations = (f) => f.calls.filter((call) => call.path === "/register").length;
async function signIn(login) {
await fetch(login.url);
return login.callback();
}
test("browser OAuth uses PKCE S256, public registration, state and issuer checks", async (t) => { test("browser OAuth uses PKCE S256, public registration, state and issuer checks", async (t) => {
const f = await fixture(t); const f = await fixture(t);
const login = await startOAuth(f.baseUrl, 1000); const login = await startOAuth(f.baseUrl, 1000);
const authURL = new URL(login.url); const authURL = new URL(login.url);
assert.equal(authURL.searchParams.get("code_challenge_method"), "S256"); assert.equal(authURL.searchParams.get("code_challenge_method"), "S256");
assert.equal(authURL.searchParams.get("utm_source"), "magpie");
const redirect = new URL(authURL.searchParams.get("redirect_uri")); const redirect = new URL(authURL.searchParams.get("redirect_uri"));
redirect.searchParams.set("state", "wrong"); redirect.searchParams.set("state", "wrong");
redirect.searchParams.set("code", "wrong"); redirect.searchParams.set("code", "wrong");
@@ -38,3 +49,50 @@ test("declined consent and abandoned sign-ins finish without leaking tokens or c
const redirect = new URL(abandoned.url).searchParams.get("redirect_uri"); const redirect = new URL(abandoned.url).searchParams.get("redirect_uri");
await assert.rejects(fetch(redirect)); await assert.rejects(fetch(redirect));
}); });
test("sign-ins reuse the registered client and its callback port", async (t) => {
const f = await fixture(t);
const file = join(f.directory, "search1api-oauth-client.json");
const first = await startOAuth(f.baseUrl, 1000, file);
assert.equal((await signIn(first)).type, "success");
const second = await startOAuth(f.baseUrl, 1000, file);
assert.equal(
new URL(second.url).searchParams.get("redirect_uri"),
new URL(first.url).searchParams.get("redirect_uri"),
);
const result = await signIn(second);
assert.equal(result.type, "success");
assert.equal(result.clientId, "test-public-client");
assert.equal(registrations(f), 1);
assert.equal(f.state.grants, 2);
});
test("a busy callback port or a saved client for another issuer registers anew", async (t) => {
const f = await fixture(t);
const file = join(f.directory, "search1api-oauth-client.json");
const first = await startOAuth(f.baseUrl, 1000, file);
await signIn(first);
const port = new URL(new URL(first.url).searchParams.get("redirect_uri")).port;
const blocker = createServer();
await new Promise((resolve) => blocker.listen(Number(port), "127.0.0.1", resolve));
t.after(() => blocker.close());
const busy = await startOAuth(f.baseUrl, 1000, file);
assert.notEqual(new URL(new URL(busy.url).searchParams.get("redirect_uri")).port, port);
assert.equal((await signIn(busy)).type, "success");
assert.equal(registrations(f), 2);
await writeFile(file, JSON.stringify({ issuer: "https://other.example", clientId: "x", redirectUri: "http://127.0.0.1:1/callback" }));
await signIn(await startOAuth(f.baseUrl, 1000, file));
assert.equal(registrations(f), 3);
});
test("a reused client that does not finish signing in is forgotten", async (t) => {
const f = await fixture(t);
const file = join(f.directory, "search1api-oauth-client.json");
await signIn(await startOAuth(f.baseUrl, 1000, file));
f.state.decline = true;
assert.equal((await signIn(await startOAuth(f.baseUrl, 1000, file))).type, "failed");
await assert.rejects(access(file));
f.state.decline = false;
assert.equal((await signIn(await startOAuth(f.baseUrl, 1000, file))).type, "success");
assert.equal(registrations(f), 2);
});
@@ -17,6 +17,7 @@ test("all six tools forward arguments to the API and preserve result metadata",
"crawl", "crawl",
"sitemap", "sitemap",
"trending", "trending",
"send_feedback",
]); ]);
const cases = [ const cases = [
[ [