@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
94 lines (92 loc) • 4.28 kB
JavaScript
import { version } from "./package.js";
import { assert, requireDefined } from "./assertions.js";
import { logger } from "./logger.js";
import { softrApiUrl } from "./softr-api.js";
import { getRequestHeader } from "@tanstack/react-start/server";
//#region src/fetch.ts
const CLIENT_IP_HEADER = "x-softr-client-ip";
const fetch = async (input, init) => {
const url = input instanceof Request ? input.url : String(input);
const platformBase = softrApiUrl("SOFTR_PLATFORM_API_URL");
if ([
platformBase,
softrApiUrl("SOFTR_DATASOURCE_API_URL"),
softrApiUrl("SOFTR_WORKFLOWS_API_URL")
].some((base) => url.startsWith(`${base}/`))) {
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
headers.set("user-agent", `softr-sdk/${version}`);
headers.delete(CLIENT_IP_HEADER);
const isPlatformCall = url.startsWith(`${platformBase}/`);
const isProduction = process.env.NODE_ENV === "production";
if (isPlatformCall && isProduction) try {
const clientIp = getRequestHeader("cf-connecting-ip");
if (clientIp) headers.set(CLIENT_IP_HEADER, clientIp);
} catch {}
init = {
...init,
headers
};
const signed = await sign(input, init);
if (signed) {
input = signed;
init = void 0;
}
}
if (process.env.NODE_ENV === "production") return globalThis.fetch(input, init);
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
const started = Date.now();
try {
const response = await globalThis.fetch(input, init);
if (!response.ok) logger.warn(`${method} ${response.status} ${url} ${Date.now() - started}ms`);
return response;
} catch (error) {
const label = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
logger.error(`${method} ERR ${url} ${label} in ${Date.now() - started}ms`);
throw error;
}
};
/**
* RFC 9421 signature over the request, with the key Studio handed the app at publish or session start. The SDK
* never derives, rotates or inspects the key: Softr derives it from a master key and the app's nonce, and the key
* id (`<environment>/<applicationId>/<master number>`) is copied into the signature as is so the verifier can
* derive the same key.
*
* The signature covers the method, authority, path, query and, when sent, the Authorization and client IP headers. The body is
* not covered: TLS protects it in transit, and signing is there to tell the app's own server from anyone holding a
* user token, which needs no body coverage. So nothing is buffered here and the body streams through as given.
*/
async function sign(input, init) {
const key = process.env.SOFTR_REQUEST_SIGNING_KEY;
const keyId = process.env.SOFTR_REQUEST_SIGNING_KEY_ID;
if (!key || !keyId) return void 0;
assert(/^[0-9a-f]{64}$/i.test(key), "SOFTR_REQUEST_SIGNING_KEY must be 64 hex characters");
assert(!/["\\]/.test(keyId), "SOFTR_REQUEST_SIGNING_KEY_ID must not contain quotes or backslashes");
const request = new Request(input, init);
const headers = new Headers(request.headers);
const { host, pathname, search } = new URL(request.url);
const derived = {
"@method": request.method,
"@authority": host,
"@path": pathname,
"@query": search || "?"
};
const fields = Object.keys(derived);
if (headers.has("authorization")) fields.push("authorization");
if (headers.has(CLIENT_IP_HEADER)) fields.push(CLIENT_IP_HEADER);
const created = Math.floor(Date.now() / 1e3);
const params = `(${fields.map((field) => `"${field}"`).join(" ")});created=${created};keyid="${keyId}";tag="softr-code-app"`;
const base = [...fields.map((field) => `"${field}": ${derived[field] ?? requireDefined(headers.get(field), field)}`), `"@signature-params": ${params}`].join("\n");
const hmacKey = await crypto.subtle.importKey("raw", Uint8Array.from(key.match(/../g) ?? [], (byte) => parseInt(byte, 16)), {
name: "HMAC",
hash: "SHA-256"
}, false, ["sign"]);
const signature = base64(await crypto.subtle.sign("HMAC", hmacKey, new TextEncoder().encode(base)));
headers.set("signature-input", `softr=${params}`);
headers.set("signature", `softr=:${signature}:`);
return new Request(request, { headers });
}
function base64(bytes) {
return btoa(String.fromCharCode(...new Uint8Array(bytes)));
}
//#endregion
export { fetch };