@acepaste/ingress 0.9.6 → 0.9.21

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 (74) hide show
  1. package/dist/src/adapters.d.ts +9 -0
  2. package/dist/src/adapters.js +76 -6
  3. package/dist/src/agent-hooks.d.ts +112 -0
  4. package/dist/src/agent-hooks.js +533 -0
  5. package/dist/src/approvers.d.ts +16 -0
  6. package/dist/src/approvers.js +50 -0
  7. package/dist/src/audio.d.ts +70 -0
  8. package/dist/src/audio.js +224 -0
  9. package/dist/src/audit-changes.d.ts +46 -0
  10. package/dist/src/audit-changes.js +110 -0
  11. package/dist/src/audit-local.d.ts +57 -0
  12. package/dist/src/audit-local.js +231 -0
  13. package/dist/src/audit-parsers.d.ts +1 -1
  14. package/dist/src/audit.js +48 -0
  15. package/dist/src/broker.d.ts +92 -1
  16. package/dist/src/broker.js +222 -3
  17. package/dist/src/calendar.d.ts +36 -0
  18. package/dist/src/calendar.js +227 -0
  19. package/dist/src/captions.d.ts +44 -0
  20. package/dist/src/captions.js +209 -0
  21. package/dist/src/changes.d.ts +105 -0
  22. package/dist/src/changes.js +174 -0
  23. package/dist/src/character.js +15 -1
  24. package/dist/src/classifier-model.d.ts +53 -0
  25. package/dist/src/classifier-model.js +3 -0
  26. package/dist/src/classifier.d.ts +41 -0
  27. package/dist/src/classifier.js +213 -0
  28. package/dist/src/cli.js +501 -1
  29. package/dist/src/egress.d.ts +71 -0
  30. package/dist/src/egress.js +242 -0
  31. package/dist/src/email.d.ts +42 -0
  32. package/dist/src/email.js +424 -0
  33. package/dist/src/engine.d.ts +35 -12
  34. package/dist/src/engine.js +88 -37
  35. package/dist/src/image-meta.d.ts +33 -0
  36. package/dist/src/image-meta.js +433 -0
  37. package/dist/src/image.d.ts +104 -0
  38. package/dist/src/image.js +347 -0
  39. package/dist/src/index.d.ts +50 -5
  40. package/dist/src/index.js +28 -3
  41. package/dist/src/localguard.d.ts +33 -0
  42. package/dist/src/localguard.js +61 -0
  43. package/dist/src/meaning.d.ts +2 -0
  44. package/dist/src/meaning.js +77 -22
  45. package/dist/src/messages.d.ts +79 -0
  46. package/dist/src/messages.js +431 -0
  47. package/dist/src/nearby.d.ts +52 -0
  48. package/dist/src/nearby.js +186 -0
  49. package/dist/src/netpolicy.js +50 -19
  50. package/dist/src/provenance.d.ts +56 -0
  51. package/dist/src/provenance.js +114 -0
  52. package/dist/src/qr.d.ts +25 -0
  53. package/dist/src/qr.js +113 -0
  54. package/dist/src/safeguards.d.ts +61 -0
  55. package/dist/src/safeguards.js +199 -0
  56. package/dist/src/served.d.ts +20 -0
  57. package/dist/src/served.js +53 -0
  58. package/dist/src/shell-commands.d.ts +39 -0
  59. package/dist/src/shell-commands.js +291 -0
  60. package/dist/src/shortcuts.d.ts +45 -0
  61. package/dist/src/shortcuts.js +220 -0
  62. package/dist/src/stream.d.ts +88 -0
  63. package/dist/src/stream.js +119 -0
  64. package/dist/src/terminal.d.ts +29 -0
  65. package/dist/src/terminal.js +313 -0
  66. package/dist/src/tooldefs.d.ts +84 -0
  67. package/dist/src/tooldefs.js +122 -0
  68. package/dist/src/types.d.ts +50 -6
  69. package/dist/src/types.js +15 -2
  70. package/dist/src/visibility.d.ts +23 -3
  71. package/dist/src/visibility.js +285 -78
  72. package/native/ingress-presence.swift +48 -0
  73. package/native/ingress-vision.swift +417 -0
  74. package/package.json +3 -1
