feat: reuse authentication for all HTTP integrations
This commit is contained in:
1 parent
879a4ae23c
commit
901fd3d940
36 files changed
+830
-295
No files matched your search
@@ -57,28 +57,10 @@ export const customWidgetHttpSourceSchema = z.strictObject({
|
||||
networkScope: z.enum(customJsxNetworkScopes),
|
||||
auth: authSchema.default("none"),
|
||||
});
|
||||
export const customWidgetIntegrationKinds = [
|
||||
"sonarr",
|
||||
"radarr",
|
||||
"lidarr",
|
||||
"readarr",
|
||||
"prowlarr",
|
||||
"overseerr",
|
||||
"jellyseerr",
|
||||
"seerr",
|
||||
"immich",
|
||||
"slskd",
|
||||
"homeAssistant",
|
||||
"coolify",
|
||||
"audiobookshelf",
|
||||
"speedtestTracker",
|
||||
"adGuardHome",
|
||||
"nextcloud",
|
||||
] as const;
|
||||
export const customWidgetIntegrationSourceSchema = z.strictObject({
|
||||
type: z.literal("integration"),
|
||||
name: z.string().trim().min(1).max(128).optional(),
|
||||
integrationKind: z.enum(customWidgetIntegrationKinds),
|
||||
integrationKind: customWidgetIdentifierSchema,
|
||||
integrationId: z.string().min(1).max(100).optional(),
|
||||
baseUrl: z.never().optional(),
|
||||
networkScope: z.never().optional(),
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "./request-types";
|
||||
import { assertCustomWidgetPathScope, resolveSameOriginTarget } from "./network-policy";
|
||||
|
||||
type HeaderSetter = Pick<Headers, "set">;
|
||||
|
||||
export const AUTH_HANDLERS: Record<
|
||||
@@ -43,3 +46,54 @@ export function applyAuth(
|
||||
handler(headers, url, secretMap.apiKey, headerName ?? undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export async function performAuthenticatedRequest(
|
||||
input: CustomWidgetHttpRequest,
|
||||
signal: AbortSignal,
|
||||
perform: (input: CustomWidgetHttpRequest, signal: AbortSignal) => Promise<CustomWidgetHttpResponse>,
|
||||
): Promise<CustomWidgetHttpResponse> {
|
||||
const target = resolveSameOriginTarget(input.baseUrl, input.targetUrl);
|
||||
if (input.pathPrefix !== undefined) assertCustomWidgetPathScope(target, input.pathPrefix);
|
||||
if (input.resolveConnectionAsync) {
|
||||
const connection = await withinDeadline(input.resolveConnectionAsync, signal);
|
||||
const base = new URL(connection.baseUrl);
|
||||
target.protocol = base.protocol;
|
||||
target.host = base.host;
|
||||
input = { ...input, ...connection, targetUrl: target };
|
||||
}
|
||||
let response = await perform(input, signal);
|
||||
if (!isExpired(input, response)) return response;
|
||||
response.ok = false;
|
||||
response.status = 401;
|
||||
response.statusText = "Integration session expired";
|
||||
if (!input.auth?.refreshAsync) return response;
|
||||
const auth = await withinDeadline(input.auth.refreshAsync, signal);
|
||||
// An action may have reached the service. Refresh for its next explicit invocation.
|
||||
if (input.kind === "action") return response;
|
||||
input = { ...input, auth };
|
||||
response = await perform(input, signal);
|
||||
if (isExpired(input, response)) {
|
||||
response.ok = false;
|
||||
response.status = 401;
|
||||
response.statusText = "Integration session expired";
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
function isExpired(input: CustomWidgetHttpRequest, response: CustomWidgetHttpResponse) {
|
||||
return input.auth && (response.status === 401 || input.auth.isExpired?.(response));
|
||||
}
|
||||
|
||||
async function withinDeadline<T>(callback: () => Promise<T>, signal: AbortSignal): Promise<T> {
|
||||
signal.throwIfAborted();
|
||||
let abort: (() => void) | undefined;
|
||||
const aborted = new Promise<never>((_resolve, reject) => {
|
||||
abort = () => reject(signal.reason);
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
});
|
||||
try {
|
||||
return await Promise.race([callback(), aborted]);
|
||||
} finally {
|
||||
if (abort) signal.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,6 @@ export {
|
||||
} from "./request-manifest";
|
||||
export type { CustomJsxRuntimeParams } from "./request-manifest";
|
||||
|
||||
export { redactResponseSecrets } from "./response-redaction";
|
||||
export { redactResponseSecrets } from "./response";
|
||||
|
||||
export { assertCustomWidgetPathScope } from "./network-policy";
|
||||
@@ -4,7 +4,7 @@ import { Headers, Response } from "undici";
|
||||
|
||||
import type { CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "./request-types";
|
||||
export type { CustomWidgetAuthConfig, CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "./request-types";
|
||||
import { applyAuth } from "./auth";
|
||||
import { applyAuth, performAuthenticatedRequest } from "./auth";
|
||||
import { CustomWidgetDomainError } from "./errors";
|
||||
import {
|
||||
assertSafeStaticHeaders,
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "./network-policy";
|
||||
import { closeDispatcher } from "./request-dispatcher-lifecycle";
|
||||
import { parseResponseBody } from "./response";
|
||||
import { redactResponseSecrets } from "./response-redaction";
|
||||
import { redactResponseSecrets } from "./response";
|
||||
|
||||
export {
|
||||
assertSafeStaticHeaders,
|
||||
@@ -52,7 +52,8 @@ async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWid
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), MAX_REQUEST_DURATION_MS);
|
||||
try {
|
||||
return await performRequestWithinDeadline(input, controller.signal);
|
||||
assertRequest(input);
|
||||
return await performAuthenticatedRequest(input, controller.signal, performRequestWithinDeadline);
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) {
|
||||
throw new CustomWidgetDomainError({
|
||||
@@ -84,9 +85,12 @@ async function performRequestWithinDeadline(
|
||||
const baseUrl = validateCustomWidgetUrl(input.baseUrl);
|
||||
let currentUrl = resolveSameOriginTarget(input.baseUrl, input.targetUrl);
|
||||
let currentMethod = input.method;
|
||||
let currentBody = input.body;
|
||||
let currentBody = input.auth?.transformBody ? input.auth.transformBody(input.body) : input.body;
|
||||
assertRequest({ ...input, body: currentBody });
|
||||
const maxRedirects = input.kind === "query" ? MAX_QUERY_REDIRECTS : 0;
|
||||
for (let redirects = 0; ; redirects += 1) {
|
||||
input.auth?.transformUrl?.(currentUrl);
|
||||
resolveSameOriginTarget(input.baseUrl, currentUrl);
|
||||
if (input.pathPrefix !== undefined) assertCustomWidgetPathScope(currentUrl, input.pathPrefix);
|
||||
const dispatcher = createPinnedAgent(
|
||||
await resolveAndValidateHost(currentUrl.hostname, input.networkScope, { signal: deadlineSignal }),
|
||||
@@ -114,15 +118,22 @@ async function performRequestWithinDeadline(
|
||||
statusText: STATUS_CODES[responseData.statusCode] ?? "",
|
||||
headers: normalizeResponseHeaders(responseData.headers),
|
||||
});
|
||||
result = {
|
||||
kind: "response",
|
||||
response: {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
data: redactResponseSecrets(await parseResponseBody(response), input.redactSecrets ?? []),
|
||||
},
|
||||
const parsed = {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
data: await parseResponseBody(response),
|
||||
};
|
||||
if (input.auth?.isExpired?.(parsed)) {
|
||||
parsed.ok = false;
|
||||
parsed.status = 401;
|
||||
parsed.statusText = "Integration session expired";
|
||||
}
|
||||
parsed.data = redactResponseSecrets(parsed.data, [
|
||||
...(input.redactSecrets ?? []),
|
||||
...(input.auth?.secrets ?? []),
|
||||
]);
|
||||
result = { kind: "response", response: parsed };
|
||||
} else {
|
||||
await responseData.body.dump();
|
||||
result = {
|
||||
@@ -227,6 +238,8 @@ function buildHeaders(input: CustomWidgetHttpRequest, url: URL, body: string | u
|
||||
if (input.auth) {
|
||||
if (input.auth.type === "apiKeyHeader") assertSafeStaticHeaders({ [input.auth.headerName ?? "X-API-Key"]: "" });
|
||||
applyAuth(headers, url, input.auth.type, input.auth.secrets, input.auth.headerName);
|
||||
for (const [name, value] of Object.entries(input.auth.headers ?? {})) headers.set(name, value);
|
||||
for (const [name, value] of Object.entries(input.auth.query ?? {})) url.searchParams.set(name, value);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
@@ -3,12 +3,22 @@ import type { ConnectionOptions } from "node:tls";
|
||||
import type { CustomJsxNetworkScope, CustomWidgetMethod } from "../core";
|
||||
|
||||
export interface CustomWidgetAuthConfig {
|
||||
baseUrl?: string;
|
||||
type: string;
|
||||
secrets: Array<{ kind: string; value: string }>;
|
||||
headerName?: string | null;
|
||||
headers?: Record<string, string>;
|
||||
query?: Record<string, string>;
|
||||
transformUrl?(url: URL): void;
|
||||
transformBody?(body: string | undefined): string;
|
||||
isExpired?(response: CustomWidgetHttpResponse): boolean;
|
||||
refreshAsync?(): Promise<CustomWidgetAuthConfig>;
|
||||
}
|
||||
|
||||
export interface CustomWidgetHttpRequest {
|
||||
resolveConnectionAsync?(): Promise<
|
||||
Pick<CustomWidgetHttpRequest, "baseUrl" | "auth" | "tls" | "pathPrefix" | "redactSecrets">
|
||||
>;
|
||||
tls?: Pick<ConnectionOptions, "ca" | "checkServerIdentity">;
|
||||
pathPrefix?: string;
|
||||
redactSecrets?: CustomWidgetAuthConfig["secrets"];
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
export function redactResponseSecrets(data: unknown, secrets: Array<{ kind: string; value: string }>): unknown {
|
||||
if (secrets.length === 0) return data;
|
||||
const values = secrets.map(({ value }) => value).filter(Boolean);
|
||||
const username = secrets.find(({ kind }) => kind === "username")?.value;
|
||||
const password = secrets.find(({ kind }) => kind === "password")?.value;
|
||||
if (username && password) values.push(`${username}:${password}`);
|
||||
const sensitive = [
|
||||
...new Set(
|
||||
values.flatMap((value) => [
|
||||
value,
|
||||
JSON.stringify(value).slice(1, -1),
|
||||
encodeURIComponent(value),
|
||||
Buffer.from(value).toString("base64"),
|
||||
]),
|
||||
),
|
||||
].toSorted((a, b) => b.length - a.length);
|
||||
const redact = (value: string) => {
|
||||
for (const secret of sensitive) value = value.replaceAll(secret, "[REDACTED]");
|
||||
return value;
|
||||
};
|
||||
const visit = (value: unknown): unknown => {
|
||||
if (typeof value === "string") return redact(value);
|
||||
if (
|
||||
(typeof value === "number" || typeof value === "boolean" || value === null) &&
|
||||
redact(String(value)) !== String(value)
|
||||
)
|
||||
return "[REDACTED]";
|
||||
if (Array.isArray(value)) return value.map(visit);
|
||||
if (value !== null && typeof value === "object") {
|
||||
return Object.fromEntries(Object.entries(value).map(([key, child]) => [redact(key), visit(child)]));
|
||||
}
|
||||
return value;
|
||||
};
|
||||
return visit(data);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import type { Response } from "undici";
|
||||
import { CustomWidgetDomainError } from "./errors";
|
||||
|
||||
@@ -63,3 +64,39 @@ export async function parseResponseBody(response: Response): Promise<unknown> {
|
||||
|
||||
const tooLarge = () =>
|
||||
new CustomWidgetDomainError({ code: "PAYLOAD_TOO_LARGE", message: "Response exceeds the 1 MiB limit" });
|
||||
|
||||
export function redactResponseSecrets(data: unknown, secrets: Array<{ kind: string; value: string }>): unknown {
|
||||
if (secrets.length === 0) return data;
|
||||
const values = secrets.map(({ value }) => value).filter(Boolean);
|
||||
const username = secrets.find(({ kind }) => kind === "username")?.value;
|
||||
const password = secrets.find(({ kind }) => kind === "password")?.value;
|
||||
if (username && password) values.push(`${username}:${password}`);
|
||||
const sensitive = [
|
||||
...new Set(
|
||||
values.flatMap((value) => [
|
||||
value,
|
||||
JSON.stringify(value).slice(1, -1),
|
||||
encodeURIComponent(value),
|
||||
Buffer.from(value).toString("base64"),
|
||||
]),
|
||||
),
|
||||
].toSorted((a, b) => b.length - a.length);
|
||||
const redact = (value: string) => {
|
||||
for (const secret of sensitive) value = value.replaceAll(secret, "[REDACTED]");
|
||||
return value;
|
||||
};
|
||||
const visit = (value: unknown): unknown => {
|
||||
if (typeof value === "string") return redact(value);
|
||||
if (
|
||||
(typeof value === "number" || typeof value === "boolean" || value === null) &&
|
||||
redact(String(value)) !== String(value)
|
||||
)
|
||||
return "[REDACTED]";
|
||||
if (Array.isArray(value)) return value.map(visit);
|
||||
if (value !== null && typeof value === "object") {
|
||||
return Object.fromEntries(Object.entries(value).map(([key, child]) => [redact(key), visit(child)]));
|
||||
}
|
||||
return value;
|
||||
};
|
||||
return visit(data);
|
||||
}
|
||||
Reference in new issue
Block a user