iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / cloud-clients / src / post-subscriptions.tsmain at aacbc74

// post-subscriptions.ts — PUBLIC X POSTS FOR A MIND: a deployment asks the Cloud to watch an X
// account's own posts, with no link to that account. The Cloud holds one subscription at X per
// account, which belongs to its X app and goes to its bot's webhook, and keeps here which
// deployments asked for it (bot.ts). X's calls for it take the app's token, not the bot's.

/** One watched X account: the deployments that asked, and X's id of the subscription. A row
 *  whose last deployment let go, and whose delete X refused, is orphaned: the alarm deletes it
 *  again (bot.ts `#sweepPostSubscriptions`). */
export type PostSubscription = {
  userId: string;
  minds: string[];
  subscriptionId?: string;
  orphanedAt?: number;
};

const X_ID = /^[0-9]{1,19}$/;
export const POST_SUBSCRIPTION_PREFIX = "post-subscription:";

/** X's id, or nothing: a string of digits, as X writes every id. */
export const digits = (value: unknown) =>
  typeof value === "string" && X_ID.test(value) ? value : undefined;

/** A JSON object's own fields, or null for anything else: an array, a string, a number, null. */
export function objectOf(value: unknown): Record<string, unknown> | null {
  return typeof value === "object" && !!value && !Array.isArray(value)
    ? Object.fromEntries(Object.entries(value))
    : null;
}

/** The value at `path` in JSON from X, or nothing. X adds fields, so the others are not read. */
export function fieldAt(value: unknown, ...path: string[]): unknown {
  return path.reduce<unknown>((at, key) => objectOf(at)?.[key], value);
}

/** A JSON array, or none. */
export const listOf = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);

/** WHO MAY ASK, from `X_POST_SUBSCRIPTIONS` (worker.ts `Env`): how many X accounts are watched in
 *  all, and the deployments that may ask. Null turns the service off. */
export function postSubscriptionsConfig(
  value: string | undefined,
): { limit: number; minds: string[] } | null {
  let config: unknown;
  try {
    config = JSON.parse(value || "null");
  } catch {
    return null;
  }
  const limit = fieldAt(config, "limit");
  const listed = fieldAt(config, "minds");
  const minds = listOf(listed).filter((mind) => typeof mind === "string");
  if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 100)
    return null;
  if (!Array.isArray(listed) || minds.length !== listed.length) return null;
  return { limit, minds };
}

/** The X account a deployment's ask names: its body is exactly
 *  `{ eventType: "post.create", userId }`, or the ask names none. */
export function askedUserId(body: Record<string, unknown>): string | undefined {
  return Object.keys(body).sort().join(",") === "eventType,userId" &&
    body.eventType === "post.create"
    ? digits(body.userId)
    : undefined;
}

type PublicPost = {
  event_uuid: string;
  event_type: "post.create";
  filter: { user_id: string };
  payload: {
    id: string;
    author_id: string;
    text: string;
    created_at?: string;
    conversation_id?: string;
    in_reply_to_tweet_id?: string;
    referenced_tweets?: { type: string; id: string }[];
  };
};

/** WHAT CROSSES TO A DEPLOYMENT: a bounded copy of a post by the watched account, or null. The
 *  conversation, the post it answers and the posts it quotes or reposts go too, when X names them
 *  well: the mind must tell a post from a reply, a quote and a repost. */
export function publicPost(value: unknown): PublicPost | null {
  const userId = digits(fieldAt(value, "filter", "user_id"));
  const post = fieldAt(value, "payload");
  const id = digits(fieldAt(post, "id"));
  const uuid = fieldAt(value, "event_uuid");
  const text = fieldAt(post, "text");
  if (
    fieldAt(value, "event_type") !== "post.create" ||
    typeof uuid !== "string" ||
    !uuid ||
    uuid.length > 128 ||
    !userId ||
    !id ||
    fieldAt(post, "author_id") !== userId ||
    typeof text !== "string" ||
    text.length > 25000
  )
    return null;
  // an optional field X names badly is left out, never a reason to refuse the post
  const createdAt = fieldAt(post, "created_at");
  const referenced = listOf(fieldAt(post, "referenced_tweets"))
    .slice(0, 10)
    .flatMap((each) => {
      const type = fieldAt(each, "type");
      const tweet = digits(fieldAt(each, "id"));
      return typeof type === "string" && type && type.length <= 32 && tweet
        ? [{ type, id: tweet }]
        : [];
    });
  return {
    event_uuid: uuid,
    event_type: "post.create",
    filter: { user_id: userId },
    payload: {
      id,
      author_id: userId,
      text,
      ...(typeof createdAt === "string" && createdAt.length <= 64 && { created_at: createdAt }),
      conversation_id: digits(fieldAt(post, "conversation_id")),
      in_reply_to_tweet_id: digits(fieldAt(post, "in_reply_to_tweet_id")),
      ...(referenced.length > 0 && { referenced_tweets: referenced }),
    },
  };
}