@atproto/ozone 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/api/inbox/appealActionedSubject.d.ts +4 -0
  3. package/dist/api/inbox/appealActionedSubject.d.ts.map +1 -0
  4. package/dist/api/inbox/appealActionedSubject.js +60 -0
  5. package/dist/api/inbox/appealActionedSubject.js.map +1 -0
  6. package/dist/api/index.d.ts.map +1 -1
  7. package/dist/api/index.js +2 -0
  8. package/dist/api/index.js.map +1 -1
  9. package/dist/api/label/subscribeLabels.d.ts.map +1 -1
  10. package/dist/api/label/subscribeLabels.js +4 -2
  11. package/dist/api/label/subscribeLabels.js.map +1 -1
  12. package/dist/api/queue/createQueue.d.ts.map +1 -1
  13. package/dist/api/queue/createQueue.js +22 -17
  14. package/dist/api/queue/createQueue.js.map +1 -1
  15. package/dist/api/queue/updateQueue.d.ts.map +1 -1
  16. package/dist/api/queue/updateQueue.js +33 -18
  17. package/dist/api/queue/updateQueue.js.map +1 -1
  18. package/dist/assignment/index.d.ts +1 -0
  19. package/dist/assignment/index.d.ts.map +1 -1
  20. package/dist/assignment/index.js +5 -0
  21. package/dist/assignment/index.js.map +1 -1
  22. package/dist/config/config.d.ts +11 -0
  23. package/dist/config/config.d.ts.map +1 -1
  24. package/dist/config/config.js +4 -0
  25. package/dist/config/config.js.map +1 -1
  26. package/dist/config/env.d.ts +1 -0
  27. package/dist/config/env.d.ts.map +1 -1
  28. package/dist/config/env.js +1 -0
  29. package/dist/config/env.js.map +1 -1
  30. package/dist/context.d.ts +2 -0
  31. package/dist/context.d.ts.map +1 -1
  32. package/dist/context.js +1 -1
  33. package/dist/context.js.map +1 -1
  34. package/dist/daemon/stats-computer.d.ts +2 -8
  35. package/dist/daemon/stats-computer.d.ts.map +1 -1
  36. package/dist/daemon/stats-computer.js +21 -9
  37. package/dist/daemon/stats-computer.js.map +1 -1
  38. package/dist/db/migrations/20260219T164523000Z-create-report-table.js +2 -2
  39. package/dist/db/migrations/20260219T164523000Z-create-report-table.js.map +1 -1
  40. package/dist/db/migrations/20260810T000000000Z-add-report-stats-components.d.ts +4 -0
  41. package/dist/db/migrations/20260810T000000000Z-add-report-stats-components.d.ts.map +1 -0
  42. package/dist/db/migrations/20260810T000000000Z-add-report-stats-components.js +31 -0
  43. package/dist/db/migrations/20260810T000000000Z-add-report-stats-components.js.map +1 -0
  44. package/dist/db/migrations/20260922T153505234Z-add-report-closed-at-index.d.ts +4 -0
  45. package/dist/db/migrations/20260922T153505234Z-add-report-closed-at-index.d.ts.map +1 -0
  46. package/dist/db/migrations/20260922T153505234Z-add-report-closed-at-index.js +14 -0
  47. package/dist/db/migrations/20260922T153505234Z-add-report-closed-at-index.js.map +1 -0
  48. package/dist/db/migrations/20260928T000000000Z-inbox-appeal.d.ts +4 -0
  49. package/dist/db/migrations/20260928T000000000Z-inbox-appeal.d.ts.map +1 -0
  50. package/dist/db/migrations/20260928T000000000Z-inbox-appeal.js +25 -0
  51. package/dist/db/migrations/20260928T000000000Z-inbox-appeal.js.map +1 -0
  52. package/dist/db/migrations/index.d.ts +3 -0
  53. package/dist/db/migrations/index.d.ts.map +1 -1
  54. package/dist/db/migrations/index.js +3 -0
  55. package/dist/db/migrations/index.js.map +1 -1
  56. package/dist/db/schema/report.js.map +1 -1
  57. package/dist/db/schema/report_queue.d.ts +1 -0
  58. package/dist/db/schema/report_queue.d.ts.map +1 -1
  59. package/dist/db/schema/report_queue.js.map +1 -1
  60. package/dist/db/schema/report_stat.d.ts +11 -1
  61. package/dist/db/schema/report_stat.d.ts.map +1 -1
  62. package/dist/db/schema/report_stat.js.map +1 -1
  63. package/dist/inbox/appeal.d.ts +187 -0
  64. package/dist/inbox/appeal.d.ts.map +1 -0
  65. package/dist/inbox/appeal.js +340 -0
  66. package/dist/inbox/appeal.js.map +1 -0
  67. package/dist/inbox/views.d.ts +92 -0
  68. package/dist/inbox/views.d.ts.map +1 -0
  69. package/dist/inbox/views.js +313 -0
  70. package/dist/inbox/views.js.map +1 -0
  71. package/dist/index.d.ts +1 -0
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +1 -0
  74. package/dist/index.js.map +1 -1
  75. package/dist/lexicons/app/bsky/authFullApp.defs.d.ts.map +1 -1
  76. package/dist/lexicons/app/bsky/authFullApp.defs.js +10 -0
  77. package/dist/lexicons/app/bsky/authFullApp.defs.js.map +1 -1
  78. package/dist/lexicons/app/bsky/feed/defs.defs.d.ts +8 -0
  79. package/dist/lexicons/app/bsky/feed/defs.defs.d.ts.map +1 -1
  80. package/dist/lexicons/app/bsky/feed/defs.defs.js +2 -0
  81. package/dist/lexicons/app/bsky/feed/defs.defs.js.map +1 -1
  82. package/dist/lexicons/app/bsky/feed/getQuotes.defs.d.ts +6 -0
  83. package/dist/lexicons/app/bsky/feed/getQuotes.defs.d.ts.map +1 -1
  84. package/dist/lexicons/app/bsky/feed/getQuotes.defs.js +2 -0
  85. package/dist/lexicons/app/bsky/feed/getQuotes.defs.js.map +1 -1
  86. package/dist/lexicons/tools/ozone/inbox/appealActionedSubject.d.ts +3 -0
  87. package/dist/lexicons/tools/ozone/inbox/appealActionedSubject.d.ts.map +1 -0
  88. package/dist/lexicons/tools/ozone/inbox/appealActionedSubject.defs.d.ts +65 -0
  89. package/dist/lexicons/tools/ozone/inbox/appealActionedSubject.defs.d.ts.map +1 -0
  90. package/dist/lexicons/tools/ozone/inbox/appealActionedSubject.defs.js +49 -0
  91. package/dist/lexicons/tools/ozone/inbox/appealActionedSubject.defs.js.map +1 -0
  92. package/dist/lexicons/tools/ozone/inbox/appealActionedSubject.js +6 -0
  93. package/dist/lexicons/tools/ozone/inbox/appealActionedSubject.js.map +1 -0
  94. package/dist/lexicons/tools/ozone/inbox/defs.d.ts +2 -0
  95. package/dist/lexicons/tools/ozone/inbox/defs.d.ts.map +1 -0
  96. package/dist/lexicons/tools/ozone/inbox/defs.defs.d.ts +89 -0
  97. package/dist/lexicons/tools/ozone/inbox/defs.defs.d.ts.map +1 -0
  98. package/dist/lexicons/tools/ozone/inbox/defs.defs.js +73 -0
  99. package/dist/lexicons/tools/ozone/inbox/defs.defs.js.map +1 -0
  100. package/dist/lexicons/tools/ozone/inbox/defs.js +5 -0
  101. package/dist/lexicons/tools/ozone/inbox/defs.js.map +1 -0
  102. package/dist/lexicons/tools/ozone/inbox.d.ts +3 -0
  103. package/dist/lexicons/tools/ozone/inbox.d.ts.map +1 -0
  104. package/dist/lexicons/tools/ozone/inbox.js +6 -0
  105. package/dist/lexicons/tools/ozone/inbox.js.map +1 -0
  106. package/dist/lexicons/tools/ozone/queue/createQueue.defs.d.ts +2 -0
  107. package/dist/lexicons/tools/ozone/queue/createQueue.defs.d.ts.map +1 -1
  108. package/dist/lexicons/tools/ozone/queue/createQueue.defs.js +2 -0
  109. package/dist/lexicons/tools/ozone/queue/createQueue.defs.js.map +1 -1
  110. package/dist/lexicons/tools/ozone/queue/defs.defs.d.ts +4 -0
  111. package/dist/lexicons/tools/ozone/queue/defs.defs.d.ts.map +1 -1
  112. package/dist/lexicons/tools/ozone/queue/defs.defs.js +2 -0
  113. package/dist/lexicons/tools/ozone/queue/defs.defs.js.map +1 -1
  114. package/dist/lexicons/tools/ozone/queue/updateQueue.defs.d.ts +3 -1
  115. package/dist/lexicons/tools/ozone/queue/updateQueue.defs.d.ts.map +1 -1
  116. package/dist/lexicons/tools/ozone/queue/updateQueue.defs.js +3 -0
  117. package/dist/lexicons/tools/ozone/queue/updateQueue.defs.js.map +1 -1
  118. package/dist/lexicons/tools/ozone/report/defs.defs.d.ts +89 -9
  119. package/dist/lexicons/tools/ozone/report/defs.defs.d.ts.map +1 -1
  120. package/dist/lexicons/tools/ozone/report/defs.defs.js +20 -0
  121. package/dist/lexicons/tools/ozone/report/defs.defs.js.map +1 -1
  122. package/dist/lexicons/tools/ozone/report/getLiveStats.defs.d.ts +1 -1
  123. package/dist/lexicons/tools/ozone/report/getLiveStats.defs.d.ts.map +1 -1
  124. package/dist/lexicons/tools/ozone/report/getLiveStats.defs.js +1 -1
  125. package/dist/lexicons/tools/ozone/report/getLiveStats.defs.js.map +1 -1
  126. package/dist/lexicons/tools/ozone/report/refreshStats.defs.d.ts +1 -1
  127. package/dist/lexicons/tools/ozone/report/refreshStats.defs.d.ts.map +1 -1
  128. package/dist/lexicons/tools/ozone/report/refreshStats.defs.js +1 -1
  129. package/dist/lexicons/tools/ozone/report/refreshStats.defs.js.map +1 -1
  130. package/dist/lexicons/tools/ozone.d.ts +1 -0
  131. package/dist/lexicons/tools/ozone.d.ts.map +1 -1
  132. package/dist/lexicons/tools/ozone.js +1 -0
  133. package/dist/lexicons/tools/ozone.js.map +1 -1
  134. package/dist/mod-service/index.d.ts +6 -2
  135. package/dist/mod-service/index.d.ts.map +1 -1
  136. package/dist/mod-service/index.js +15 -6
  137. package/dist/mod-service/index.js.map +1 -1
  138. package/dist/queue/service.d.ts +16 -3
  139. package/dist/queue/service.d.ts.map +1 -1
  140. package/dist/queue/service.js +81 -27
  141. package/dist/queue/service.js.map +1 -1
  142. package/dist/report/stats.d.ts +25 -31
  143. package/dist/report/stats.d.ts.map +1 -1
  144. package/dist/report/stats.js +269 -175
  145. package/dist/report/stats.js.map +1 -1
  146. package/dist/report/views.d.ts.map +1 -1
  147. package/dist/report/views.js +20 -0
  148. package/dist/report/views.js.map +1 -1
  149. package/dist/sequencer/outbox.d.ts +3 -0
  150. package/dist/sequencer/outbox.d.ts.map +1 -1
  151. package/dist/sequencer/outbox.js +76 -42
  152. package/dist/sequencer/outbox.js.map +1 -1
  153. package/dist/video-invalidator.d.ts +9 -0
  154. package/dist/video-invalidator.d.ts.map +1 -0
  155. package/dist/video-invalidator.js +20 -0
  156. package/dist/video-invalidator.js.map +1 -0
  157. package/package.json +11 -13
