aboutsummaryrefslogtreecommitdiff
path: root/castle-search/src/x-search.ts
diff options
context:
space:
mode:
authorIgor Soarez <igor@soarez.org>2026-11-18 10:50:14 +0000
committerIgor Soarez <igor@soarez.org>2026-11-18 10:50:14 +0000
commit910ac7cd424f6401ea042a84603c42ba055994f8 (patch)
tree3ff40da7d14c644428c71cab1b005eca0b186d13 /castle-search/src/x-search.ts
parent39f887e07721c5b3ddd31657e5e8e25e4486d2e5 (diff)
castle-search: sign X back in when a search finds it signed out
Username, password, the authenticator code (TOTP) and, when X asks, the code it emails, read over IMAP. At most one try per 30 minutes, the password never sent twice, and any unknown step (a captcha) fails saying a person has to sign in. Details from the file CCS_X_LOGIN_FILE names.
Diffstat (limited to 'castle-search/src/x-search.ts')
-rw-r--r--castle-search/src/x-search.ts70
1 files changed, 63 insertions, 7 deletions
diff --git a/castle-search/src/x-search.ts b/castle-search/src/x-search.ts
index 38dc053..7c8badf 100644
--- a/castle-search/src/x-search.ts
+++ b/castle-search/src/x-search.ts
@@ -19,10 +19,29 @@
import { BrowserUnavailableError, NoResultsError } from "./errors.ts";
import { withPage } from "./search.ts";
import { XLimiter } from "./x-limits.ts";
+import { loadCredentials, X_LOGIN_TIMEOUT_MS, xLogin } from "./x-login.ts";
/** Shared by every X search in this process: see x-limits.ts. */
const limiter = new XLimiter();
+/**
+ * Signed out, a search signs the browser back in (x-login.ts) when
+ * CCS_X_LOGIN_FILE names the credentials, then searches again, once. At most
+ * one sign-in attempt per LOGIN_COOLDOWN_MS: a sign-in that keeps failing
+ * is what gets an account locked, so until the cooldown has passed every
+ * search fails with the reason the last attempt gave.
+ */
+export const LOGIN_COOLDOWN_MS = 30 * 60_000;
+let lastLogin: { at: number; error?: string } | undefined;
+
+class SignedOut extends Error {
+ readonly at: string;
+ constructor(at: string) {
+ super(`signed out at ${at}`);
+ this.at = at;
+ }
+}
+
export type XSort = "latest" | "top";
export type XPost = {
@@ -160,6 +179,17 @@ export const xSearch = (request: XSearchRequest, outer: AbortSignal): Promise<XS
limiter.run(outer, () => searchNow(request, outer));
const searchNow = async (request: XSearchRequest, outer: AbortSignal): Promise<XSearchOutcome> => {
+ try {
+ return await attempt(request, outer);
+ } catch (e) {
+ if (!(e instanceof SignedOut)) throw e;
+ // The sign-in has its own deadline, and the search after it a fresh one.
+ await signIn(e.at, outer);
+ return await attempt(request, outer);
+ }
+};
+
+const attempt = async (request: XSearchRequest, outer: AbortSignal): Promise<XSearchOutcome> => {
const sort: XSort = request.sort ?? "latest";
const searchUrl = buildXSearchUrl(request.query, sort);
const signal = AbortSignal.any([outer, AbortSignal.timeout(X_SEARCH_TIMEOUT_MS)]);
@@ -178,6 +208,37 @@ const searchNow = async (request: XSearchRequest, outer: AbortSignal): Promise<X
}
};
+const signedOutError = (at: string, why: string): BrowserUnavailableError =>
+ new BrowserUnavailableError(
+ `X search needs a signed-in X session in castle Chrome, and it is signed out (X sent it to ${at}). ` +
+ `${why} Tell the user: someone has to sign in to X in that browser again.`,
+ );
+
+/** Signs the browser in, within its own deadline, or throws saying why not. */
+const signIn = async (at: string, outer: AbortSignal): Promise<void> => {
+ const creds = loadCredentials(process.env["CCS_X_LOGIN_FILE"]);
+ if (!creds) throw signedOutError(at, "No sign-in details are configured (CCS_X_LOGIN_FILE).");
+ if (lastLogin && Date.now() - lastLogin.at < LOGIN_COOLDOWN_MS) {
+ const next = new Date(lastLogin.at + LOGIN_COOLDOWN_MS).toISOString().slice(11, 16);
+ throw signedOutError(
+ at,
+ `Signing in again was tried at ${new Date(lastLogin.at).toISOString().slice(11, 16)} UTC` +
+ (lastLogin.error ? ` and failed: ${lastLogin.error}` : ", yet it is signed out again.") +
+ ` The next try is after ${next} UTC.`,
+ );
+ }
+ lastLogin = { at: Date.now() };
+ const signal = AbortSignal.any([outer, AbortSignal.timeout(X_LOGIN_TIMEOUT_MS)]);
+ try {
+ await withPage(signal, (page) => xLogin(page, creds, signal, (line) => console.log(line)));
+ } catch (e) {
+ const why = signal.aborted && !outer.aborted ? `it took over ${X_LOGIN_TIMEOUT_MS / 1000} s` : (e as Error).message;
+ lastLogin.error = why;
+ console.log(`x-login failed: ${why}`);
+ throw signedOutError(at, `Signing in again failed: ${why}`);
+ }
+};
+
const run = (
request: XSearchRequest,
sort: XSort,
@@ -185,7 +246,7 @@ const run = (
signal: AbortSignal,
saw: (state: string) => void,
): Promise<XSearchOutcome> =>
- withPage(signal, async (page, endpoint) => {
+ withPage(signal, async (page) => {
await page.navigate(searchUrl, signal);
// X renders after the load event: poll until posts, an empty or error
@@ -198,12 +259,7 @@ const run = (
await sleep(POLL_MS, signal);
}
- if (probe.state === "signed-out") {
- throw new BrowserUnavailableError(
- `X search needs a signed-in X session in the browser (${endpoint}), and it is signed out ` +
- `(X sent it to ${probe.url}). Tell the user: someone has to sign in to X in that browser again.`,
- );
- }
+ if (probe.state === "signed-out") throw new SignedOut(probe.url);
if (probe.state === "error") {
throw new BrowserUnavailableError(
`X answered with an error page instead of results (${probe.url}): "${probe.note}". This is ` +