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:
@@ -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 }) },
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { join } from "node:path";
|
||||
import { Credentials } from "./auth.ts";
|
||||
import { CATEGORIES, DESCRIPTION, feedbackBody } from "./feedback.ts";
|
||||
import { startOAuth } from "./oauth.ts";
|
||||
import { AuthenticationError, request } from "./request.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 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(
|
||||
name: string,
|
||||
description: string,
|
||||
@@ -22,24 +37,25 @@ export const Search1APIPlugin = async (input: PluginInput, options: Options = {}
|
||||
description,
|
||||
args,
|
||||
async execute(value: unknown, ctx: { abort: AbortSignal }) {
|
||||
const payload = body(validate(args, value));
|
||||
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);
|
||||
}
|
||||
const result = await send(name, body(validate(args, value)), ctx.abort);
|
||||
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 {
|
||||
config: async (config: { provider?: Record<string, unknown> }) => {
|
||||
config.provider ??= {};
|
||||
@@ -50,7 +66,7 @@ export const Search1APIPlugin = async (input: PluginInput, options: Options = {}
|
||||
provider: PROVIDER,
|
||||
single: true,
|
||||
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" },
|
||||
],
|
||||
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.",
|
||||
{ service: { type: "string", enum: ["github", "hackernews"] }, maxResults },
|
||||
["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.`;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
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 { dirname } from "node:path";
|
||||
import { serviceURL, type StoredOAuth } from "./types.ts";
|
||||
|
||||
const SCOPES = "openid profile email offline_access";
|
||||
const NETWORK_TIMEOUT = 15_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 {
|
||||
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);
|
||||
let saved = await savedClient(clientFile, metadata.issuer);
|
||||
const state = randomBytes(32).toString("base64url");
|
||||
const verifier = randomBytes(48).toString("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.",
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
try {
|
||||
await listen(server, saved ? Number(CALLBACK.exec(saved.redirectUri)![1]) : 0);
|
||||
} 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();
|
||||
const close = () => {
|
||||
server.close();
|
||||
@@ -200,41 +252,64 @@ export async function startOAuth(baseUrl: string, timeoutMs = LOGIN_TIMEOUT) {
|
||||
timer.unref();
|
||||
try {
|
||||
const redirect = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`;
|
||||
const registration = await json<{
|
||||
client_id: string;
|
||||
token_endpoint_auth_method?: string;
|
||||
}>(metadata.registration_endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
client_name: "Search1API for Magpie",
|
||||
application_type: "native",
|
||||
redirect_uris: [redirect],
|
||||
token_endpoint_auth_method: "none",
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
response_types: ["code"],
|
||||
scope: SCOPES,
|
||||
}),
|
||||
});
|
||||
if (
|
||||
!registration.client_id ||
|
||||
(registration.token_endpoint_auth_method &&
|
||||
registration.token_endpoint_auth_method !== "none")
|
||||
) {
|
||||
throw new Error("Search1API OAuth did not register a public client.");
|
||||
let clientId = saved?.clientId;
|
||||
if (!clientId) {
|
||||
const registration = await json<{
|
||||
client_id: string;
|
||||
token_endpoint_auth_method?: string;
|
||||
}>(metadata.registration_endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
client_name: "Search1API for Magpie",
|
||||
application_type: "native",
|
||||
redirect_uris: [redirect],
|
||||
token_endpoint_auth_method: "none",
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
response_types: ["code"],
|
||||
scope: SCOPES,
|
||||
}),
|
||||
});
|
||||
if (
|
||||
!registration.client_id ||
|
||||
(registration.token_endpoint_auth_method &&
|
||||
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);
|
||||
for (const [key, value] of Object.entries({
|
||||
response_type: "code",
|
||||
client_id: registration.client_id,
|
||||
client_id: clientId,
|
||||
redirect_uri: redirect,
|
||||
scope: SCOPES,
|
||||
state,
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: "S256",
|
||||
utm_source: SOURCE,
|
||||
}))
|
||||
url.searchParams.set(key, value);
|
||||
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 {
|
||||
url: url.href,
|
||||
instructions:
|
||||
@@ -249,8 +324,10 @@ export async function startOAuth(baseUrl: string, timeoutMs = LOGIN_TIMEOUT) {
|
||||
completed = true;
|
||||
try {
|
||||
const response = await result;
|
||||
if (response.error)
|
||||
if (response.error) {
|
||||
await forget();
|
||||
return { type: "failed" as const, error: response.error };
|
||||
}
|
||||
const tokens = await json<Tokens>(metadata.token_endpoint, {
|
||||
method: "POST",
|
||||
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",
|
||||
code: response.code!,
|
||||
redirect_uri: redirect,
|
||||
client_id: registration.client_id,
|
||||
client_id: clientId,
|
||||
code_verifier: verifier,
|
||||
}),
|
||||
});
|
||||
const { type: _, ...auth } = credential(
|
||||
tokens,
|
||||
registration.client_id,
|
||||
metadata,
|
||||
);
|
||||
const { type: _, ...auth } = credential(tokens, clientId, metadata);
|
||||
return { type: "success" as const, ...auth };
|
||||
} catch (error) {
|
||||
await forget();
|
||||
return {
|
||||
type: "failed" as const,
|
||||
error:
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { serviceURL } from "./types.ts";
|
||||
import { serviceURL, USER_AGENT } from "./types.ts";
|
||||
|
||||
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.
|
||||
export async function request(
|
||||
baseUrl: string,
|
||||
@@ -19,6 +19,7 @@ export async function request(
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
"User-Agent": USER_AGENT,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.any([
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
export const PROVIDER = "search1api";
|
||||
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 {
|
||||
type: "oauth";
|
||||
|
||||
Reference in New Issue
Block a user