@@ -0,0 +1,92 @@
1
+ import { type DatetimeString, type DidString } from '@atproto/lex';
2
+ import type { InboxConfig } from '../config/config.js';
3
+ import type { Database } from '../db/index.js';
4
+ import type { ActionView, EnforcementView, SubjectView } from '../lexicons/tools/ozone/inbox/defs.js';
5
+ import type { ModSubject } from '../mod-service/subject.js';
6
+ import type { ModerationEventRow, ModerationSubjectStatusRow } from '../mod-service/types.js';
7
+ import type { AppealReport } from './appeal.js';
8
+ /** Everything one `subjectView` needs, as loaded from the database. */
9
+ export type SubjectSnapshot = {
10
+ status: ModerationSubjectStatusRow | null;
11
+ events: ModerationEventRow[];
12
+ /** Active, non-negated, unexpired label values on the subject. */
13
+ labels: string[];
14
+ /** Total public actions, exact even when `events` was capped. */
15
+ actionCount: number;
16
+ firstActionAt: DatetimeString | null;
17
+ /** Newest action the user is allowed to appeal, if any. */
18
+ latestAppealableAt: DatetimeString | null;
19
+ appealReport: AppealReport | null;
20
+ /** Latest nonempty `publicNote` from the appeal's close activities. */
21
+ appealPublicNote: string | null;
22
+ };
23
+ /**
24
+ * Load the public moderation state needed to hydrate one subject view.
25
+ *
26
+ * Only public columns are read. Event comments, `report.actionNote`, and
27
+ * `report_activity.internalNote` are moderator-facing and never leave the
28
+ * database on this path.
29
+ */
30
+ export declare const loadSubject: (db: Database, subject: ModSubject) => Promise<SubjectSnapshot>;
31
+ export type SubjectViewInput = {
32
+ subject: ModSubject;
33
+ /** DID of the moderation service the view speaks for. */
34
+ serviceDid: string;
35
+ cfg: InboxConfig;
36
+ snapshot: SubjectSnapshot;
37
+ };
38
+ export type EnforcementViewInput = {
39
+ subject: ModSubject;
40
+ status: ModerationSubjectStatusRow | null;
41
+ /** Active, non-negated, unexpired label values on the subject. */
42
+ labels: string[];
43
+ /** Public action history, newest first, used only for the takedown's scope. */
44
+ actions: ActionView[];
45
+ };
46
+ /** Public action type for one event, or null when it is not an entry. */
47
+ export declare const publicActionType: (row: ModerationEventRow) => string | null;
48
+ /**
49
+ * Map raw moderation events to the public action history, newest first.
50
+ *
51
+ * Reversals do not appear as actions. A `modEventReverseTakedown` stamps
52
+ * `reversedAt` on the newest takedown it undoes, and a label negation does the
53
+ * same to the `labelApplied` that put those values there - so the user sees
54
+ * "removed, then restored" as one action with an end date rather than as two
55
+ * unrelated events.
56
+ */
57
+ export declare const toActionViews: (rows: ModerationEventRow[]) => ActionView[];
58
+ /**
59
+ * Current enforcement, as a single state.
60
+ *
61
+ * A subject can be labeled and taken down at once, so precedence decides which
62
+ * one `state` reports: takendown > suspended > removed > labeled > none. Which
63
+ * of `takendown` / `suspended` / `removed` applies is a question of subject
64
+ * type and duration, not of three separate flags - a record is `removed`, an
65
+ * account is `takendown`, and either becomes a suspension when the takedown
66
+ * carried a duration.
67
+ *
68
+ * `labels[]` carries the label values whichever state won, minus `!takedown`
69
+ * and `!suspend`: those are written straight to the label table by the
70
+ * takedown paths and already say what `state` says.
71
+ */
72
+ export declare const toEnforcementView: ({ subject, status, labels, actions, }: EnforcementViewInput) => EnforcementView;
73
+ /**
74
+ * Compose one `tools.ozone.inbox.defs#subjectView` from an already-loaded
75
+ * snapshot. Pure and synchronous: every query belongs to the caller, so the
76
+ * view rules can be read and tested without a database.
77
+ *
78
+ * Returns null when the subject has no moderation history at all - it has
79
+ * never been actioned and has no status row - which is not a subject the
80
+ * inbox has anything to say about.
81
+ *
82
+ * `isRead` is deliberately absent: it is a comparison against a per-section
83
+ * read watermark, and Ozone has nowhere to store one yet. Sending a value now
84
+ * would mean inventing the watermark.
85
+ */
86
+ export declare const toSubjectView: ({ subject, serviceDid, snapshot, cfg, }: SubjectViewInput) => SubjectView | null;
87
+ /**
88
+ * Load a subject and compose its view: the read path in one call, for callers
89
+ * that have a database and a subject and want the finished thing.
90
+ */
91
+ export declare const hydrateSubjectView: (db: Database, subject: ModSubject, serviceDid: DidString, cfg: InboxConfig) => Promise<SubjectView | null>;
92
+ //# sourceMappingURL=views.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"views.d.ts","sourceRoot":"","sources":["../../src/inbox/views.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,SAAS,EAEf,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ACzC,kEAAkE;IAClE,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,+EAA+E;IAC/E,OAAO,EAAE,UAAU,EAAE,CAAA;CACtB,CAAA;AA4BD,yEAAyE;AACzE,eAAO,MAAM,gBAAgB,QAAS,kBAAkB,KAAG,MAAM,GAAG,IAkBnE,CAAA;AAkCD;;;;;;;;GAQG;AACH,eAAO,MAAM,aAAa,SAAU,kBAAkB,EAAE,KAAG,UAAU,EAuCpE,CAAA;AAQD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,iBAAiB,0CAK3B,oBAAoB,KAAG,eA+BzB,CAAA;AAUD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,aAAa,4CAKvB,gBAAgB,KAAG,WAAW,GAAG,IA+CnC,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,kBAAkB,OACzB,QAAQ,WACH,UAAU,cACP,SAAS,OAChB,WAAW,KACf,OAAO,CAAC,WAAW,GAAG,IAAI,CAMzB,CAAA"}
@@ -0,0 +1,313 @@
1
+ import { sql } from 'kysely';
2
+ import { currentDatetimeString, } from '@atproto/lex';
3
+ import { SUSPEND_LABEL, TAKEDOWN_LABEL } from '../mod-service/index.js';
4
+ import { APPEALABLE_EVENT_ACTIONS, EMAIL, LABEL, MUTE_REPORTER, PUBLIC_EVENT_ACTIONS, REVERSE_TAKEDOWN, REVOKE_CREDENTIALS, TAKEDOWN, eventSubjectFilter, findLatestAppealReport, subjectLabelUri, toAppealState, } from './appeal.js';
5
+ /**
6
+ * Newest events mapped into the action history. The totals query supplies the
7
+ * exact count and first-action date, so this cap bounds the read without making
8
+ * either number wrong. It has to stay generous enough that a takedown and the
9
+ * reversal undoing it normally land in the same window.
10
+ */
11
+ const EVENT_WINDOW = 50;
12
+ /**
13
+ * Load the public moderation state needed to hydrate one subject view.
14
+ *
15
+ * Only public columns are read. Event comments, `report.actionNote`, and
16
+ * `report_activity.internalNote` are moderator-facing and never leave the
17
+ * database on this path.
18
+ */
19
+ export const loadSubject = async (db, subject) => {
20
+ const appealable = sql.join(APPEALABLE_EVENT_ACTIONS.map((action) => sql.lit(action)));
21
+ const [status, labelRows, events, totals, appealReport] = await Promise.all([
22
+ db.db
23
+ .selectFrom('moderation_subject_status')
24
+ .where('did', '=', subject.did)
25
+ .where('recordPath', '=', subject.recordPath ?? '')
26
+ .where('convoId', '=', subject.convoId ?? '')
27
+ .selectAll()
28
+ .executeTakeFirst(),
29
+ db.db
30
+ .selectFrom('label')
31
+ .where('uri', '=', subjectLabelUri(subject))
32
+ .where('neg', '=', false)
33
+ .where((eb) => eb.or([eb('exp', 'is', null), eb('exp', '>', currentDatetimeString())]))
34
+ .select('val')
35
+ .execute(),
36
+ db.db
37
+ .selectFrom('moderation_event')
38
+ .where((eb) => eventSubjectFilter(eb, subject))
39
+ .where('action', 'in', [...PUBLIC_EVENT_ACTIONS])
40
+ .orderBy('id', 'desc')
41
+ .limit(EVENT_WINDOW)
42
+ .selectAll()
43
+ .execute(),
44
+ db.db
45
+ .selectFrom('moderation_event')
46
+ .where((eb) => eventSubjectFilter(eb, subject))
47
+ .where('action', 'in', [...PUBLIC_EVENT_ACTIONS])
48
+ .select([
49
+ sql `count(*) FILTER (WHERE action <> ${REVERSE_TAKEDOWN})::int`.as('actionCount'),
50
+ sql `min("createdAt") FILTER (WHERE action <> ${REVERSE_TAKEDOWN})`.as('firstActionAt'),
51
+ sql `max("createdAt") FILTER (WHERE action IN (${appealable}))`.as('latestAppealableAt'),
52
+ ])
53
+ .executeTakeFirstOrThrow(),
54
+ findLatestAppealReport(db, subject),
55
+ ]);
56
+ const publicNote = appealReport
57
+ ? await db.db
58
+ .selectFrom('report_activity')
59
+ .where('reportId', '=', appealReport.id)
60
+ .where('activityType', '=', 'closeActivity')
61
+ .where('publicNote', 'is not', null)
62
+ .where(sql `length(trim("publicNote")) > 0`)
63
+ .orderBy('id', 'desc')
64
+ .select('publicNote')
65
+ .executeTakeFirst()
66
+ : undefined;
67
+ return {
68
+ status: status ?? null,
69
+ events,
70
+ labels: labelRows.map((row) => row.val),
71
+ actionCount: totals.actionCount,
72
+ firstActionAt: totals.firstActionAt,
73
+ latestAppealableAt: totals.latestAppealableAt,
74
+ appealReport: appealReport ?? null,
75
+ appealPublicNote: publicNote?.publicNote ?? null,
76
+ };
77
+ };
78
+ const splitVals = (vals) => vals?.length ? vals.split(' ').filter(Boolean) : [];
79
+ /** `!takedown` and `!suspend` are already carried by the enforcement state. */
80
+ const withoutTakedownLabels = (vals) => vals.filter((val) => val !== TAKEDOWN_LABEL && val !== SUSPEND_LABEL);
81
+ const splitMeta = (row, key) => {
82
+ const raw = row.meta?.[key];
83
+ return typeof raw === 'string' && raw.length ? raw.split(',') : [];
84
+ };
85
+ /**
86
+ * `targetServices` names where a takedown was applied; empty means everywhere.
87
+ * An appview-only takedown is visible in the app but leaves the record hosted,
88
+ * which is what `app` means here.
89
+ */
90
+ const takedownScope = (row) => {
91
+ const services = splitMeta(row, 'targetServices');
92
+ if (!services.length)
93
+ return 'network';
94
+ return services.includes('pds') ? 'network' : 'app';
95
+ };
96
+ const isAccountSubject = (row) => row.subjectType === 'com.atproto.admin.defs#repoRef';
97
+ /** Public action type for one event, or null when it is not an entry. */
98
+ export const publicActionType = (row) => {
99
+ switch (row.action) {
100
+ case TAKEDOWN:
101
+ if (!isAccountSubject(row))
102
+ return 'contentRemoved';
103
+ return row.durationInHours ? 'accountSuspended' : 'accountTakedown';
104
+ case LABEL:
105
+ return splitVals(row.createLabelVals).length
106
+ ? 'labelApplied'
107
+ : 'labelRemoved';
108
+ case EMAIL:
109
+ return 'communicationSent';
110
+ case MUTE_REPORTER:
111
+ return 'reportingRestricted';
112
+ case REVOKE_CREDENTIALS:
113
+ return 'credentialsRevoked';
114
+ default:
115
+ return null;
116
+ }
117
+ };
118
+ const toActionView = (row) => {
119
+ const type = publicActionType(row);
120
+ if (!type)
121
+ return null;
122
+ const view = {
123
+ id: row.id,
124
+ type,
125
+ createdAt: row.createdAt,
126
+ };
127
+ if (row.expiresAt)
128
+ view.expiresAt = row.expiresAt;
129
+ if (row.action === TAKEDOWN) {
130
+ view.scope = takedownScope(row);
131
+ const policies = splitMeta(row, 'policies');
132
+ if (policies.length)
133
+ view.policies = policies;
134
+ }
135
+ if (row.action === EMAIL) {
136
+ const policies = splitMeta(row, 'policies');
137
+ if (policies.length)
138
+ view.policies = policies;
139
+ }
140
+ if (row.action === LABEL) {
141
+ view.scope = 'app';
142
+ const labels = withoutTakedownLabels(type === 'labelApplied'
143
+ ? splitVals(row.createLabelVals)
144
+ : splitVals(row.negateLabelVals));
145
+ if (labels.length)
146
+ view.labels = labels;
147
+ }
148
+ return view;
149
+ };
150
+ /**
151
+ * Map raw moderation events to the public action history, newest first.
152
+ *
153
+ * Reversals do not appear as actions. A `modEventReverseTakedown` stamps
154
+ * `reversedAt` on the newest takedown it undoes, and a label negation does the
155
+ * same to the `labelApplied` that put those values there - so the user sees
156
+ * "removed, then restored" as one action with an end date rather than as two
157
+ * unrelated events.
158
+ */
159
+ export const toActionViews = (rows) => {
160
+ // Oldest first, so a reversal always meets the action it undoes.
161
+ const ordered = [...rows].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id - b.id);
162
+ const actions = [];
163
+ const openTakedowns = [];
164
+ const openLabels = new Map();
165
+ for (const row of ordered) {
166
+ if (row.action === REVERSE_TAKEDOWN) {
167
+ const takedown = openTakedowns.pop();
168
+ if (takedown)
169
+ takedown.reversedAt = row.createdAt;
170
+ continue;
171
+ }
172
+ const view = toActionView(row);
173
+ if (!view)
174
+ continue;
175
+ actions.push(view);
176
+ if (row.action === TAKEDOWN) {
177
+ openTakedowns.push(view);
178
+ }
179
+ if (row.action === LABEL) {
180
+ for (const val of withoutTakedownLabels(splitVals(row.negateLabelVals))) {
181
+ const applied = openLabels.get(val);
182
+ if (applied) {
183
+ applied.reversedAt = row.createdAt;
184
+ openLabels.delete(val);
185
+ }
186
+ }
187
+ for (const val of withoutTakedownLabels(splitVals(row.createLabelVals))) {
188
+ openLabels.set(val, view);
189
+ }
190
+ }
191
+ }
192
+ return actions.reverse();
193
+ };
194
+ const TAKEDOWN_TYPES = new Set([
195
+ 'contentRemoved',
196
+ 'accountSuspended',
197
+ 'accountTakedown',
198
+ ]);
199
+ /**
200
+ * Current enforcement, as a single state.
201
+ *
202
+ * A subject can be labeled and taken down at once, so precedence decides which
203
+ * one `state` reports: takendown > suspended > removed > labeled > none. Which
204
+ * of `takendown` / `suspended` / `removed` applies is a question of subject
205
+ * type and duration, not of three separate flags - a record is `removed`, an
206
+ * account is `takendown`, and either becomes a suspension when the takedown
207
+ * carried a duration.
208
+ *
209
+ * `labels[]` carries the label values whichever state won, minus `!takedown`
210
+ * and `!suspend`: those are written straight to the label table by the
211
+ * takedown paths and already say what `state` says.
212
+ */
213
+ export const toEnforcementView = ({ subject, status, labels, actions, }) => {
214
+ const active = labels.filter((val) => val !== TAKEDOWN_LABEL && val !== SUSPEND_LABEL);
215
+ const suspendUntil = status?.suspendUntil;
216
+ const temporary = !!suspendUntil && new Date(suspendUntil) > new Date();
217
+ const enforced = !!status?.takendown || temporary;
218
+ let state = 'none';
219
+ if (enforced) {
220
+ if (!subject.isRepo())
221
+ state = 'removed';
222
+ else
223
+ state = temporary ? 'suspended' : 'takendown';
224
+ }
225
+ else if (active.length) {
226
+ state = 'labeled';
227
+ }
228
+ const view = { state };
229
+ if (state === 'none')
230
+ return view;
231
+ if (state === 'labeled') {
232
+ view.scope = 'app';
233
+ }
234
+ else {
235
+ const takedown = actions.find((action) => TAKEDOWN_TYPES.has(action.type) && !action.reversedAt);
236
+ if (takedown?.scope)
237
+ view.scope = takedown.scope;
238
+ if (temporary && suspendUntil)
239
+ view.expiresAt = suspendUntil;
240
+ }
241
+ if (active.length)
242
+ view.labels = active;
243
+ return view;
244
+ };
245
+ const latest = (...times) => {
246
+ const known = times.filter((time) => !!time);
247
+ if (!known.length)
248
+ return null;
249
+ return known.reduce((a, b) => (Date.parse(a) >= Date.parse(b) ? a : b));
250
+ };
251
+ /**
252
+ * Compose one `tools.ozone.inbox.defs#subjectView` from an already-loaded
253
+ * snapshot. Pure and synchronous: every query belongs to the caller, so the
254
+ * view rules can be read and tested without a database.
255
+ *
256
+ * Returns null when the subject has no moderation history at all - it has
257
+ * never been actioned and has no status row - which is not a subject the
258
+ * inbox has anything to say about.
259
+ *
260
+ * `isRead` is deliberately absent: it is a comparison against a per-section
261
+ * read watermark, and Ozone has nowhere to store one yet. Sending a value now
262
+ * would mean inventing the watermark.
263
+ */
264
+ export const toSubjectView = ({ subject, serviceDid, snapshot, cfg, }) => {
265
+ if (!snapshot.status && !snapshot.actionCount)
266
+ return null;
267
+ const actions = toActionViews(snapshot.events);
268
+ const enforcement = toEnforcementView({
269
+ subject,
270
+ status: snapshot.status,
271
+ labels: snapshot.labels,
272
+ actions,
273
+ });
274
+ const { view: appeal, availableActions } = toAppealState({
275
+ subject,
276
+ status: snapshot.status,
277
+ report: snapshot.appealReport,
278
+ publicNote: snapshot.appealPublicNote,
279
+ latestAppealableAt: snapshot.latestAppealableAt,
280
+ windowMonths: cfg.appealWindowMonths,
281
+ });
282
+ // The subject dates from its first action, not from whenever Ozone first
283
+ // opened a status row for it.
284
+ const createdAt = snapshot.firstActionAt ??
285
+ snapshot.status?.createdAt ??
286
+ currentDatetimeString();
287
+ const updatedAt = latest(actions[0]?.createdAt, appeal.appealedAt, appeal.resolvedAt, snapshot.status?.updatedAt) ?? createdAt;
288
+ const view = {
289
+ src: serviceDid,
290
+ subject: subject.lex(),
291
+ enforcement,
292
+ appeal,
293
+ availableActions,
294
+ createdAt,
295
+ updatedAt,
296
+ };
297
+ if (actions.length) {
298
+ view.latestAction = actions[0];
299
+ view.actionCount = snapshot.actionCount;
300
+ }
301
+ return view;
302
+ };
303
+ /**
304
+ * Load a subject and compose its view: the read path in one call, for callers
305
+ * that have a database and a subject and want the finished thing.
306
+ */
307
+ export const hydrateSubjectView = async (db, subject, serviceDid, cfg) => toSubjectView({
308
+ subject,
309
+ serviceDid,
310
+ cfg,
311
+ snapshot: await loadSubject(db, subject),
312
+ });
313
+ //# sourceMappingURL=views.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"views.js","sourceRoot":"","sources":["../../src/inbox/views.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAC5B,OAAO,EAGL,qBAAqB,GACtB,MAAM,cAAc,CAAA;AAQrB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAOvE,OAAO,EACL,wBAAwB,EACxB,KAAK,EACL,KAAK,EACL,aAAa,EACb,oBAAoB,EACpB,gBAAgB,EAChB,kBAAkB,EAClB,QAAQ,EACR,kBAAkB,EAClB,sBAAsB,EACtB,eAAe,EACf,aAAa,GACd,MAAM,aAAa,CAAA;AAEpB;;;;;GAKG;AACH,MAAM,YAAY,GAAG,EAAE,CAAA;AAwBvB;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAC9B,EAAY,EACZ,OAAmB,EACO,EAAE;IAC5B,MAAM,UAAU,GAAG,GAAG,CAAC,IAAI,CACzB,wBAAwB,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAC1D,CAAA;IAED,MAAM,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QAC1E,EAAE,CAAC,EAAE;aACF,UAAU,CAAC,2BAA2B,CAAC;aACvC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC;aAC9B,KAAK,CAAC,YAAY,EAAE,GAAG,EAAE,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC;aAClD,KAAK,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC;aAC5C,S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AAM,EAAE,SAAS,CAC3B,IAAI,SAAS,CAAA;IAEhB,MAAM,IAAI,GAAgB;QACxB,GAAG,EAAE,UAAuB;QAC5B,OAAO,EAAE,OAAO,CAAC,GAAG,EAA4B;QAChD,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,SAAS;QACT,SAAS;KACV,CAAA;IACD,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QACnB,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;QAC9B,IAAI,CAAC,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAA;IACzC,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,EACrC,EAAY,EACZ,OAAmB,EACnB,UAAqB,EACrB,GAAgB,EACa,EAAE,CAC/B,aAAa,CAAC;IACZ,OAAO;IACP,UAAU;IACV,GAAG;IACH,QAAQ,EAAE,MAAM,WAAW,CAAC,EAAE,EAAE,OAAO,CAAC;CACzC,CAAC,CAAA","sourcesContent":["import { sql } from 'kysely'\nimport {\n type DatetimeString,\n type DidString,\n currentDatetimeString,\n} from '@atproto/lex'\nimport type { InboxConfig } from '../config/config.js'\nimport type { Database } from '../db/index.js'\nimport type {\n ActionView,\n EnforcementView,\n SubjectView,\n} from '../lexicons/tools/ozone/inbox/defs.js'\nimport { SUSPEND_LABEL, TAKEDOWN_LABEL } from '../mod-service/index.js'\nimport type { ModSubject } from '../mod-service/subject.js'\nimport type {\n ModerationEventRow,\n ModerationSubjectStatusRow,\n} from '../mod-service/types.js'\nimport type { AppealReport } from './appeal.js'\nimport {\n APPEALABLE_EVENT_ACTIONS,\n EMAIL,\n LABEL,\n MUTE_REPORTER,\n PUBLIC_EVENT_ACTIONS,\n REVERSE_TAKEDOWN,\n REVOKE_CREDENTIALS,\n TAKEDOWN,\n eventSubjectFilter,\n findLatestAppealReport,\n subjectLabelUri,\n toAppealState,\n} from './appeal.js'\n\n/**\n * Newest events mapped into the action history. The totals query supplies the\n * exact count and first-action date, so this cap bounds the read without making\n * either number wrong. It has to stay generous enough that a takedown and the\n * reversal undoing it normally land in the same window.\n */\nconst EVENT_WINDOW = 50\n\n/** Everything one `subjectView` needs, as loaded from the database. */\nexport type SubjectSnapshot = {\n status: ModerationSubjectStatusRow | null\n events: ModerationEventRow[]\n /** Active, non-negated, unexpired label values on the subject. */\n labels: string[]\n /** Total public actions, exact even when `events` was capped. */\n actionCount: number\n firstActionAt: DatetimeString | null\n /** Newest action the user is allowed to appeal, if any. */\n latestAppealableAt: DatetimeString | null\n appealReport: AppealReport | null\n /** Latest nonempty `publicNote` from the appeal's close activities. */\n appealPublicNote: string | null\n}\n\ntype EventTotals = {\n actionCount: number\n firstActionAt: DatetimeString | null\n latestAppealableAt: DatetimeString | null\n}\n\n/**\n * Load the public moderation state needed to hydrate one subject view.\n *\n * Only public columns are read. Event comments, `report.actionNote`, and\n * `report_activity.internalNote` are moderator-facing and never leave the\n * database on this path.\n */\nexport const loadSubject = async (\n db: Database,\n subject: ModSubject,\n): Promise<SubjectSnapshot> => {\n const appealable = sql.join(\n APPEALABLE_EVENT_ACTIONS.map((action) => sql.lit(action)),\n )\n\n const [status, labelRows, events, totals, appealReport] = await Promise.all([\n db.db\n .selectFrom('moderation_subject_status')\n .where('did', '=', subject.did)\n .where('recordPath', '=', subject.recordPath ?? '')\n .where('convoId', '=', subject.convoId ?? '')\n .selectAll()\n .executeTakeFirst(),\n\n db.db\n .selectFrom('label')\n .where('uri', '=', subjectLabelUri(subject))\n .where('neg', '=', false)\n .where((eb) =>\n eb.or([eb('exp', 'is', null), eb('exp', '>', currentDatetimeString())]),\n )\n .select('val')\n .execute(),\n\n db.db\n .selectFrom('moderation_event')\n .where((eb) => eventSubjectFilter(eb, subject))\n .where('action', 'in', [...PUBLIC_EVENT_ACTIONS])\n .orderBy('id', 'desc')\n .limit(EVENT_WINDOW)\n .selectAll()\n .execute(),\n\n db.db\n .selectFrom('moderation_event')\n .where((eb) => eventSubjectFilter(eb, subject))\n .where('action', 'in', [...PUBLIC_EVENT_ACTIONS])\n .select([\n sql<number>`count(*) FILTER (WHERE action <> ${REVERSE_TAKEDOWN})::int`.as(\n 'actionCount',\n ),\n sql<\n string | null\n >`min(\"createdAt\") FILTER (WHERE action <> ${REVERSE_TAKEDOWN})`.as(\n 'firstActionAt',\n ),\n sql<\n string | null\n >`max(\"createdAt\") FILTER (WHERE action IN (${appealable}))`.as(\n 'latestAppealableAt',\n ),\n ])\n .executeTakeFirstOrThrow() as Promise<EventTotals>,\n\n findLatestAppealReport(db, subject),\n ])\n\n const publicNote = appealReport\n ? await db.db\n .selectFrom('report_activity')\n .where('reportId', '=', appealReport.id)\n .where('activityType', '=', 'closeActivity')\n .where('publicNote', 'is not', null)\n .where(sql<boolean>`length(trim(\"publicNote\")) > 0`)\n .orderBy('id', 'desc')\n .select('publicNote')\n .executeTakeFirst()\n : undefined\n\n return {\n status: status ?? null,\n events,\n labels: labelRows.map((row) => row.val),\n actionCount: totals.actionCount,\n firstActionAt: totals.firstActionAt,\n latestAppealableAt: totals.latestAppealableAt,\n appealReport: appealReport ?? null,\n appealPublicNote: publicNote?.publicNote ?? null,\n }\n}\n\nexport type SubjectViewInput = {\n subject: ModSubject\n /** DID of the moderation service the view speaks for. */\n serviceDid: string\n cfg: InboxConfig\n snapshot: SubjectSnapshot\n}\n\nexport type EnforcementViewInput = {\n subject: ModSubject\n status: ModerationSubjectStatusRow | null\n /** Active, non-negated, unexpired label values on the subject. */\n labels: string[]\n /** Public action history, newest first, used only for the takedown's scope. */\n actions: ActionView[]\n}\n\nconst splitVals = (vals: string | null): string[] =>\n vals?.length ? vals.split(' ').filter(Boolean) : []\n\n/** `!takedown` and `!suspend` are already carried by the enforcement state. */\nconst withoutTakedownLabels = (vals: string[]): string[] =>\n vals.filter((val) => val !== TAKEDOWN_LABEL && val !== SUSPEND_LABEL)\n\nconst splitMeta = (row: ModerationEventRow, key: string): string[] => {\n const raw = row.meta?.[key]\n return typeof raw === 'string' && raw.length ? raw.split(',') : []\n}\n\n/**\n * `targetServices` names where a takedown was applied; empty means everywhere.\n * An appview-only takedown is visible in the app but leaves the record hosted,\n * which is what `app` means here.\n */\nconst takedownScope = (row: ModerationEventRow): ActionView['scope'] => {\n const services = splitMeta(row, 'targetServices')\n if (!services.length) return 'network'\n return services.includes('pds') ? 'network' : 'app'\n}\n\nconst isAccountSubject = (row: ModerationEventRow): boolean =>\n row.subjectType === 'com.atproto.admin.defs#repoRef'\n\n/** Public action type for one event, or null when it is not an entry. */\nexport const publicActionType = (row: ModerationEventRow): string | null => {\n switch (row.action) {\n case TAKEDOWN:\n if (!isAccountSubject(row)) return 'contentRemoved'\n return row.durationInHours ? 'accountSuspended' : 'accountTakedown'\n case LABEL:\n return splitVals(row.createLabelVals).length\n ? 'labelApplied'\n : 'labelRemoved'\n case EMAIL:\n return 'communicationSent'\n case MUTE_REPORTER:\n return 'reportingRestricted'\n case REVOKE_CREDENTIALS:\n return 'credentialsRevoked'\n default:\n return null\n }\n}\n\nconst toActionView = (row: ModerationEventRow): ActionView | null => {\n const type = publicActionType(row)\n if (!type) return null\n\n const view: ActionView = {\n id: row.id,\n type,\n createdAt: row.createdAt,\n }\n if (row.expiresAt) view.expiresAt = row.expiresAt\n\n if (row.action === TAKEDOWN) {\n view.scope = takedownScope(row)\n const policies = splitMeta(row, 'policies')\n if (policies.length) view.policies = policies\n }\n if (row.action === EMAIL) {\n const policies = splitMeta(row, 'policies')\n if (policies.length) view.policies = policies\n }\n if (row.action === LABEL) {\n view.scope = 'app'\n const labels = withoutTakedownLabels(\n type === 'labelApplied'\n ? splitVals(row.createLabelVals)\n : splitVals(row.negateLabelVals),\n )\n if (labels.length) view.labels = labels\n }\n return view\n}\n\n/**\n * Map raw moderation events to the public action history, newest first.\n *\n * Reversals do not appear as actions. A `modEventReverseTakedown` stamps\n * `reversedAt` on the newest takedown it undoes, and a label negation does the\n * same to the `labelApplied` that put those values there - so the user sees\n * \"removed, then restored\" as one action with an end date rather than as two\n * unrelated events.\n */\nexport const toActionViews = (rows: ModerationEventRow[]): ActionView[] => {\n // Oldest first, so a reversal always meets the action it undoes.\n const ordered = [...rows].sort(\n (a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id - b.id,\n )\n\n const actions: ActionView[] = []\n const openTakedowns: ActionView[] = []\n const openLabels = new Map<string, ActionView>()\n\n for (const row of ordered) {\n if (row.action === REVERSE_TAKEDOWN) {\n const takedown = openTakedowns.pop()\n if (takedown) takedown.reversedAt = row.createdAt\n continue\n }\n\n const view = toActionView(row)\n if (!view) continue\n actions.push(view)\n\n if (row.action === TAKEDOWN) {\n openTakedowns.push(view)\n }\n if (row.action === LABEL) {\n for (const val of withoutTakedownLabels(splitVals(row.negateLabelVals))) {\n const applied = openLabels.get(val)\n if (applied) {\n applied.reversedAt = row.createdAt\n openLabels.delete(val)\n }\n }\n for (const val of withoutTakedownLabels(splitVals(row.createLabelVals))) {\n openLabels.set(val, view)\n }\n }\n }\n\n return actions.reverse()\n}\n\nconst TAKEDOWN_TYPES = new Set([\n 'contentRemoved',\n 'accountSuspended',\n 'accountTakedown',\n])\n\n/**\n * Current enforcement, as a single state.\n *\n * A subject can be labeled and taken down at once, so precedence decides which\n * one `state` reports: takendown > suspended > removed > labeled > none. Which\n * of `takendown` / `suspended` / `removed` applies is a question of subject\n * type and duration, not of three separate flags - a record is `removed`, an\n * account is `takendown`, and either becomes a suspension when the takedown\n * carried a duration.\n *\n * `labels[]` carries the label values whichever state won, minus `!takedown`\n * and `!suspend`: those are written straight to the label table by the\n * takedown paths and already say what `state` says.\n */\nexport const toEnforcementView = ({\n subject,\n status,\n labels,\n actions,\n}: EnforcementViewInput): EnforcementView => {\n const active = labels.filter(\n (val) => val !== TAKEDOWN_LABEL && val !== SUSPEND_LABEL,\n )\n const suspendUntil = status?.suspendUntil\n const temporary = !!suspendUntil && new Date(suspendUntil) > new Date()\n const enforced = !!status?.takendown || temporary\n\n let state: EnforcementView['state'] = 'none'\n if (enforced) {\n if (!subject.isRepo()) state = 'removed'\n else state = temporary ? 'suspended' : 'takendown'\n } else if (active.length) {\n state = 'labeled'\n }\n\n const view: EnforcementView = { state }\n if (state === 'none') return view\n\n if (state === 'labeled') {\n view.scope = 'app'\n } else {\n const takedown = actions.find(\n (action) => TAKEDOWN_TYPES.has(action.type) && !action.reversedAt,\n )\n if (takedown?.scope) view.scope = takedown.scope\n if (temporary && suspendUntil) view.expiresAt = suspendUntil\n }\n\n if (active.length) view.labels = active\n return view\n}\n\nconst latest = (\n ...times: (DatetimeString | null | undefined)[]\n): DatetimeString | null => {\n const known = times.filter((time): time is DatetimeString => !!time)\n if (!known.length) return null\n return known.reduce((a, b) => (Date.parse(a) >= Date.parse(b) ? a : b))\n}\n\n/**\n * Compose one `tools.ozone.inbox.defs#subjectView` from an already-loaded\n * snapshot. Pure and synchronous: every query belongs to the caller, so the\n * view rules can be read and tested without a database.\n *\n * Returns null when the subject has no moderation history at all - it has\n * never been actioned and has no status row - which is not a subject the\n * inbox has anything to say about.\n *\n * `isRead` is deliberately absent: it is a comparison against a per-section\n * read watermark, and Ozone has nowhere to store one yet. Sending a value now\n * would mean inventing the watermark.\n */\nexport const toSubjectView = ({\n subject,\n serviceDid,\n snapshot,\n cfg,\n}: SubjectViewInput): SubjectView | null => {\n if (!snapshot.status && !snapshot.actionCount) return null\n\n const actions = toActionViews(snapshot.events)\n const enforcement = toEnforcementView({\n subject,\n status: snapshot.status,\n labels: snapshot.labels,\n actions,\n })\n const { view: appeal, availableActions } = toAppealState({\n subject,\n status: snapshot.status,\n report: snapshot.appealReport,\n publicNote: snapshot.appealPublicNote,\n latestAppealableAt: snapshot.latestAppealableAt,\n windowMonths: cfg.appealWindowMonths,\n })\n\n // The subject dates from its first action, not from whenever Ozone first\n // opened a status row for it.\n const createdAt =\n snapshot.firstActionAt ??\n snapshot.status?.createdAt ??\n currentDatetimeString()\n const updatedAt =\n latest(\n actions[0]?.createdAt,\n appeal.appealedAt,\n appeal.resolvedAt,\n snapshot.status?.updatedAt,\n ) ?? createdAt\n\n const view: SubjectView = {\n src: serviceDid as DidString,\n subject: subject.lex() as SubjectView['subject'],\n enforcement,\n appeal,\n availableActions,\n createdAt,\n updatedAt,\n }\n if (actions.length) {\n view.latestAction = actions[0]\n view.actionCount = snapshot.actionCount\n }\n return view\n}\n\n/**\n * Load a subject and compose its view: the read path in one call, for callers\n * that have a database and a subject and want the finished thing.\n */\nexport const hydrateSubjectView = async (\n db: Database,\n subject: ModSubject,\n serviceDid: DidString,\n cfg: InboxConfig,\n): Promise<SubjectView | null> =>\n toSubjectView({\n subject,\n serviceDid,\n cfg,\n snapshot: await loadSubject(db, subject),\n })\n"]}
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export { AppContext } from './context.js';
8
8
  export { EventPusher, EventReverser, OzoneDaemon } from './daemon/index.js';
