openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
249 lines (248 loc) • 9.31 kB
JavaScript
import { a as asOptionalRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { v as resolveSecretInputString } from "../../types.secrets-BmNLLnHp.mjs";
import { n as createRuntimeConfigReader } from "../../runtime-snapshot-WbwbY5b7.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../runtime-config-snapshot-Dy0VFqWf.mjs";
import "../../secret-input-CpgOwFAi.mjs";
import { i as resolveXAccount, n as listXRuntimeAccountIds } from "../../accounts-Bg4ihS1J.mjs";
import { i as openXAllowlist } from "../../allowlist-Cvibwhmj.mjs";
import { a as XBudgetExceededError, l as fetchXService, t as getXApi } from "../../client-C7tbjMI4.mjs";
import { r as syncXGitHub, t as emptyXGitHubSnapshot } from "../../verified-github-Ct--PPa0.mjs";
//#region extensions/x/src/github.ts
var XGitHubError = class extends Error {
constructor(e) {
super(e);
this.name = "XGitHubError";
}
};
const PERMISSION_RANK = {
push: 1,
maintain: 2,
admin: 3
};
const LOGIN_PATTERN = /^[a-z\d][a-z\d_-]*$/i;
function xHandle(e) {
if (typeof e !== "string") return;
let t = e.trim();
if (/^https?:\/\//i.test(t)) try {
const e = new URL(t);
if (![
"x.com",
"twitter.com",
"www.x.com",
"www.twitter.com"
].includes(e.hostname) || e.username || e.password || e.port || e.search || e.hash) return;
t = e.pathname.replace(/^\//, "").replace(/\/$/, "");
} catch {
return;
}
t = t.replace(/^@/, "");
return /^[a-z\d_]{1,15}$/i.test(t) ? t.toLowerCase() : void 0;
}
function invalidResponse() {
throw new XGitHubError("GitHub returned an invalid response; the last verified set is unchanged.");
}
function retryDeadline(e) {
const t = Date.now();
const n = e.headers.get("retry-after");
const r = n === null ? NaN : Number(n);
const i = [n === null ? NaN : Number.isFinite(r) ? t + r * 1e3 : Date.parse(n), Number(e.headers.get("x-ratelimit-reset")) * 1e3].filter((e) => Number.isFinite(e) && e > t);
return i.length ? Math.max(...i) : void 0;
}
function createXGitHubReader(e) {
const t = /* @__PURE__ */ new Map();
let n = 0;
function rateLimited() {
throw new XGitHubError(`GitHub rate limit reached; retry after ${new Date(n).toISOString()}.`);
}
async function request(t, r, i, a) {
if (Date.now() < n) rateLimited();
if (!e.token.trim()) throw new XGitHubError("Configure verifiedFromGitHub.token with a GitHub credential that can list repository collaborators.");
const o = i ? AbortSignal.any([i, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4);
const s = {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${e.token}`,
"X-GitHub-Api-Version": "2022-11-28"
};
if (a?.etag) s["If-None-Match"] = a.etag;
const c = {
method: "GET",
headers: s,
signal: o,
redirect: "error"
};
let l;
try {
o.throwIfAborted();
l = await fetchXService("api.github.com", t, c);
} catch {
throw new XGitHubError("GitHub request failed or was cancelled; the last verified set is unchanged.");
}
const u = l.headers.get("x-ratelimit-remaining") === "0";
if (u) n = retryDeadline(l) ?? Date.now() + 6e4;
if (l.status === 304) {
await l.body?.cancel();
return a ?? invalidResponse();
}
let d;
try {
const { readResponseWithLimit: e } = await import("../../plugin-sdk/response-limit-runtime.js");
const t = await e(l, 2e6, {
signal: o,
timeoutMs: 3e4
});
d = JSON.parse(t.toString());
} catch {
if (l.ok) invalidResponse();
}
if (!l.ok) {
const e = asOptionalRecord(d)?.message;
if (l.status === 429 || l.status === 403 && (u || l.headers.has("retry-after") || typeof e === "string" && /secondary rate limit|abuse detection/i.test(e))) {
n = retryDeadline(l) ?? Date.now() + 6e4;
rateLimited();
}
if ([
401,
403,
404
].includes(l.status) && t.startsWith("/repos/")) throw new XGitHubError(`GitHub cannot list repository collaborators (HTTP ${l.status}); check the repository and verifiedFromGitHub.token access and permissions.`);
throw new XGitHubError(`GitHub request failed (HTTP ${l.status}); check verifiedFromGitHub.token and retry.`);
}
return {
etag: l.headers.get("etag") ?? void 0,
value: r(d)
};
}
return { async readCollaborators(e, n, r) {
const [i, a, o] = e.split("/");
if (!i || !LOGIN_PATTERN.test(i) || !a || !/^[a-z\d_.-]{1,100}$/i.test(a) || [".", ".."].includes(a) || o !== void 0) throw new XGitHubError("verifiedFromGitHub.repo must be owner/name.");
const s = /* @__PURE__ */ new Map();
for (let t = 1;; t++) {
const { value: i } = await request(`/repos/${e}/collaborators?affiliation=all&per_page=100&page=${t}`, (e) => {
if (!Array.isArray(e) || e.length > 100) invalidResponse();
return e.map((e) => {
const t = asOptionalRecord(e);
const n = asOptionalRecord(t?.permissions);
if (typeof t?.login !== "string" || !LOGIN_PATTERN.test(t.login) || typeof t.id !== "number" || !Number.isSafeInteger(t.id) || t.id <= 0 || !n || typeof n.push !== "boolean" || [n.maintain, n.admin].some((e) => e !== void 0 && typeof e !== "boolean")) invalidResponse();
const r = n.admin ? "admin" : n.maintain ? "maintain" : n.push ? "push" : void 0;
return {
githubLogin: t.login,
githubId: t.id,
permission: r
};
});
}, r);
for (const e of i) if (e.permission && PERMISSION_RANK[e.permission] >= PERMISSION_RANK[n]) s.set(e.githubLogin.toLowerCase(), {
githubLogin: e.githubLogin,
githubId: e.githubId,
permission: e.permission
});
if (i.length < 100) break;
}
for (const e of t.keys()) if (!s.has(e)) t.delete(e);
const c = [];
for (const [e, n] of s) {
const i = t.get(e);
const a = i?.githubId === n.githubId ? i : { githubId: n.githubId };
t.set(e, a);
a.profile = await request(`/users/${encodeURIComponent(e)}`, (t) => {
const r = asOptionalRecord(t);
if (typeof r?.login !== "string" || r.login.toLowerCase() !== e || r.id !== n.githubId || r.twitter_username !== null && r.twitter_username !== void 0 && typeof r.twitter_username !== "string") invalidResponse();
const i = xHandle(r.twitter_username);
return i ? [i] : [];
}, r, a.profile);
a.social = await request(`/users/${encodeURIComponent(e)}/social_accounts`, (e) => {
if (!Array.isArray(e)) invalidResponse();
return e.flatMap((e) => {
const t = asOptionalRecord(e);
if (!t || typeof t.provider !== "string" || typeof t.url !== "string") invalidResponse();
const n = t.provider.toLowerCase() === "twitter" || /^https?:\/\/(?:www\.)?(?:x|twitter)\.com\//i.test(t.url) ? xHandle(t.url) : void 0;
return n ? [n] : [];
});
}, r, a.social);
c.push({
githubLogin: n.githubLogin,
permission: n.permission,
xHandles: [.../* @__PURE__ */ new Set([...a.profile.value, ...a.social.value])]
});
}
return c;
} };
}
//#endregion
//#region extensions/x/src/verified-github-service.ts
function createXGitHubService(e) {
let t = [];
return {
id: "x-verified-github",
apiVersion: 2,
reload: { configPrefixes: ["channels.x"] },
start(n) {
const r = createRuntimeConfigReader(n.config);
const i = r();
const a = openXAllowlist(e.runtime);
t = listXRuntimeAccountIds(i);
for (const o of t) {
a.invalidate(o);
const t = resolveXAccount(i, o);
const s = t.config.verifiedFromGitHub;
if (!t.enabled || !t.configured || !s?.repo) continue;
const c = JSON.stringify(t.config);
const assertCurrent = () => {
n.scheduler.signal.throwIfAborted();
if (JSON.stringify(resolveXAccount(r(), o).config) !== c) throw new Error("X GitHub verification configuration changed");
};
let l;
let u = false;
n.scheduler.schedule({
id: o,
delayMs: 0,
everyMs: (s.refreshMinutes ?? 60) * 6e4,
run: async () => {
try {
assertCurrent();
const a = resolveSecretInputString({
value: s.token,
defaults: i.secrets?.defaults,
path: `channels.x.accounts.${o}.verifiedFromGitHub.token`,
mode: "strict"
}).value;
if (!a) throw new XGitHubError("Configure verifiedFromGitHub.token with a GitHub credential that can list repository collaborators.");
l ??= createXGitHubReader({ token: a });
await syncXGitHub({
runtime: e.runtime,
account: t,
github: l,
getApi: () => getXApi(o, r()),
signal: n.scheduler.signal,
assertCurrent
});
u = false;
} catch (e) {
if (n.scheduler.signal.aborted) return;
assertCurrent();
const r = e instanceof XGitHubError || e instanceof XBudgetExceededError ? e.message : "GitHub verification failed; check the configured credentials and Gateway logs. If X token refresh failed, reauthorize the X account. The last verified set is unchanged.";
if (!u) {
n.logger.warn(`X GitHub verification (${o}): ${r}`);
u = true;
}
const i = await a.readGitHub(o, s);
await a.replaceGitHub(o, {
...i ?? emptyXGitHubSnapshot(t),
stale: true,
message: r
}, assertCurrent);
}
}
});
}
},
stop() {
const n = openXAllowlist(e.runtime);
for (const e of t) n.invalidate(e);
t = [];
}
};
}
//#endregion
export { createXGitHubService };