• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

cofacts / rumors-api / 45391274480

24 Nov 2026 12:12PM UTC coverage: 85.757% (+0.09%) from 85.663%
45391274480

push

github

web-flow
Merge pull request #423 from cofacts/claude/relaxed-albattani-6hjj7b

feat(adm): restore vandalized transcripts from version history

1100 of 1362 branches covered (80.76%)

Branch coverage included in aggregate %.

65 of 67 new or added lines in 2 files covered. (97.01%)

2067 of 2331 relevant lines covered (88.67%)

17.39 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.16
/src/scripts/restoreTranscript.ts
1
/**
2
 * Restore an article's transcript to one of its saved versions (`ydocs.versions`).
3
 *
4
 * Used when a transcript is vandalized (e.g. replaced by spam via the collaborative editor).
5
 * The restore is applied as a new Yjs change on top of the existing document, so the edit history
6
 * (including the vandalism) is kept and the history UI on rumors-site keeps working.
7
 *
8
 * Caveat: collab-server keeps a document in memory while anyone has its editor open, and it will
9
 * write its in-memory copy back over this restore. Run this when nobody is editing the transcript.
10
 *
11
 * Usage:
12
 *   # List versions of an article
13
 *   npx babel-node --extensions .ts,.js src/scripts/restoreTranscript.ts -a <articleId>
14
 *
15
 *   # Restore to the version created at the given time
16
 *   npx babel-node --extensions .ts,.js src/scripts/restoreTranscript.ts -a <articleId> -v <createdAt>
17
 */
18
import 'dotenv/config';
19
import yargs from 'yargs';
20
import * as Y from 'yjs';
21
import client from 'util/client';
22

23
type YdocVersion = { createdAt: string; snapshot: string };
24
type Contributor = { userId: string; appId: string; updatedAt: string };
25

26
/**
27
 * The "user" doing the restore. Recorded in the Yjs permanent user data in the same way as
28
 * AI_TRANSCRIBER_DESCRIPTION in CreateMediaArticle.
29
 */
30
export const TRANSCRIPT_RESTORER_DESCRIPTION = JSON.stringify({
1 ✔
31
  id: 'transcript-restore',
32
  appId: 'RUMORS_ADM',
33
  name: 'Transcript restore',
34
});
35

36
function decodeYdoc(base64: string) {
37
  const doc = new Y.Doc({ gc: false });
5 ✔
38
  Y.applyUpdate(doc, Buffer.from(base64, 'base64'));
5 ✔
39
  return doc;
5 ✔
40
}
41

42
function textContent(node: Y.XmlElement | Y.XmlText | Y.XmlHook): string {
43
  if (node instanceof Y.XmlText) {
52 ✔
44
    return node
26 ✔
45
      .toDelta()
46
      .map(({ insert }: { insert: unknown }) =>
47
        typeof insert === 'string' ? insert : ''
26 !
48
      )
49
      .join('');
50
  }
51
  if (node instanceof Y.XmlElement) {
26 !
52
    return node.toArray().map(textContent).join('');
26 ✔
53
  }
NEW
54
  return '';
×
55
}
56

57
/**
58
 * Same plain text format as collab-server's `docToPlainText`:
59
 * each top-level node's text content followed by a newline.
60
 */
61
export function ydocToPlainText(doc: Y.Doc) {
62
  return doc
11 ✔
63
    .getXmlFragment('prosemirror')
64
    .toArray()
65
    .map((node) => textContent(node) + '\n')
26 ✔
66
    .join('');
67
}
68

69
async function getYdoc(articleId: string) {
70
  const result = await client
7 ✔
71
    .get<{ ydoc?: string; versions?: YdocVersion[] }>({
72
      index: 'ydocs',
73
      id: articleId,
74
    })
75
    .catch((e) => {
76
      if (e?.meta?.statusCode === 404) return undefined;
1 !
NEW
77
      throw e;
×
78
    });
79

80
  if (!result?._source?.ydoc)
7 ✔
81
    throw new Error(`Article ${articleId} has no transcript ydoc`);
1 ✔
82

83
  return {
6 ✔
84
    ydoc: result._source.ydoc,
85
    versions: result._source.versions ?? [],
6 !
86
    // For optimistic concurrency control against collab-server's writes
87
    seqNo: result._seq_no,
88
    primaryTerm: result._primary_term,
89
  };
90
}
91