@@ -0,0 +1,431 @@
1
+ /**
2
+ * Messages and notifications: chat, text messages, and the banners an operating system shows.
3
+ *
4
+ * These are the channels where anyone can write to you. In a group chat or a shared channel one participant's
5
+ * message is, to an assistant reading the conversation, as present as everyone else's. A text message comes
6
+ * from a number. A notification says who it is from, and the claim costs nothing to make.
7
+ *
8
+ * The adapters turn each message into segments and check what the channel's own structure gives away:
9
+ *
10
+ * what the app shows vs. what an API consumer reads Slack renders `blocks` and keeps `text` for
11
+ * notifications; Teams has a `summary` beside the body. Words in the unseen one are concealed text.
12
+ * link previews written by the linked site, not the sender; a preview's plain-text fallback is
13
+ * shown nowhere
14
+ * sender names a display name is free text: "System", "IT Support", "[ADMIN]" from a bot, a
15
+ * webhook or an outsider is a costume
16
+ * scam shape an unknown sender, a link that hides where it goes, and pressure or a request for
17
+ * a code, a password or a payment
18
+ * verification codes noted: a code in a message is for the person. The action broker refuses to let
19
+ * one be sent to a destination that came from content (see egress.ts)
20
+ * notifications an alarm in the system's or a brand's voice, delivered by a web browser
21
+ *
22
+ * Trust is per scan. A caller that knows a conversation is with a known contact says so with `source.trust`;
23
+ * a group chat or channel is an open channel (5), an unknown number a stranger (4).
24
+ *
25
+ * Not inspected, and said so: voice messages, stickers, files. Pictures go through scanImage when the caller
26
+ * has their bytes.
27
+ */
28
+ import { decodeEntities } from "./adapters.js";
29
+ import { analyzeHtml } from "./visibility.js";
30
+ import { passagesOnlyIn } from "./served.js";
31
+ import { oneTimeCodes } from "./egress.js";
32
+ const str = (v) => (typeof v === "string" ? v : "");
33
+ const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined);
34
+ const arr = (v) => (Array.isArray(v) ? v : []);
35
+ const MAX_ITEMS = 500;
36
+ /** text of Slack's block kit: what the app renders when blocks are present */
37
+ function blockText(blocks, out = [], depth = 0) {
38
+ if (depth > 8)
39
+ return out;
40
+ for (const b of arr(blocks)) {
41
+ const o = obj(b);
42
+ if (!o)
43
+ continue;
44
+ const t = o.text;
45
+ if (typeof t === "string")
46
+ out.push(t);
47
+ else if (obj(t) && typeof obj(t).text === "string")
48
+ out.push(obj(t).text);
49
+ for (const k of ["fields", "elements", "accessory", "title", "label", "description", "placeholder", "alt_text"]) {
50
+ const v = o[k];
51
+ if (typeof v === "string")
52
+ out.push(v);
53
+ else if (Array.isArray(v))
54
+ blockText(v, out, depth + 1);
55
+ else if (obj(v))
56
+ blockText([v], out, depth + 1);
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+ function one(m) {
62
+ // Telegram wraps each update
63
+ const top = obj(m);
64
+ if (!top)
65
+ return undefined;
66
+ const o = obj(top.message) && (typeof top.update_id === "number" || !("text" in top)) ? obj(top.message) : top;
67
+ const msg = { shown: "", html: false, unseen: [], sender: "", automated: false, outside: false, self: false, service: "", previews: [], files: [], unread: [] };
68
+ const author = obj(o.author), from = obj(o.from), profile = obj(o.user_profile), body = obj(o.body);
69
+ // sender, as the channel names them
70
+ msg.sender = str(profile?.display_name) || str(profile?.real_name) || str(o.username) || str(author?.global_name) || str(author?.username) || str(author?.name)
71
+ || str(obj(from?.user)?.displayName) || str(obj(from?.application)?.displayName) || [str(from?.first_name), str(from?.last_name)].filter(Boolean).join(" ") || str(from?.username) || str(from?.name) || str(from?.displayName)
72
+ || str(o.sender_name) || str(o.senderName) || str(o.sender) || str(o.from) || str(o.handle) || str(o.author) || str(o.user_name) || str(o.user);
73
+ msg.automated = !!(o.bot_id || o.webhook_id || o.app_id || author?.bot || from?.is_bot || obj(from?.application) || o.subtype === "bot_message" || o.via_bot || o.is_bot);
74
+ msg.outside = !!(o.is_ext_shared || o.forward_from || o.forward_origin || o.forward_from_chat || o.forwarded || o.is_forwarded || o.external || (typeof o.user_team === "string" && typeof o.team === "string" && o.user_team !== o.team));
75
+ msg.self = o.is_from_me === true || o.is_from_me === 1 || o.fromMe === true || o.outgoing === true;
76
+ msg.service = str(o.service) || (typeof o.is_from_me !== "undefined" ? "SMS" : "") || str(o.channel_type) || str(o.platform);
77
+ // the words
78
+ const blocks = blockText(o.blocks);
79
+ const text = str(o.text) || str(obj(o.text)?.body) || str(o.content) || str(o.caption) || (typeof o.body === "string" ? o.body : "") || (typeof o.message === "string" ? o.message : "") || str(o.snippet);
80
+ if (body && typeof body.content === "string") {
81
+ msg.shown = body.content;
82
+ msg.html = /html/i.test(str(body.contentType));
83
+ }
84
+ else if (typeof o.formatted_body === "string" && /html/i.test(str(o.format))) {
85
+ msg.shown = o.formatted_body;
86
+ msg.html = true;
87
+ if (text)
88
+ msg.unseen.push({ field: "body", text });
89
+ }
90
+ else if (blocks.length) {
91
+ msg.shown = blocks.join("\n");
92
+ if (text)
93
+ msg.unseen.push({ field: "text", text });
94
+ }
95
+ else
96
+ msg.shown = text;
97
+ for (const k of ["summary", "notification_text", "fallback", "preview_text"])
98
+ if (typeof o[k] === "string" && o[k])
99
+ msg.unseen.push({ field: k, text: o[k] });
100
+ if (typeof o.subject === "string" && o.subject)
101
+ msg.shown = `${o.subject}\n${msg.shown}`;
102
+ // previews, embeds and cards: written by whoever controls the link
103
+ for (const a of [...arr(o.attachments), ...arr(o.embeds), ...arr(o.link_previews)].slice(0, 20)) {
104
+ const p = obj(a);
105
+ if (!p)
106
+ continue;
107
+ const fields = arr(p.fields).map((f) => `${str(obj(f)?.title) || str(obj(f)?.name)} ${str(obj(f)?.value)}`.trim());
108
+ const shown = [str(p.pretext), str(obj(p.author)?.name) || str(p.author_name), str(p.title), str(p.text) || str(p.description), ...fields, str(obj(p.footer)?.text) || (typeof p.footer === "string" ? p.footer : ""), ...blockText(p.blocks)].filter(Boolean).join("\n");
109
+ const url = str(p.title_link) || str(p.url) || str(p.original_url) || str(p.from_url);
110
+ if (typeof p.content === "string" && p.content.length > 2)
111
+ msg.unread.push("a card");
112
+ if (shown || p.fallback)
113
+ msg.previews.push({ shown, fallback: str(p.fallback), url });
114
+ if (str(p.filename) || (str(p.name) && (p.url || p.contentUrl)))
115
+ msg.files.push(str(p.filename) || str(p.name));
116
+ }
117
+ for (const f of arr(o.files).slice(0, 20)) {
118
+ const n = str(obj(f)?.title) || str(obj(f)?.name);
119
+ if (n)
120
+ msg.files.push(n);
121
+ }
122
+ for (const k of ["voice", "audio", "video", "sticker", "animation", "document", "photo"])
123
+ if (o[k])
124
+ msg.unread.push(k === "photo" ? "a picture" : `a ${k} part`);
125
+ if (typeof o.type === "string" && /^(audio|voice|ptt|video|sticker|image|document)$/.test(o.type))
126
+ msg.unread.push(`a ${o.type} part`);
127
+ if (!msg.shown && !msg.unseen.length && !msg.previews.length && !msg.files.length && !msg.unread.length)
128
+ return undefined;
129
+ return msg;
130
+ }
131
+ const LISTS = ["messages", "value", "items", "result", "results", "data", "history", "chats", "events"];
132
+ /** Messages in a chat API's JSON, in order. Lenient: used when the caller has said this is a conversation. */
133
+ export function parseMessages(doc) {
134
+ const d = obj(doc);
135
+ const list = Array.isArray(doc) ? doc : LISTS.map((k) => d?.[k]).find(Array.isArray) ?? (d ? [d] : []);
136
+ return list.slice(0, MAX_ITEMS).map(one).filter((m) => !!m);
137
+ }
138
+ /** Is this JSON plainly a chat export or a chat API's reply? Strict: decides how unlabelled JSON is read. */
139
+ export function looksLikeMessagesJson(doc) {
140
+ const is = (m) => {
141
+ const t = obj(m);
142
+ if (!t)
143
+ return false;
144
+ const o = obj(t.message) && typeof t.update_id === "number" ? obj(t.message) : t;
145
+ if ("subject" in o && ("from" in o || "sender" in o))
146
+ return false; // mail
147
+ if (typeof o.ts === "string" && /^\d{9,}\.\d+$/.test(o.ts) && ("text" in o || "blocks" in o) && ("user" in o || "bot_id" in o || "username" in o))
148
+ return true; // Slack
149
+ if (obj(o.author) && typeof obj(o.author).username === "string" && "content" in o && ("channel_id" in o || "timestamp" in o))
150
+ return true; // Discord
151
+ if (typeof o.message_id === "number" && obj(o.chat) && (obj(o.from) || "sender_chat" in o))
152
+ return true; // Telegram
153
+ if (obj(o.body) && typeof obj(o.body).content === "string" && obj(o.from) && ("createdDateTime" in o || "messageType" in o))
154
+ return true; // Teams
155
+ if ("is_from_me" in o && ("text" in o || "body" in o))
156
+ return true; // Messages / SMS exports
157
+ if (typeof o.type === "string" && typeof o.from === "string" && obj(o.text) && typeof obj(o.text).body === "string")
158
+ return true; // WhatsApp Cloud API
159
+ if (typeof o.sender === "string" && typeof o.event_id === "string" && obj(o.content))
160
+ return false; // Matrix events: nested content, read as JSON
161
+ return false;
162
+ };
163
+ const d = obj(doc);
164
+ const list = Array.isArray(doc) ? doc : LISTS.map((k) => d?.[k]).find(Array.isArray);
165
+ if (list)
166
+ return list.length > 0 && list.slice(0, 50).every(is);
167
+ return is(doc);
168
+ }
169
+ // ---------- checks ----------
170
+ const AUTHORITY_NAME = /^\W*(?:system|sys ?admin|admin(?:istrator)?|root|security(?: team| alert)?|it(?: support| help ?desk| department)?|help ?desk|tech(?:nical)? support|support(?: team)?|moderator|mod team|compliance|human resources|hr(?: team)?|payroll|legal|the (?:ceo|cfo|cto|boss|management)|ceo|slack ?bot|workspace admin|claude|chatgpt|gemini|copilot|assistant|ai assistant|anthropic|openai|microsoft(?: support| security)?|apple(?: support| security)?|google(?: support| security)?|your bank|bank security|fraud (?:team|department|prevention))\W*$/i;
171
+ const ROLE_IN_NAME = /\[(?:system|admin|assistant|developer|instruction)[^\]]{0,20}\]|^\s*(?:system|assistant|developer)\s*:|<\|[^|]{1,24}\|>|#{3,}/i;
172
+ const PRESSURE = /\b(?:urgent(?:ly)?|immediately|right away|within \d+ ?(?:h|hrs?|hours?|min(?:ute)?s?)|final (?:notice|warning|reminder)|last (?:chance|warning)|act now|expires? (?:today|soon|in)|suspend(?:ed)?|locked|restricted|unusual (?:activity|sign-?in)|unauthori[sz]ed|overdue|unpaid|past due|penalt(?:y|ies)|legal action|arrest|failed delivery|could not be delivered|held at|customs fee|redelivery|toll|refund (?:is )?(?:pending|available)|you(?:'ve| have) won|prize|claim (?:your|it)|verify (?:your|now)|confirm (?:your|now)|update (?:your )?(?:payment|billing|details))\b/i;
173
+ const ASKS = /\b(?:(?:send|share|give|tell|text|reply with|forward|enter|provide|confirm)\b[^.\n]{0,40}\b(?:code|otp|pin|password|passcode|card (?:number|details)|cvv|ssn|social security|bank details|gift cards?|seed phrase|recovery phrase)|gift cards?|wire (?:the )?(?:money|funds|transfer)|bitcoin|crypto wallet|western union|zelle|cash ?app)\b/i;
174
+ const CLAIMS = /\b(?:(?:your |the )?bank|fraud (?:team|department|prevention)|security (?:team|department)|(?:customer|technical|tech) (?:service|support|care)|support team|help ?desk|your (?:provider|carrier|network)|tax office|revenue service|police|court|amazon|paypal|apple|microsoft|google|netflix|irs|hmrc|usps|fedex|dhl|ups)\b/i;
175
+ const LINK = /\bhttps?:\/\/[^\s<>"')\]]+|\b(?:[a-z0-9-]+\.)+(?:com|net|org|io|co|me|info|biz|xyz|top|site|online|link|click|ly|gl|gd|cc|to|app|page|shop|live|icu|vip|cfd|sbs)(?:\/[^\s<>"')\]]*)?/gi;
176
+ const SHORTENER = /^(?:bit\.ly|t\.co|tinyurl\.com|goo\.gl|is\.gd|ow\.ly|buff\.ly|rebrand\.ly|cutt\.ly|rb\.gy|t\.ly|shorturl\.at|s\.id|tiny\.cc|lnkd\.in|v\.gd|qr\.ae|shorte\.st|bl\.ink|x\.co)$/i;
177
+ /** How a link hides where it goes, or undefined when it does not. */
178
+ export function linkTrick(link) {
179
+ let u;
180
+ try {
181
+ u = new URL(/^https?:\/\//i.test(link) ? link : `https://${link}`);
182
+ }
183
+ catch {
184
+ return "an address that does not parse";
185
+ }
186
+ const h = u.hostname.toLowerCase();
187
+ if (u.username || u.password)
188
+ return "a name before the @ that is not the destination";
189
+ if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(h))
190
+ return "a bare network address";
191
+ if (/^xn--|\.xn--/.test(h))
192
+ return "an international name that may imitate another";
193
+ if (SHORTENER.test(h))
194
+ return "a shortener";
195
+ if (/\.(?:top|xyz|icu|vip|cfd|sbs|click|link|live|shop|online|site)$/.test(h) && /(?:secure|verify|login|account|update|support|billing|pay|refund|parcel|post|track|bank|apple|paypal|amazon|microsoft|netflix|usps|fedex|dhl|ups|gov|irs|tax)/.test(h))
196
+ return "a brand or a service name on an unrelated domain";
197
+ if (h.split(".").length >= 5)
198
+ return "a long chain of subdomains";
199
+ return undefined;
200
+ }
201
+ /** plain text with its entities decoded, noting any that decode to characters nobody sees */
202
+ function plain(text, where, findings) {
203
+ const dec = decodeEntities(text);
204
+ if (dec.suspicious > 0)
205
+ findings.push({ pass: "character", kind: "unicode.entity_smuggling", confidence: Math.min(0.95, 0.6 + dec.suspicious * 0.05), severity: 0.7, message: `${dec.suspicious} HTML entities decoding to invisible or format characters`, excerpt: dec.sample, location: where, action: "neutralized" });
206
+ return dec.text;
207
+ }
208
+ const senderIsNumber = (s) => /^\+?[\d\s().-]{4,}$/.test(s) || /^\d{3,6}$/.test(s.trim());
209
+ export function adaptMessages(raw) {
210
+ const segments = [];
211
+ const findings = [];
212
+ let doc;
213
+ try {
214
+ doc = JSON.parse(raw);
215
+ }
216
+ catch {
217
+ doc = undefined;
218
+ }
219
+ const add = (f) => findings.push({ pass: "channel", action: "none", ...f });
220
+ // not JSON: a transcript or a single message as plain text
221
+ if (doc === undefined || (typeof doc !== "object")) {
222
+ const text = plain(typeof doc === "string" ? doc : raw, "message/text", findings);
223
+ segments.push({ text, visibility: "visible", path: "message/text" });
224
+ scamShape(text, "", "", "message", add);
225
+ for (const c of oneTimeCodes(text).slice(0, 1))
226
+ add({ kind: "message.verification_code", confidence: 0.02, severity: 0.1, message: `a verification code (ending ${c.slice(-2)}) in this message: a code is for the person` });
227
+ return { segments, findings };
228
+ }
229
+ const msgs = parseMessages(doc);
230
+ const unread = new Map();
231
+ const codes = new Set();
232
+ msgs.forEach((m, i) => {
233
+ const path = `message[${i}]`;
234
+ if (m.sender)
235
+ segments.push({ text: m.sender, visibility: "visible", path: `${path}/sender` });
236
+ let shownText = m.shown;
237
+ if (m.html) {
238
+ const v = analyzeHtml(m.shown);
239
+ for (const s of v.segments)
240
+ segments.push({ ...s, path: `${path}/html/${s.path}` });
241
+ findings.push(...v.findings.map((f) => ({ ...f, location: `${path}/html${f.location ? `/${f.location}` : ""}` })));
242
+ shownText = v.segments.map((s) => s.text).join(" ");
243
+ }
244
+ else if (m.shown.trim()) {
245
+ // chat APIs escape a few characters as entities; decode them here, and notice ones that decode to nothing visible
246
+ shownText = plain(m.shown, `${path}/text`, findings);
247
+ segments.push({ text: shownText, visibility: "visible", path: `${path}/text` });
248
+ }
249
+ // words the app does not show
250
+ const seen = [shownText, ...m.previews.map((p) => p.shown)].join(" ");
251
+ for (const u of m.unseen) {
252
+ const only = passagesOnlyIn(u.text, seen);
253
+ if (!only.length)
254
+ continue;
255
+ add({ kind: "message.text_divergence", confidence: 0.45, severity: 0.7, message: `the "${u.field}" field says ${only.length} thing(s) the message as shown does not: an app displays one, a program reading the conversation gets both`, excerpt: only[0].slice(0, 160), location: `${path}/${u.field}`, inHidden: true });
256
+ only.forEach((t, j) => segments.push({ text: t, visibility: "concealed", path: `${path}/${u.field}~unseen[${j}]` }));
257
+ }
258
+ m.previews.forEach((p, j) => {
259
+ if (p.shown.trim())
260
+ segments.push({ text: p.shown, visibility: "visible", path: `${path}/preview[${j}]` });
261
+ const only = p.fallback ? passagesOnlyIn(p.fallback, `${p.shown} ${shownText}`) : [];
262
+ only.forEach((t, k) => segments.push({ text: t, visibility: "concealed", path: `${path}/preview[${j}]/fallback[${k}]` }));
263
+ if (only.length)
264
+ add({ kind: "message.text_divergence", confidence: 0.4, severity: 0.65, message: "a link preview's plain-text fallback says something the preview as shown does not", excerpt: only[0].slice(0, 160), location: `${path}/preview[${j}]`, inHidden: true });
265
+ });
266
+ if (m.files.length)
267
+ segments.push({ text: m.files.join("\n"), visibility: "visible", path: `${path}/files` });
268
+ for (const u of m.unread)
269
+ unread.set(u, (unread.get(u) ?? 0) + 1);
270
+ // who it says it is from
271
+ if (m.sender && !m.self) {
272
+ if (ROLE_IN_NAME.test(m.sender))
273
+ add({ kind: "message.sender_impersonation", confidence: 0.5, severity: 0.7, message: `a sender's display name is shaped like a system or role marker ("${m.sender.slice(0, 40)}")`, location: `${path}/sender` });
274
+ else if (AUTHORITY_NAME.test(m.sender) && (m.automated || m.outside))
275
+ add({ kind: "message.sender_impersonation", confidence: 0.4, severity: 0.6, message: `"${m.sender.slice(0, 40)}" is a display name chosen by ${m.automated ? "a bot or webhook" : "someone outside the workspace"}: a name is not an identity`, location: `${path}/sender` });
276
+ }
277
+ if (!m.self)
278
+ scamShape([shownText, ...m.previews.map((p) => p.shown)].join("\n"), m.sender, m.service, path, add);
279
+ for (const c of oneTimeCodes(shownText))
280
+ codes.add(c);
281
+ });
282
+ if (codes.size)
283
+ add({ kind: "message.verification_code", confidence: 0.02, severity: 0.1, message: `${codes.size} verification code(s) in these messages: a code is for the person. An action that carries one to a destination that came from content is refused by the action broker` });
284
+ if (unread.size)
285
+ add({ kind: "message.uninspected_part", confidence: 0.02, severity: 0.1, message: `not inspected: ${[...unread].map(([k, n]) => `${n} × ${k}`).join(", ")}` });
286
+ return { segments, findings };
287
+ }
288
+ /** An unknown sender, a link that hides where it goes, and pressure or a request for a secret or money. */
289
+ function scamShape(text, sender, service, path, add) {
290
+ if (text.length < 20)
291
+ return;
292
+ const links = [...text.matchAll(LINK)].map((m) => m[0]).slice(0, 10);
293
+ const tricks = links.map(linkTrick).filter((t) => !!t);
294
+ const pressure = PRESSURE.test(text), asks = ASKS.test(text);
295
+ const stranger = senderIsNumber(sender) || /sms|mms|rcs/i.test(service) || /^[^@\s]+@[^@\s]+$/.test(sender);
296
+ // a hidden destination with pressure is the shape, whoever sent it; a plain link needs both pressure and a stranger
297
+ const why = [];
298
+ if (tricks.length)
299
+ why.push(`a link that is ${tricks[0]}`);
300
+ if (pressure)
301
+ why.push("pressure to act now");
302
+ if (asks)
303
+ why.push("a request for a code, a password or a payment");
304
+ // A scam text is short: it has one job. Long messages mention deadlines, links and payments all the time
305
+ // (ordinary business mail read as if it were a text from a stranger tripped this 236 times in 3,000 before
306
+ // the length limits).
307
+ const words = text.trim().split(/\s+/).length;
308
+ const strong = words <= 120 && ((tricks.length > 0 && (pressure || asks)) || (asks && pressure && links.length > 0));
309
+ // "can you send me the door code again?" is how friends text; a stranger asking for a code in an institution's
310
+ // name, or with a deadline, is the scam
311
+ const claims = CLAIMS.test(text);
312
+ if (claims && asks)
313
+ why.push("in the name of an institution");
314
+ const medium = !strong && words <= 60 && stranger && ((links.length > 0 && pressure) || (asks && (pressure || claims)));
315
+ if (!strong && !medium)
316
+ return;
317
+ add({ kind: "message.scam_shape", confidence: strong ? 0.5 : 0.35, severity: 0.65, message: `shaped like a scam message${stranger ? " from an unknown sender" : ""}: ${why.join(", ")}`, location: `${path}/text` });
318
+ }
319
+ const APP_KEYS = ["app", "appName", "app_name", "application", "packageName", "package", "bundleId", "bundle_id", "bundleIdentifier", "source"];
320
+ function oneNote(n) {
321
+ const o = obj(n);
322
+ if (!o)
323
+ return undefined;
324
+ const extras = obj(o.extras) ?? {};
325
+ const note = {
326
+ app: APP_KEYS.map((k) => str(o[k])).find(Boolean) ?? "",
327
+ origin: str(o.origin) || (/^https?:\/\//.test(str(o.url)) ? str(o.url) : "") || str(o.scope),
328
+ title: str(o.title) || str(extras["android.title"]) || str(o.heading),
329
+ subtitle: str(o.subtitle) || str(o.subText) || str(extras["android.subText"]),
330
+ body: str(o.body) || str(o.bigText) || str(extras["android.bigText"]) || str(o.text) || str(extras["android.text"]) || str(o.message) || str(o.content),
331
+ sender: str(o.sender) || str(o.from) || str(extras["android.conversationTitle"]),
332
+ actions: arr(o.actions).map((a) => (typeof a === "string" ? a : str(obj(a)?.title) || str(obj(a)?.label) || str(obj(a)?.action))).filter(Boolean).slice(0, 10),
333
+ payload: [],
334
+ };
335
+ // fields a banner does not show: the ticker line, and whatever the sender attached for the app
336
+ if (str(o.tickerText))
337
+ note.payload.push({ field: "tickerText", text: str(o.tickerText) });
338
+ for (const k of ["data", "userInfo", "payload", "custom"]) {
339
+ const walk = (v, p, depth) => {
340
+ if (depth > 4 || note.payload.length > 40)
341
+ return;
342
+ if (typeof v === "string") {
343
+ if (v.length >= 12 && /\s/.test(v))
344
+ note.payload.push({ field: p, text: v });
345
+ }
346
+ else if (Array.isArray(v))
347
+ v.slice(0, 20).forEach((x, i) => walk(x, `${p}[${i}]`, depth + 1));
348
+ else if (obj(v))
349
+ for (const [kk, x] of Object.entries(v).slice(0, 40))
350
+ walk(x, `${p}.${kk}`, depth + 1);
351
+ };
352
+ walk(o[k], k, 0);
353
+ }
354
+ return note.title || note.body ? note : undefined;
355
+ }
356
+ export function parseNotifications(doc) {
357
+ const d = obj(doc);
358
+ const list = Array.isArray(doc) ? doc : ["notifications", "items", "value", "results"].map((k) => d?.[k]).find(Array.isArray) ?? (d ? [d] : []);
359
+ return list.slice(0, MAX_ITEMS).map(oneNote).filter((n) => !!n);
360
+ }
361
+ export function looksLikeNotificationJson(doc) {
362
+ const is = (n) => {
363
+ const o = obj(n);
364
+ if (!o || "subject" in o)
365
+ return false;
366
+ const hasApp = APP_KEYS.slice(0, 9).some((k) => typeof o[k] === "string") || obj(o.extras) !== undefined || (typeof o.origin === "string" && "tag" in o);
367
+ return hasApp && (typeof o.title === "string" || obj(o.extras) !== undefined) && ("body" in o || "text" in o || "bigText" in o || "subtitle" in o || obj(o.extras) !== undefined);
368
+ };
369
+ const d = obj(doc);
370
+ const list = Array.isArray(doc) ? doc : ["notifications", "items"].map((k) => d?.[k]).find(Array.isArray);
371
+ if (list)
372
+ return list.length > 0 && list.slice(0, 50).every(is);
373
+ return is(doc);
374
+ }
375
+ const BROWSER = /\b(?:chrome|chromium|safari|firefox|edge|msedge|brave|opera|vivaldi|arc|duckduckgo|samsung internet|sbrowser)\b|^(?:com\.android\.chrome|com\.apple\.safari|org\.mozilla\.\w+|com\.microsoft\.(?:edge|emmx)|com\.brave\.\w+|com\.opera\.\w+)/i;
376
+ const SYSTEM_VOICE = /\b(?:virus(?:es)?|infected|malware|trojan|spyware|system (?:alert|warning|error|update|scan)|security (?:alert|warning|scan)|critical (?:alert|warning|error)|your (?:mac|pc|iphone|ipad|android|computer|device|phone|system|battery|storage|icloud|account) (?:is|has been|may be|was|will be)|(?:\d+|several|multiple) (?:threats?|virus(?:es)?|issues?) (?:found|detected)|scan now|clean now|protection (?:expired|has expired|disabled)|subscription (?:expired|has expired)|license (?:expired|has expired)|mcafee|norton|avast|kaspersky|windows defender|apple ?care|macos update)\b/i;
377
+ const BRANDS = ["apple", "icloud", "microsoft", "windows", "google", "gmail", "paypal", "amazon", "netflix", "facebook", "instagram", "whatsapp", "coinbase", "binance", "chase", "wells fargo", "bank of america", "citibank", "hsbc", "barclays", "usps", "fedex", "dhl", "ups", "irs", "hmrc"];
378
+ export function adaptNotifications(raw) {
379
+ const segments = [];
380
+ const findings = [];
381
+ const add = (f) => findings.push({ pass: "channel", action: "none", ...f });
382
+ let doc;
383
+ try {
384
+ doc = JSON.parse(raw);
385
+ }
386
+ catch {
387
+ doc = undefined;
388
+ }
389
+ if (doc === undefined || typeof doc !== "object") {
390
+ segments.push({ text: plain(typeof doc === "string" ? doc : raw, "notification/text", findings), visibility: "visible", path: "notification/text" });
391
+ return { segments, findings };
392
+ }
393
+ const codes = new Set();
394
+ parseNotifications(doc).forEach((n, i) => {
395
+ const path = `notification[${i}]`;
396
+ const shown = [n.title, n.subtitle, n.body].filter(Boolean).join("\n");
397
+ if (n.sender)
398
+ segments.push({ text: n.sender, visibility: "visible", path: `${path}/sender` });
399
+ if (shown)
400
+ segments.push({ text: shown, visibility: "visible", path: `${path}/text` });
401
+ if (n.actions.length)
402
+ segments.push({ text: n.actions.join("\n"), visibility: "visible", path: `${path}/actions` });
403
+ for (const p of n.payload)
404
+ for (const [j, t] of passagesOnlyIn(p.text, shown, 6).entries())
405
+ segments.push({ text: t, visibility: "concealed", path: `${path}/${p.field}[${j}]` });
406
+ // an alarm in the system's voice, or a brand's, delivered by a web browser: any site a person once allowed can send it
407
+ const viaWeb = !!n.origin || BROWSER.test(n.app);
408
+ let host = "";
409
+ try {
410
+ host = n.origin ? new URL(n.origin).hostname.toLowerCase() : "";
411
+ }
412
+ catch { /* no host */ }
413
+ if (viaWeb && SYSTEM_VOICE.test(shown)) {
414
+ add({ kind: "notification.source_mismatch", confidence: 0.55, severity: 0.65, message: `a notification speaking as the system or a security product was sent by a website${host ? ` (${host})` : ""} through the browser: the operating system does not announce itself that way`, location: `${path}/text` });
415
+ }
416
+ else if (viaWeb) {
417
+ const brand = BRANDS.find((b) => new RegExp(`\\b${b}\\b`, "i").test(`${n.title} ${n.sender}`));
418
+ if (brand && host && !host.replace(/[^a-z]/g, "").includes(brand.replace(/[^a-z]/g, "")) && (PRESSURE.test(shown) || ASKS.test(shown))) {
419
+ add({ kind: "notification.source_mismatch", confidence: 0.45, severity: 0.6, message: `a notification in the name of ${brand} was sent by ${host}, with pressure to act`, location: `${path}/text` });
420
+ }
421
+ }
422
+ if (ROLE_IN_NAME.test(n.sender) || ROLE_IN_NAME.test(n.title))
423
+ add({ kind: "message.sender_impersonation", confidence: 0.5, severity: 0.7, message: "a notification's title or sender is shaped like a system or role marker", location: `${path}/sender` });
424
+ scamShape(shown, n.sender, "", path, add);
425
+ for (const c of oneTimeCodes(shown))
426
+ codes.add(c);
427
+ });
428
+ if (codes.size)
429
+ add({ kind: "message.verification_code", confidence: 0.02, severity: 0.1, message: `${codes.size} verification code(s) in these notifications: a code is for the person, and the action broker refuses to let one be sent to a destination that came from content` });
430
+ return { segments, findings };
431
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Nearby: what devices around you say about themselves.
3
+ *
4
+ * A Bonjour service name, a Bluetooth device name, a printer's description, a beacon's link: each is a string
5
+ * chosen by whoever owns the device, broadcast to everyone in range, and shown in pickers and lists that an
6
+ * agent may read ("which printer should I use?", "what's on this network?"). Nobody vouches for any of it.
7
+ * It is the lowest-trust content there is (trust level 6), and it is read here as content, never as fact.
8
+ *
9
+ * Checks:
10
+ * instructions in a name or a record the ordinary rules and the classifier's short-text mode
11
+ * authority names "IT Managed Printer", "Apple Setup", "System Update Service"
12
+ * lookalikes a name one or two characters from a device you know, or the same
13
+ * name from a different address
14
+ * links a beacon's or a service's URL is listed, never opened; ones that hide
15
+ * their destination are flagged
16
+ * oversized fields a TXT record or a name far longer than a device needs
17
+ *
18
+ * Ingress cannot stop a broadcast. It gates what an agent reads of it.
19
+ */
20
+ import { type AdapterResult } from "./adapters.js";
21
+ export interface NearbyRecord {
22
+ type: "bonjour" | "bluetooth" | "printer" | "beacon" | "wifi" | "other";
23
+ name: string;
24
+ /** the service type or device class: "_ipp._tcp", "Keyboard" */
25
+ service?: string;
26
+ /** an address that identifies the device: host, MAC, UUID */
27
+ address?: string;
28
+ /** key and value pairs the device publishes (Bonjour TXT, printer make and location) */
29
+ fields?: Record<string, string>;
30
+ url?: string;
31
+ /** paired, connected or added by the person: still its own words, but a device they chose */
32
+ known?: boolean;
33
+ }
34
+ export interface NearbyHints {
35
+ knownDevices?: Array<{
36
+ name: string;
37
+ address?: string;
38
+ }>;
39
+ }
40
+ export declare function looksLikeNearbyJson(doc: unknown): boolean;
41
+ export declare function parseNearby(doc: unknown): NearbyRecord[];
42
+ /** `dns-sd -B <type>` lines: "Timestamp A/R Flags if Domain Service-Type Instance-Name" */
43
+ export declare function parseDnsSdBrowse(text: string): NearbyRecord[];
44
+ /** `system_profiler SPBluetoothDataType -json` */
45
+ export declare function parseBluetoothProfile(json: string): NearbyRecord[];
46
+ /** `lpstat -l -p` blocks: "printer NAME ..." followed by indented "Description:", "Location:" lines */
47
+ export declare function parseLpstatPrinters(text: string): NearbyRecord[];
48
+ /** What this Mac currently lists: Bonjour services, Bluetooth devices, printers. Read-only; nothing is joined, paired or contacted. */
49
+ export declare function collectNearby(opts?: {
50
+ seconds?: number;
51
+ }): Promise<NearbyRecord[]>;
52
+ export declare function adaptNearby(raw: string, hints?: NearbyHints): AdapterResult;