9
9
  export { Database } from './db/index.js';
10
10
  export { type ImageInvalidator } from './image-invalidator.js';
11
+ export { VideoInvalidator } from './video-invalidator.js';
11
12
  export { httpLogger } from './logger.js';
12
13
  export declare class OzoneService {
13
14
  ctx: AppContext;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AAIjC,OAAO,OAAO,MAAM,SAAS,CAAA;AAE7B,OAAO,KAAK,UAAU,MAAM,aAAa,CAAA;AAWzC,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAClE,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAOjE,cAAc,mBAAmB,CAAA;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC3E,OAAO,EAAE,QA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AAE,UAAU,CAAC,QAAQ,GAC7B,OAAO,CAAC,YAAY,CAAC,CA+DvB;IAEK,kBAAkB,kBA4BvB;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAgClC;IAEK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAkB7B;CACF;AAED,MAAM,MAAM,kBAAkB,GAAG;IAI/B,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CACrC,CAAA;AAOD,qBAAa,cAAc;IAGN,GAAG,EAAE,OAAO,CAAC,WAAW;IAF3C,OAAO,CAAC,UAAU,CAAC,CAAgB;IAEnC,YAAmB,GAAG,EAAE,OAAO,CAAC,WAAW,EAAI;IAE/C,MAAM,CAAC,MAAM,CACX,QAAQ,EAAE,UAAU,CAAC,QAAQ,EAC7B,IAAI,GAAE,kBAAuB,GAC5B,cAAc,CAuChB;IAEK,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAM9C;IAEK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAE7B;CACF;eAEc,YAAY"}
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ export { AppContext } from './context.js';
18
18
  export { EventPusher, EventReverser, OzoneDaemon } from './daemon/index.js';
19
19
  export { Database } from './db/index.js';
20
20
  export {} from './image-invalidator.js';
21
+ export { VideoInvalidator } from './video-invalidator.js';
21
22
  export { httpLogger } from './logger.js';
22
23
  const KNOWN_METHODS = new Set(walk(lexicons)
23
24
  .filter((s) => s instanceof Procedure ||
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAGhC,OAAO,WAAW,MAAM,aAAa,CAAA;AACrC,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7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K,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,UAAU,EAAE,SAAS,EAAE,CAAA;IACpC,CAAC;CACF;AAED,eAAe,YAAY,CAAA","sourcesContent":["import events from 'node:events'\nimport type http from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport compression from 'compression'\nimport cors from 'cors'\nimport express from 'express'\nimport { type HttpTerminator, createHttpTerminator } from 'http-terminator'\nimport * as prometheus from 'prom-client'\nimport { DAY, SECOND } from '@atproto/common'\nimport {\n type DidString,\n Procedure,\n Query,\n Subscription,\n walk,\n} from '@atproto/lex'\nimport { createServer, extractUrlNsid } from '@atproto/xrpc-server'\nimport API, { health, wellKnown } from './api/index.js'\nimport type { OzoneConfig, OzoneSecrets } from './config/index.js'\nimport { AppContext, type AppContextOptions } from './context.js'\nimport type { Member } from './db/schema/member.js'\nimport * as error from './error.js'\nimport * as lexicons from './lexicons/index.js'\nimport { tools } from './lexicons/index.js'\nimport { dbLogger, loggerMiddleware } from './logger.js'\n\nexport * from './config/index.js'\nexport { AppContext } from './context.js'\nexport { EventPusher, EventReverser, OzoneDaemon } from './daemon/index.js'\nexport { Database } from './db/index.js'\nexport { type ImageInvalidator } from './image-invalidator.js'\nexport { httpLogger } from './logger.js'\n\nconst KNOWN_METHODS = new Set<string>(\n walk(lexicons)\n .filter(\n (s) =>\n s instanceof Procedure ||\n s instanceof Query ||\n s instanceof Subscription,\n )\n .map((s) => s.nsid),\n)\n\nexport class OzoneService {\n public ctx: AppContext\n public app: express.Application\n public server?: http.Server\n private terminator?: HttpTerminator\n private dbStatsInterval?: NodeJS.Timeout\n\n constructor(opts: { ctx: AppContext; app: express.Application }) {\n this.ctx = opts.ctx\n this.app = opts.app\n }\n\n static async create(\n cfg: OzoneConfig,\n secrets: OzoneSecrets,\n overrides?: Partial<AppContextOptions>,\n // Optional Prometheus registry. Its presence is the collection gate: when\n // omitted (dev-env, tests, self-hosted distros that don't opt in), no\n // metrics are collected and no per-request timing overhead is incurred.\n register?: prometheus.Registry,\n ): Promise<OzoneService> {\n const app = express()\n app.set('trust proxy', true)\n app.use(cors({ maxAge: DAY / SECOND }))\n app.use(loggerMiddleware)\n app.use(compression())\n\n const ctx = await AppContext.fromConfig(cfg, secrets, overrides)\n\n let server = createServer([], {\n validateResponse: false,\n payload: {\n jsonLimit: 100 * 1024, // 100kb\n textLimit: 100 * 1024, // 100kb\n blobLimit: 5 * 1024 * 1024, // 5mb\n },\n })\n\n server = API(server, ctx)\n\n if (register) {\n // Collect standard metrics on the nodejs runtime (GC, event loop, etc).\n prometheus.collectDefaultMetrics({ prefix: 'ozone_', register })\n\n // Per-XRPC-method request timing. Labeled by nsid (e.g.\n // tools.ozone.moderation.emitEvent) so every method is covered without\n // per-endpoint code. This middleware runs above the xrpc router, so\n // req.route is not yet populated; we derive the nsid from the URL instead.\n const xrpcRequestDuration = new prometheus.Histogram({\n name: 'ozone_xrpc_request_duration_seconds',\n help: 'XRPC request duration in seconds, by method',\n labelNames: ['nsid', 'method', 'code'],\n registers: [register],\n })\n\n app.use((req, res, next) => {\n const nsid = extractUrlNsid(req.originalUrl)\n // Only record xrpc methods; non-xrpc paths (health, robots, frontend)\n // are skipped to keep the metric's label cardinality bounded.\n if (!nsid) return next()\n // extractUrlNsid only validates path *shape*, not that the method\n // exists. A caller can hit /xrpc/<well-formed-but-bogus-nsid> (served a\n // 501), so labeling by the raw nsid lets external traffic mint unbounded\n // series and grow prom-client's memory without limit. Bucket anything\n // that isn't a registered query/procedure under a single `unknown` label.\n const end = xrpcRequestDuration.startTimer()\n res.on('finish', () => {\n end({\n nsid: KNOWN_METHODS.has(nsid) ? nsid : 'unknown',\n method: req.method,\n code: res.statusCode,\n })\n })\n next()\n })\n }\n\n app.use(health.createRouter(ctx))\n app.use(wellKnown.createRouter(ctx))\n app.use(server.router)\n app.use(error.handler)\n\n return new OzoneService({ ctx, app })\n }\n\n async seedInitialMembers() {\n const members: Array<{ role: Member['role']; did: DidString }> = []\n this.ctx.cfg.access.admins.forEach((did) =>\n members.push({\n role: tools.ozone.team.defs.RoleAdmin,\n did,\n }),\n )\n this.ctx.cfg.access.triage.forEach((did) =>\n members.push({\n role: tools.ozone.team.defs.RoleTriage,\n did,\n }),\n )\n this.ctx.cfg.access.moderators.forEach((did) =>\n members.push({\n role: tools.ozone.team.defs.RoleModerator,\n did,\n }),\n )\n\n for (const member of members) {\n const service = this.ctx.teamService(this.ctx.db)\n await service.upsert({\n ...member,\n lastUpdatedBy: this.ctx.cfg.service.did,\n })\n }\n }\n\n async start(): Promise<http.Server> {\n if (this.dbStatsInterval) {\n throw new Error(`${this.constructor.name} already started`)\n }\n\n // Any moderator that are configured via env var may not exist in the database\n // so we need to sync them from env var to the database\n await this.seedInitialMembers()\n\n this.dbStatsInterval = setInterval(() => {\n dbLogger.info(\n {\n idleCount: this.ctx.db.pool.idleCount,\n totalCount: this.ctx.db.pool.totalCount,\n waitingCount: this.ctx.db.pool.waitingCount,\n },\n 'db pool stats',\n )\n dbLogger.info(\n this.ctx.backgroundQueue.getStats(),\n 'background queue stats',\n )\n }, 10000)\n await this.ctx.sequencer.start()\n const server = this.app.listen(this.ctx.cfg.service.port)\n this.server = server\n server.keepAliveTimeout = 90000\n this.terminator = createHttpTerminator({ server })\n await events.once(server, 'listening')\n const { port } = server.address() as AddressInfo\n this.ctx.assignPort(port)\n return server\n }\n\n async destroy(): Promise<void> {\n clearInterval(this.dbStatsInterval)\n this.dbStatsInterval = undefined\n\n // @TODO Use a disposable stack when Node24 becomes the min supported version\n try {\n await this.terminator?.terminate()\n } finally {\n try {\n await this.ctx.backgroundQueue.destroy()\n } finally {\n try {\n await this.ctx.sequencer.destroy()\n } finally {\n await this.ctx.db.close()\n }\n }\n }\n }\n}\n\nexport type MetricsServiceOpts = {\n // Optional readiness probe. Should reject/throw when the service cannot serve\n // traffic (e.g. database unreachable). When omitted, /readyz behaves like\n // /livez (process-alive only).\n readinessCheck?: () => Promise<void>\n}\n\n// A separate, pull-based Prometheus metrics server. Kept on its own port and\n// HTTP server so private metrics and ops probes are never exposed on the public\n// ozone server. Only started by an entrypoint when metrics are explicitly\n// opted in. Also serves Kubernetes-style liveness (/livez) and readiness\n// (/readyz) probes.\nexport class MetricsService {\n private terminator?: HttpTerminator\n\n constructor(public app: express.Application) {}\n\n static create(\n register: prometheus.Registry,\n opts: MetricsServiceOpts = {},\n ): MetricsService {\n const app = express()\n\n app.get('/metrics', async (_req, res) => {\n // Express 4 does not catch rejections from async handlers, so an\n // unguarded throw here (e.g. a custom collector failing) would surface as\n // an unhandledRejection and crash the process. Metrics are a passive\n // side-channel and must never take down the service.\n try {\n const metrics = await register.metrics()\n res.set('Content-Type', register.contentType)\n res.end(metrics)\n } catch {\n res.status(500).end()\n }\n })\n\n // Liveness: is the process up and the event loop responsive? No external\n // dependencies, so a transient dependency outage never causes a pod restart.\n app.get('/livez', (_req, res) => {\n res.send({ status: 'ok' })\n })\n\n // Readiness: can the service handle traffic right now? Runs the optional\n // readiness check (e.g. a db ping); a failure pulls the pod from the load\n // balancer without restarting it.\n app.get('/readyz', async (_req, res) => {\n if (!opts.readinessCheck) {\n return res.send({ status: 'ok' })\n }\n try {\n await opts.readinessCheck()\n res.send({ status: 'ok' })\n } catch {\n res.status(503).send({ status: 'not ready' })\n }\n })\n\n return new MetricsService(app)\n }\n\n async start(port: number): Promise<http.Server> {\n const server = this.app.listen(port)\n server.keepAliveTimeout = 90000\n this.terminator = createHttpTerminator({ server })\n await events.once(server, 'listening')\n return server\n }\n\n async destroy(): Promise<void> {\n await this.terminator?.terminate()\n }\n}\n\nexport default OzoneService\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAGhC,OAAO,WAAW,MAAM,aAAa,CAAA;AACrC,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7B,OAAO,EAAuB,oBAAoB,EAAE,MAAM,iBAAiB,CA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ED,KAAK,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,UAAU,EAAE,SAAS,EAAE,CAAA;IACpC,CAAC;CACF;AAED,eAAe,YAAY,CAAA","sourcesContent":["import events from 'node:events'\nimport type http from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport compression from 'compression'\nimport cors from 'cors'\nimport express from 'express'\nimport { type HttpTerminator, createHttpTerminator } from 'http-terminator'\nimport * as prometheus from 'prom-client'\nimport { DAY, SECOND } from '@atproto/common'\nimport {\n type DidString,\n Procedure,\n Query,\n Subscription,\n walk,\n} from '@atproto/lex'\nimport { createServer, extractUrlNsid } from '@atproto/xrpc-server'\nimport API, { health, wellKnown } from './api/index.js'\nimport type { OzoneConfig, OzoneSecrets } from './config/index.js'\nimport { AppContext, type AppContextOptions } from './context.js'\nimport type { Member } from './db/schema/member.js'\nimport * as error from './error.js'\nimport * as lexicons from './lexicons/index.js'\nimport { tools } from './lexicons/index.js'\nimport { dbLogger, loggerMiddleware } from './logger.js'\n\nexport * from './config/index.js'\nexport { AppContext } from './context.js'\nexport { EventPusher, EventReverser, OzoneDaemon } from './daemon/index.js'\nexport { Database } from './db/index.js'\nexport { type ImageInvalidator } from './image-invalidator.js'\nexport { VideoInvalidator } from './video-invalidator.js'\nexport { httpLogger } from './logger.js'\n\nconst KNOWN_METHODS = new Set<string>(\n walk(lexicons)\n .filter(\n (s) =>\n s instanceof Procedure ||\n s instanceof Query ||\n s instanceof Subscription,\n )\n .map((s) => s.nsid),\n)\n\nexport class OzoneService {\n public ctx: AppContext\n public app: express.Application\n public server?: http.Server\n private terminator?: HttpTerminator\n private dbStatsInterval?: NodeJS.Timeout\n\n constructor(opts: { ctx: AppContext; app: express.Application }) {\n this.ctx = opts.ctx\n this.app = opts.app\n }\n\n static async create(\n cfg: OzoneConfig,\n secrets: OzoneSecrets,\n overrides?: Partial<AppContextOptions>,\n // Optional Prometheus registry. Its presence is the collection gate: when\n // omitted (dev-env, tests, self-hosted distros that don't opt in), no\n // metrics are collected and no per-request timing overhead is incurred.\n register?: prometheus.Registry,\n ): Promise<OzoneService> {\n const app = express()\n app.set('trust proxy', true)\n app.use(cors({ maxAge: DAY / SECOND }))\n app.use(loggerMiddleware)\n app.use(compression())\n\n const ctx = await AppContext.fromConfig(cfg, secrets, overrides)\n\n let server = createServer([], {\n validateResponse: false,\n payload: {\n jsonLimit: 100 * 1024, // 100kb\n textLimit: 100 * 1024, // 100kb\n blobLimit: 5 * 1024 * 1024, // 5mb\n },\n })\n\n server = API(server, ctx)\n\n if (register) {\n // Collect standard metrics on the nodejs runtime (GC, event loop, etc).\n prometheus.collectDefaultMetrics({ prefix: 'ozone_', register })\n\n // Per-XRPC-method request timing. Labeled by nsid (e.g.\n // tools.ozone.moderation.emitEvent) so every method is covered without\n // per-endpoint code. This middleware runs above the xrpc router, so\n // req.route is not yet populated; we derive the nsid from the URL instead.\n const xrpcRequestDuration = new prometheus.Histogram({\n name: 'ozone_xrpc_request_duration_seconds',\n help: 'XRPC request duration in seconds, by method',\n labelNames: ['nsid', 'method', 'code'],\n registers: [register],\n })\n\n app.use((req, res, next) => {\n const nsid = extractUrlNsid(req.originalUrl)\n // Only record xrpc methods; non-xrpc paths (health, robots, frontend)\n // are skipped to keep the metric's label cardinality bounded.\n if (!nsid) return next()\n // extractUrlNsid only validates path *shape*, not that the method\n // exists. A caller can hit /xrpc/<well-formed-but-bogus-nsid> (served a\n // 501), so labeling by the raw nsid lets external traffic mint unbounded\n // series and grow prom-client's memory without limit. Bucket anything\n // that isn't a registered query/procedure under a single `unknown` label.\n const end = xrpcRequestDuration.startTimer()\n res.on('finish', () => {\n end({\n nsid: KNOWN_METHODS.has(nsid) ? nsid : 'unknown',\n method: req.method,\n code: res.statusCode,\n })\n })\n next()\n })\n }\n\n app.use(health.createRouter(ctx))\n app.use(wellKnown.createRouter(ctx))\n app.use(server.router)\n app.use(error.handler)\n\n return new OzoneService({ ctx, app })\n }\n\n async seedInitialMembers() {\n const members: Array<{ role: Member['role']; did: DidString }> = []\n this.ctx.cfg.access.admins.forEach((did) =>\n members.push({\n role: tools.ozone.team.defs.RoleAdmin,\n did,\n }),\n )\n this.ctx.cfg.access.triage.forEach((did) =>\n members.push({\n role: tools.ozone.team.defs.RoleTriage,\n did,\n }),\n )\n this.ctx.cfg.access.moderators.forEach((did) =>\n members.push({\n role: tools.ozone.team.defs.RoleModerator,\n did,\n }),\n )\n\n for (const member of members) {\n const service = this.ctx.teamService(this.ctx.db)\n await service.upsert({\n ...member,\n lastUpdatedBy: this.ctx.cfg.service.did,\n })\n }\n }\n\n async start(): Promise<http.Server> {\n if (this.dbStatsInterval) {\n throw new Error(`${this.constructor.name} already started`)\n }\n\n // Any moderator that are configured via env var may not exist in the database\n // so we need to sync them from env var to the database\n await this.seedInitialMembers()\n\n this.dbStatsInterval = setInterval(() => {\n dbLogger.info(\n {\n idleCount: this.ctx.db.pool.idleCount,\n totalCount: this.ctx.db.pool.totalCount,\n waitingCount: this.ctx.db.pool.waitingCount,\n },\n 'db pool stats',\n )\n dbLogger.info(\n this.ctx.backgroundQueue.getStats(),\n 'background queue stats',\n )\n }, 10000)\n await this.ctx.sequencer.start()\n const server = this.app.listen(this.ctx.cfg.service.port)\n this.server = server\n server.keepAliveTimeout = 90000\n this.terminator = createHttpTerminator({ server })\n await events.once(server, 'listening')\n const { port } = server.address() as AddressInfo\n this.ctx.assignPort(port)\n return server\n }\n\n async destroy(): Promise<void> {\n clearInterval(this.dbStatsInterval)\n this.dbStatsInterval = undefined\n\n // @TODO Use a disposable stack when Node24 becomes the min supported version\n try {\n await this.terminator?.terminate()\n } finally {\n try {\n await this.ctx.backgroundQueue.destroy()\n } finally {\n try {\n await this.ctx.sequencer.destroy()\n } finally {\n await this.ctx.db.close()\n }\n }\n }\n }\n}\n\nexport type MetricsServiceOpts = {\n // Optional readiness probe. Should reject/throw when the service cannot serve\n // traffic (e.g. database unreachable). When omitted, /readyz behaves like\n // /livez (process-alive only).\n readinessCheck?: () => Promise<void>\n}\n\n// A separate, pull-based Prometheus metrics server. Kept on its own port and\n// HTTP server so private metrics and ops probes are never exposed on the public\n// ozone server. Only started by an entrypoint when metrics are explicitly\n// opted in. Also serves Kubernetes-style liveness (/livez) and readiness\n// (/readyz) probes.\nexport class MetricsService {\n private terminator?: HttpTerminator\n\n constructor(public app: express.Application) {}\n\n static create(\n register: prometheus.Registry,\n opts: MetricsServiceOpts = {},\n ): MetricsService {\n const app = express()\n\n app.get('/metrics', async (_req, res) => {\n // Express 4 does not catch rejections from async handlers, so an\n // unguarded throw here (e.g. a custom collector failing) would surface as\n // an unhandledRejection and crash the process. Metrics are a passive\n // side-channel and must never take down the service.\n try {\n const metrics = await register.metrics()\n res.set('Content-Type', register.contentType)\n res.end(metrics)\n } catch {\n res.status(500).end()\n }\n })\n\n // Liveness: is the process up and the event loop responsive? No external\n // dependencies, so a transient dependency outage never causes a pod restart.\n app.get('/livez', (_req, res) => {\n res.send({ status: 'ok' })\n })\n\n // Readiness: can the service handle traffic right now? Runs the optional\n // readiness check (e.g. a db ping); a failure pulls the pod from the load\n // balancer without restarting it.\n app.get('/readyz', async (_req, res) => {\n if (!opts.readinessCheck) {\n return res.send({ status: 'ok' })\n }\n try {\n await opts.readinessCheck()\n res.send({ status: 'ok' })\n } catch {\n res.status(503).send({ status: 'not ready' })\n }\n })\n\n return new MetricsService(app)\n }\n\n async start(port: number): Promise<http.Server> {\n const server = this.app.listen(port)\n server.keepAliveTimeout = 90000\n this.terminator = createHttpTerminator({ server })\n await events.once(server, 'listening')\n return server\n }\n\n async destroy(): Promise<void> {\n await this.terminator?.terminate()\n }\n}\n\nexport default OzoneService\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"authFullApp.defs.d.ts","sourceRoot":"","sources":["../../../../src/lexicons/app/bsky/authFullApp.defs.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,cAAc,CAAA;AAEhC,QAAA,MAAM,KAAK,yBAAyB,CAAA;AAEpC,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,OAAO,EAAE,KAAK,EAAE,CAAA;AAEhB,QAAA,MAAM,IAAI,mHAwIT,CAAA;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
1
+ {"version":3,"file":"authFullApp.defs.d.ts","sourceRoot":"","sources":["../../../../src/lexicons/app/bsky/authFullApp.defs.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,cAAc,CAAA;AAEhC,QAAA,MAAM,KAAK,yBAAyB,CAAA;AAEpC,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,OAAO,EAAE,KAAK,EAAE,CAAA;AAEhB,QAAA,MAAM,IAAI,mHAkJT,CAAA;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -25,6 +25,10 @@ const main = /*#__PURE__*/ l.permissionSet($nsid, [
25
25
  'app.bsky.contact.removeData',
26
26
  'app.bsky.contact.startPhoneVerification',
27
27
  'app.bsky.contact.verifyPhone',
28
+ 'app.bsky.draft.createDraft',
29
+ 'app.bsky.draft.deleteDraft',
30
+ 'app.bsky.draft.getDrafts',
31
+ 'app.bsky.draft.updateDraft',
28
32
  'app.bsky.feed.describeFeedGenerator',
29
33
  'app.bsky.feed.getActorFeeds',
30
34
  'app.bsky.feed.getActorLikes',
@@ -87,9 +91,13 @@ const main = /*#__PURE__*/ l.permissionSet($nsid, [
87
91
  'app.bsky.unspecced.getPostThreadV2',
88
92
  'app.bsky.unspecced.getSuggestedFeeds',
89
93
  'app.bsky.unspecced.getSuggestedFeedsSkeleton',
94
+ 'app.bsky.unspecced.getSuggestedOnboardingUsers',
90
95
  'app.bsky.unspecced.getSuggestedStarterPacks',
91
96
  'app.bsky.unspecced.getSuggestedStarterPacksSkeleton',
92
97
  'app.bsky.unspecced.getSuggestedUsers',
98
+ 'app.bsky.unspecced.getSuggestedUsersForDiscover',
99
+ 'app.bsky.unspecced.getSuggestedUsersForExplore',
100
+ 'app.bsky.unspecced.getSuggestedUsersForSeeMore',
93
101
  'app.bsky.unspecced.getSuggestedUsersSkeleton',
94
102
  'app.bsky.unspecced.getSuggestionsSkeleton',
95
103
  'app.bsky.unspecced.getTaggedSuggestions',
@@ -113,6 +121,7 @@ const main = /*#__PURE__*/ l.permissionSet($nsid, [
113
121
  /*#__PURE__*/ l.permission('repo', {
114
122
  action: ['create', 'update', 'delete'],
115
123
  collection: [
124
+ 'app.bsky.actor.contentVisibilityDeclaration',
116
125
  'app.bsky.actor.profile',
117
126
  'app.bsky.actor.status',
118
127
  'app.bsky.feed.like',
@@ -127,6 +136,7 @@ const main = /*#__PURE__*/ l.permissionSet($nsid, [
127
136
  'app.bsky.graph.listitem',
128
137
  'app.bsky.graph.referencelistoptout',
129
138
  'app.bsky.graph.starterpack',
139
+ 'app.bsky.graph.verification',
130
140
  'app.bsky.notification.declaration',
131
141
  ],
132
142
  }),