92
/**
93
 * List saved versions of the transcript of the given article.
94
 */
95
export async function listVersions(articleId: string) {
96
  const { ydoc, versions } = await getYdoc(articleId);
1 ✔
97
  const doc = decodeYdoc(ydoc);
1 ✔
98

99
  return versions.map(({ createdAt, snapshot }) => ({
2 ✔
100
    createdAt,
101
    text: ydocToPlainText(
102
      Y.createDocFromSnapshot(
103
        doc,
104
        Y.decodeSnapshot(Buffer.from(snapshot, 'base64'))
105
      )
106
    ),
107
  }));
108
}
109

110
/**
111
 * Restore the transcript of the article to the version created at `versionCreatedAt`.
112
 *
113
 * - Article text is set to the restored version.
114
 * - Contributors who did not edit before that version and last edited after it are removed from
115
 *   `articles.contributors`, since their edits are reverted.
116
 * - Fails without writing anything if collab-server stores the doc at the same time.
117
 * - A new version snapshot is pushed, so that collab-server's next contributor diff starts from
118
 *   the restored state.
119
 */
120
async function restoreTranscript({
121
  articleId,
122
  versionCreatedAt,
123
}: {
124
  articleId: string;
125
  versionCreatedAt: string;
126
}) {
127
  const { ydoc, versions, seqNo, primaryTerm } = await getYdoc(articleId);
6 ✔
128
  const targetVersion = versions.find(
5 ✔
129
    ({ createdAt }) => createdAt === versionCreatedAt
6 ✔
130
  );
131
  if (!targetVersion)
5 ✔
132
    throw new Error(
1 ✔
133
      `Article ${articleId} has no transcript version created at ${versionCreatedAt}`
134
    );
135

136
  // Read the article first, so that a missing article fails before anything is written
137
  const { _source: article } = await client.get<{
4 ✔
138
    contributors?: Contributor[];
139
  }>({ index: 'articles', id: articleId, _source_includes: ['contributors'] });
140

141
  const doc = decodeYdoc(ydoc);
4 ✔
142
  const targetSnapshot = Y.decodeSnapshot(
4 ✔
143
    Buffer.from(targetVersion.snapshot, 'base64')
144
  );
145
  const versionDoc = Y.createDocFromSnapshot(doc, targetSnapshot);
4 ✔
146
  if (!ydocToPlainText(versionDoc).trim())
4 ✔
147
    throw new Error(
1 ✔
148
      `Transcript version ${versionCreatedAt} of article ${articleId} is empty`
149
    );
150

151
  const pud = new Y.PermanentUserData(doc);
3 ✔
152

153
  // Users who had edited the doc by the target version, so their text is (partly) restored.
154
  const usersBeforeVersion = new Set<string>();
3 ✔
155
  for (const clientId of targetSnapshot.sv.keys()) {
3 ✔
156
    const user = pud.getUserByClientId(clientId);
6 ✔
157
    if (user) usersBeforeVersion.add(JSON.parse(user).id);
6 !
158
  }
159

160
  pud.setUserMapping(doc, doc.clientID, TRANSCRIPT_RESTORER_DESCRIPTION);
3 ✔
161

162
  const fragment = doc.getXmlFragment('prosemirror');
3 ✔
163
  const restoredNodes = versionDoc
3 ✔
164
    .getXmlFragment('prosemirror')
165
    .toArray()
166
    // ProseMirror documents contain only XmlElement & XmlText
167
    .filter(
168
      (node): node is Y.XmlElement | Y.XmlText => !(node instanceof Y.XmlHook)
9 ✔
169
    )
170
    .map((node) => node.clone());
9 ✔
171

172
  doc.transact(() => {
3 ✔
173
    fragment.delete(0, fragment.length);
3 ✔
174
    fragment.insert(0, restoredNodes);
3 ✔
175
  });
176

177
  // PermanentUserData records the deletions of a transaction in a setTimeout callback (yjs 13.6.x,
178
  // src/utils/PermanentUserData.js); wait for it so that the deleted spam is attributed to the
179
  // restorer. The test on deletion attribution catches it if a yjs upgrade changes this.
180
  await new Promise((resolve) => setTimeout(resolve, 0));
3 ✔
181

182
  const text = ydocToPlainText(doc);
3 ✔
183
  const now = new Date().toISOString();
3 ✔
184

185
  await client.update({
3 ✔
186
    index: 'ydocs',
187
    id: articleId,
188
    if_seq_no: seqNo,
189
    if_primary_term: primaryTerm,
190
    doc: {
191
      ydoc: Buffer.from(Y.encodeStateAsUpdate(doc)).toString('base64'),
192
      versions: [
193
        ...versions,
194
        {
195
          createdAt: now,
196
          snapshot: Buffer.from(Y.encodeSnapshot(Y.snapshot(doc))).toString(
197
            'base64'
198
          ),
199
        },
200
      ],
201
    },
202
    refresh: true,
203
  });
204

205
  const removedContributors = (article?.contributors ?? []).filter(
3 !
206
    // collab-server writes contributors' updatedAt before the version's createdAt on the same
207
    // disconnect, both with toISOString(), so string comparison works.
208
    ({ userId, updatedAt }) =>
209
      !usersBeforeVersion.has(userId) && updatedAt > versionCreatedAt
9 ✔
210
  );
211

212
  try {
3 ✔
213
    await client.update({
3 ✔
214
      index: 'articles',
215
      id: articleId,
216
      script: {
217
        // Remove only the contributor entries read above, so that entries collab-server writes
218
        // in the meantime are kept.
219
        source: `
220
          if (ctx._source.contributors != null) {
221
            ctx._source.contributors.removeIf(c ->
222
              params.removed.containsKey(c.userId) && params.removed[c.userId] == c.updatedAt
223
            );
224
          }
225
          ctx._source.text = params.text;
226
          ctx._source.updatedAt = params.now;
227
        `,
228
        lang: 'painless',
229
        params: {
230
          removed: Object.fromEntries(
231
            removedContributors.map(({ userId, updatedAt }) => [
3 ✔
232
              userId,
233
              updatedAt,
234
            ])
235
          ),
236
          text,
237
          now,
238
        },
239
      },
240
      retry_on_conflict: 3,
241
      refresh: true,
242
    });
243
  } catch (e) {
244
    throw new Error(
1 ✔
245
      `Transcript ydoc of article ${articleId} is restored, but updating the article failed. ` +
246
        `Re-running the restore is safe (it adds one more restore version): ${
247
          e instanceof Error ? e.message : e
1 !
248
        }`
249
    );
250
  }
251

252
  return {
2 ✔
253
    text,
254
    removedContributorIds: removedContributors.map(({ userId }) => userId),
2 ✔
255
  };
256
}
257

258
export default restoreTranscript;
259

260
/* istanbul ignore if */
261
if (require.main === module) {
1 ✔
262
  const argv = yargs
263
    .options({
264
      articleId: {
265
        alias: 'a',
266
        description: 'The article ID',
267
        type: 'string',
268
        demandOption: true,
269
      },
270
      versionCreatedAt: {
271
        alias: 'v',
272
        description:
273
          '`createdAt` of the version to restore to. Omit to list versions.',
274
        type: 'string',
275
      },
276
    })
277
    .help('help')
278
    .parseSync();
279

280
  (argv.versionCreatedAt
281
    ? restoreTranscript({
282
        articleId: argv.articleId,
283
        versionCreatedAt: argv.versionCreatedAt,
284
      })
285
    : listVersions(argv.articleId)
286
  )
287
    .then((result) => console.log(JSON.stringify(result, null, 2)))
288
    .catch((e) => {
289
      console.error(e);
290
      process.exit(1);
291
    });
292
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc