@flowspec-qa/runner-core 0.3.0 → 0.4.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.
- package/dist/api-client.d.ts +87 -10
- package/dist/api-client.d.ts.map +1 -1
- package/dist/api-client.js +108 -7
- package/dist/api-client.js.map +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +4 -3
- package/dist/auth.js.map +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +4 -1
- package/dist/config.js.map +1 -1
- package/dist/discovery-report.d.ts.map +1 -1
- package/dist/discovery-report.js +669 -49
- package/dist/discovery-report.js.map +1 -1
- package/dist/discovery.d.ts +99 -5
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +1552 -263
- package/dist/discovery.js.map +1 -1
- package/dist/evidence-corpus.d.ts +338 -0
- package/dist/evidence-corpus.d.ts.map +1 -0
- package/dist/evidence-corpus.js +927 -0
- package/dist/evidence-corpus.js.map +1 -0
- package/dist/evidence-types.d.ts +230 -0
- package/dist/evidence-types.d.ts.map +1 -0
- package/dist/evidence-types.js +24 -0
- package/dist/evidence-types.js.map +1 -0
- package/dist/executor.d.ts.map +1 -1
- package/dist/executor.js +49 -184
- package/dist/executor.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/suite-manager.d.ts +6 -0
- package/dist/suite-manager.d.ts.map +1 -1
- package/dist/suite-manager.js +14 -4
- package/dist/suite-manager.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,927 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FlowSpec QA — Evidence Corpus Manager
|
|
3
|
+
*
|
|
4
|
+
* Utility functions for creating, populating and querying an EvidenceCorpus.
|
|
5
|
+
*
|
|
6
|
+
* Design principle: functions are pure / side-effect-free where possible.
|
|
7
|
+
* The corpus object is mutated only by `addRecord()` and `finalizeCorpus()`.
|
|
8
|
+
*
|
|
9
|
+
* Spec reference: smartcase/DISCOVERY_SPEC.md § 2 "El Evidence Corpus"
|
|
10
|
+
*/
|
|
11
|
+
import { createHash, randomUUID } from 'crypto';
|
|
12
|
+
// ─── Counter for human-readable evidence IDs ─────────────────────────────────
|
|
13
|
+
let _evCounter = 0;
|
|
14
|
+
function nextEvidenceId() {
|
|
15
|
+
_evCounter++;
|
|
16
|
+
return `ev_${String(_evCounter).padStart(3, '0')}`;
|
|
17
|
+
}
|
|
18
|
+
/** Reset the counter — call this at the start of each Discovery session. */
|
|
19
|
+
export function resetEvidenceCounter() {
|
|
20
|
+
_evCounter = 0;
|
|
21
|
+
}
|
|
22
|
+
// ─── Corpus lifecycle ─────────────────────────────────────────────────────────
|
|
23
|
+
/**
|
|
24
|
+
* Create a fresh, empty EvidenceCorpus for a new Discovery session.
|
|
25
|
+
*
|
|
26
|
+
* @param appId App package name or URL being explored
|
|
27
|
+
* @param sessionId Caller-supplied session ID (use randomUUID() if none)
|
|
28
|
+
*/
|
|
29
|
+
export function createCorpus(appId, sessionId) {
|
|
30
|
+
resetEvidenceCounter();
|
|
31
|
+
return {
|
|
32
|
+
sessionId: sessionId ?? randomUUID(),
|
|
33
|
+
appId,
|
|
34
|
+
startedAt: new Date().toISOString(),
|
|
35
|
+
records: [],
|
|
36
|
+
elementIndex: {},
|
|
37
|
+
screenIndex: {},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Add an EvidenceRecord to the corpus and update all indices.
|
|
42
|
+
* Call this immediately after each interaction is captured.
|
|
43
|
+
*/
|
|
44
|
+
export function addRecord(corpus, record) {
|
|
45
|
+
corpus.records.push(record);
|
|
46
|
+
// Update element index
|
|
47
|
+
const allElements = [...record.elements_before, ...record.elements_after];
|
|
48
|
+
for (const el of allElements) {
|
|
49
|
+
if (!el.elementId)
|
|
50
|
+
continue;
|
|
51
|
+
if (!corpus.elementIndex[el.elementId]) {
|
|
52
|
+
corpus.elementIndex[el.elementId] = [];
|
|
53
|
+
}
|
|
54
|
+
if (!corpus.elementIndex[el.elementId].includes(record.evidenceId)) {
|
|
55
|
+
corpus.elementIndex[el.elementId].push(record.evidenceId);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
// Update screen index (origin + destination)
|
|
59
|
+
for (const screenName of [record.screen_origin, record.screen_destination]) {
|
|
60
|
+
if (!screenName)
|
|
61
|
+
continue;
|
|
62
|
+
if (!corpus.screenIndex[screenName]) {
|
|
63
|
+
corpus.screenIndex[screenName] = [];
|
|
64
|
+
}
|
|
65
|
+
if (!corpus.screenIndex[screenName].includes(record.evidenceId)) {
|
|
66
|
+
corpus.screenIndex[screenName].push(record.evidenceId);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Mark the corpus as finished and set the finishedAt timestamp.
|
|
72
|
+
* Call this after the final interaction is recorded.
|
|
73
|
+
*/
|
|
74
|
+
export function finalizeCorpus(corpus) {
|
|
75
|
+
return { ...corpus, finishedAt: new Date().toISOString() };
|
|
76
|
+
}
|
|
77
|
+
// ─── EvidenceRecord factory ───────────────────────────────────────────────────
|
|
78
|
+
/**
|
|
79
|
+
* Build an EvidenceRecord from its component parts.
|
|
80
|
+
* Assigns an auto-incrementing evidenceId and stamps the current timestamp.
|
|
81
|
+
*/
|
|
82
|
+
export function buildRecord(params) {
|
|
83
|
+
const evidenceId = nextEvidenceId();
|
|
84
|
+
const record = {
|
|
85
|
+
evidenceId,
|
|
86
|
+
timestamp: new Date().toISOString(),
|
|
87
|
+
...params,
|
|
88
|
+
// Backfill evidenceRef in all UIElements so they point to this record
|
|
89
|
+
elements_before: params.elements_before.map(e => e.evidenceRef ? e : { ...e, evidenceRef: evidenceId }),
|
|
90
|
+
elements_after: params.elements_after.map(e => e.evidenceRef ? e : { ...e, evidenceRef: evidenceId }),
|
|
91
|
+
};
|
|
92
|
+
// Phase 6 auto-computed fields
|
|
93
|
+
record.capture_mode = params.capture_mode ?? params.captured_by;
|
|
94
|
+
record.evidence_status = 'captured';
|
|
95
|
+
record.evidence_quality = deriveEvidenceQuality(record);
|
|
96
|
+
const afterElements = record.elements_after.length > 0
|
|
97
|
+
? record.elements_after : record.elements_before;
|
|
98
|
+
const texts = afterElements.map(e => e.visibleText).filter((t) => !!t);
|
|
99
|
+
record.screen_fingerprint = screenFingerprint(afterElements, texts);
|
|
100
|
+
record.evidence_hash = computeEvidenceHash(record);
|
|
101
|
+
return record;
|
|
102
|
+
}
|
|
103
|
+
// ─── UIElement helpers ────────────────────────────────────────────────────────
|
|
104
|
+
/**
|
|
105
|
+
* Convert the legacy `{ type, text, id }` element format used by `ScreenEvidence`
|
|
106
|
+
* into the richer `UIElement` format used by `EvidenceRecord`.
|
|
107
|
+
*
|
|
108
|
+
* @param elements Legacy element array from extractMaestroSelectors()
|
|
109
|
+
* @param evidenceRef The evidenceId to assign to all elements
|
|
110
|
+
*/
|
|
111
|
+
export function legacyElementsToUIElements(elements, evidenceRef) {
|
|
112
|
+
return elements.map(e => ({
|
|
113
|
+
elementId: e.id,
|
|
114
|
+
elementType: e.type,
|
|
115
|
+
visibleText: e.text !== 'N/A' ? e.text : undefined,
|
|
116
|
+
// An element is interactive if it's a natively interactive widget OR
|
|
117
|
+
// if the hierarchy reported it as clickable (covers custom UIs that
|
|
118
|
+
// render buttons as clickable TextViews — e.g. Scotiabank).
|
|
119
|
+
isInteractive: isInteractiveType(e.type) || !!e.clickable,
|
|
120
|
+
evidenceRef,
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Convert a Maestro hierarchy element array to UIElements using a temporary ID
|
|
125
|
+
* (before the evidenceId is assigned). Call `buildRecord()` afterwards to
|
|
126
|
+
* backfill the correct evidenceRef.
|
|
127
|
+
*/
|
|
128
|
+
export function elementsToUIElements(elements) {
|
|
129
|
+
return legacyElementsToUIElements(elements, '__pending__');
|
|
130
|
+
}
|
|
131
|
+
function isInteractiveType(elementType) {
|
|
132
|
+
const INTERACTIVE = new Set([
|
|
133
|
+
'Button', 'ImageButton', 'EditText', 'CheckBox', 'RadioButton', 'Switch',
|
|
134
|
+
]);
|
|
135
|
+
return INTERACTIVE.has(elementType);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Heuristic to detect "button-like" elements regardless of native type.
|
|
139
|
+
*
|
|
140
|
+
* Many Android apps use TextView with `clickable=true` as buttons (Scotiabank,
|
|
141
|
+
* banca custom, RN apps, etc.). Maestro reports the underlying native type
|
|
142
|
+
* (`TextView`), so a strict `elementType === 'Button'` check misses them.
|
|
143
|
+
*
|
|
144
|
+
* Recognizes a button when ANY of the following holds:
|
|
145
|
+
* 1. Native widget type is a button (Button | ImageButton | TouchableOpacity)
|
|
146
|
+
* 2. elementId starts with `btn_` / `button_` / ends with `_button`
|
|
147
|
+
* 3. visibleText is a common action verb (Continuar, Iniciar, Pagar, etc.)
|
|
148
|
+
*
|
|
149
|
+
* Spec reference: DISCOVERY_SPEC.md § 0.1 (rankNavigableButtons heuristics).
|
|
150
|
+
*/
|
|
151
|
+
const BUTTON_NATIVE_TYPES = new Set(['Button', 'ImageButton', 'TouchableOpacity']);
|
|
152
|
+
const BUTTON_ID_RE = /^(btn|button)_|_button$|_btn$/i;
|
|
153
|
+
const BUTTON_TEXT_RE = /^\s*(continuar|aceptar|iniciar|ingresar|entrar|acceder|registrar|enviar|confirmar|guardar|cancelar|cerrar|siguiente|atr[aá]s|volver|ok|sí|s[íi] continuar|salir|listo|finalizar|completar|empezar|comenzar|next|back|close|done|submit|sign\s*in|log\s*in|log\s*out|recuperar?|olvid[eé]|adicional|asociar|no\s+tien[es])\s*$/i;
|
|
154
|
+
export function looksLikeButton(element) {
|
|
155
|
+
if (!element)
|
|
156
|
+
return false;
|
|
157
|
+
if (element.visibleText && element.visibleText.length > 80)
|
|
158
|
+
return false; // Ignore large text overlays / containers
|
|
159
|
+
if (BUTTON_NATIVE_TYPES.has(element.elementType))
|
|
160
|
+
return true;
|
|
161
|
+
if (element.elementId && BUTTON_ID_RE.test(element.elementId))
|
|
162
|
+
return true;
|
|
163
|
+
if (element.visibleText && BUTTON_TEXT_RE.test(element.visibleText))
|
|
164
|
+
return true;
|
|
165
|
+
// Clickable TextViews with meaningful visible text are buttons in custom UIs
|
|
166
|
+
// (e.g. Scotiabank renders all actions as clickable TextViews).
|
|
167
|
+
if (element.isInteractive && element.visibleText && element.visibleText.length >= 4)
|
|
168
|
+
return true;
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
// ─── Form detection ───────────────────────────────────────────────────────────
|
|
172
|
+
/**
|
|
173
|
+
* Examine a set of elements and determine whether they form a fillable form.
|
|
174
|
+
*
|
|
175
|
+
* A "form" is defined as: at least 2 EditText elements + at least 1 Button.
|
|
176
|
+
* Returns null if the screen does not contain a form.
|
|
177
|
+
*/
|
|
178
|
+
export function detectForm(elements, screenName) {
|
|
179
|
+
const inputs = elements.filter(e => e.elementType === 'EditText');
|
|
180
|
+
// Use looksLikeButton to also catch TextView/View used as buttons
|
|
181
|
+
// (common in custom Android UIs — see Scotiabank's btn_next as TextView).
|
|
182
|
+
const buttons = elements.filter(looksLikeButton);
|
|
183
|
+
if (inputs.length < 2 || buttons.length === 0)
|
|
184
|
+
return null;
|
|
185
|
+
// Prefer a semantically meaningful submit button
|
|
186
|
+
const SUBMIT_IDS = ['btn_confirm', 'btn_submit', 'btn_pay', 'btn_send', 'btn_continue', 'btn_accept', 'btn_login', 'btn_next'];
|
|
187
|
+
const submitBtn = buttons.find(b => SUBMIT_IDS.includes(b.elementId)) ?? buttons[buttons.length - 1];
|
|
188
|
+
const fields = inputs.map(input => ({
|
|
189
|
+
id: input.elementId,
|
|
190
|
+
label: input.visibleText || undefined,
|
|
191
|
+
isRequired: true, // conservative default
|
|
192
|
+
}));
|
|
193
|
+
return {
|
|
194
|
+
screenName,
|
|
195
|
+
fields,
|
|
196
|
+
submitButtonId: submitBtn.elementId,
|
|
197
|
+
submitButtonLabel: submitBtn.visibleText,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Detect a login form from a captured hierarchy.
|
|
202
|
+
*
|
|
203
|
+
* Heuristic — fully generic, no hardcoded IDs:
|
|
204
|
+
* - Need ≥1 EditText (single-step login) or ≥2 EditText (classic login)
|
|
205
|
+
* - Need ≥1 Button
|
|
206
|
+
* - Username field = first EditText (top-most in document order)
|
|
207
|
+
* - Password field = the EditText whose visible text/label hints at "password",
|
|
208
|
+
* "contraseña", "clave" or "pin"; otherwise the second EditText
|
|
209
|
+
* - Submit button = the Button whose label hints at "login", "iniciar", "entrar",
|
|
210
|
+
* "acceder", "ingresar", "continuar"; otherwise the last Button
|
|
211
|
+
*
|
|
212
|
+
* Returns null if no plausible form is detected.
|
|
213
|
+
*/
|
|
214
|
+
export function detectLoginForm(elements) {
|
|
215
|
+
const editTexts = elements.filter(e => e.elementType === 'EditText');
|
|
216
|
+
// Use looksLikeButton to handle apps that wrap buttons as TextView/View
|
|
217
|
+
// with clickable=true (e.g. Scotiabank's `btn_next` as TextView).
|
|
218
|
+
const buttons = elements.filter(looksLikeButton);
|
|
219
|
+
if (editTexts.length === 0 || buttons.length === 0)
|
|
220
|
+
return null;
|
|
221
|
+
// Identify password field by hint matching on visible text or known patterns
|
|
222
|
+
const PASSWORD_HINTS = /pass|contrase|clave|pin|secret/i;
|
|
223
|
+
const passwordEdit = editTexts.find(e => e.visibleText && PASSWORD_HINTS.test(e.visibleText)) ??
|
|
224
|
+
(editTexts.length >= 2 ? editTexts[1] : null);
|
|
225
|
+
const usernameEdit = editTexts.find(e => e !== passwordEdit) ?? editTexts[0];
|
|
226
|
+
if (!usernameEdit || !passwordEdit)
|
|
227
|
+
return null;
|
|
228
|
+
// Identify submit button by label heuristics; fall back to last button
|
|
229
|
+
const SUBMIT_HINTS = /login|iniciar|sesi[oó]n|entrar|acceder|ingresar|continuar|sign\s?in|log\s?in/i;
|
|
230
|
+
const submitBtn = buttons.find(b => b.visibleText && SUBMIT_HINTS.test(b.visibleText)) ??
|
|
231
|
+
buttons[buttons.length - 1];
|
|
232
|
+
return {
|
|
233
|
+
usernameId: usernameEdit.elementId,
|
|
234
|
+
usernameLabel: usernameEdit.visibleText,
|
|
235
|
+
passwordId: passwordEdit.elementId,
|
|
236
|
+
passwordLabel: passwordEdit.visibleText,
|
|
237
|
+
submitId: submitBtn.elementId,
|
|
238
|
+
submitLabel: submitBtn.visibleText,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Compare two element sets (before/after) and decide whether the screen changed.
|
|
243
|
+
*
|
|
244
|
+
* Returns:
|
|
245
|
+
* - changed: true if more than `threshold` of the IDs differ
|
|
246
|
+
* - similarity: Jaccard similarity in [0..1] (1 = identical sets)
|
|
247
|
+
* - newIdsCount / removedIdsCount: cardinality of the symmetric difference
|
|
248
|
+
*
|
|
249
|
+
* Default threshold = 0.5 (i.e. ≥50% of IDs must change to count as a new screen).
|
|
250
|
+
*/
|
|
251
|
+
export function detectScreenChange(before, after, threshold = 0.5) {
|
|
252
|
+
const idsBefore = new Set(before.map(e => e.elementId).filter(Boolean));
|
|
253
|
+
const idsAfter = new Set(after.map(e => e.elementId).filter(Boolean));
|
|
254
|
+
if (idsBefore.size === 0 && idsAfter.size === 0) {
|
|
255
|
+
return { changed: false, similarity: 1, newIdsCount: 0, removedIdsCount: 0 };
|
|
256
|
+
}
|
|
257
|
+
const newIds = [...idsAfter].filter(id => !idsBefore.has(id));
|
|
258
|
+
const removedIds = [...idsBefore].filter(id => !idsAfter.has(id));
|
|
259
|
+
const intersect = [...idsBefore].filter(id => idsAfter.has(id));
|
|
260
|
+
const unionSize = idsBefore.size + idsAfter.size - intersect.length;
|
|
261
|
+
const similarity = unionSize === 0 ? 1 : intersect.length / unionSize;
|
|
262
|
+
// "Changed" if similarity is below the threshold complement
|
|
263
|
+
// (i.e. the symmetric difference dominates)
|
|
264
|
+
const changed = similarity < (1 - threshold) || newIds.length >= Math.max(2, Math.floor(idsAfter.size * threshold));
|
|
265
|
+
return {
|
|
266
|
+
changed,
|
|
267
|
+
similarity,
|
|
268
|
+
newIdsCount: newIds.length,
|
|
269
|
+
removedIdsCount: removedIds.length,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Infer a likely screen title from the visible texts on a captured screen.
|
|
274
|
+
*
|
|
275
|
+
* Looks for the first text that:
|
|
276
|
+
* - Is not in `excludeTexts` (avoids picking labels from a parent/launch screen)
|
|
277
|
+
* - Is between 4 and 40 characters
|
|
278
|
+
* - Is not pure numbers, currency, dates or system text (clocks, battery)
|
|
279
|
+
*
|
|
280
|
+
* Returns `fallback` if no suitable text is found.
|
|
281
|
+
*
|
|
282
|
+
* Example: for a Transferencia screen, the captured texts might be:
|
|
283
|
+
* ["Nueva Transferencia", "Monto a transferir", "$ 0", "RUT", ...]
|
|
284
|
+
* → returns "Nueva Transferencia"
|
|
285
|
+
*/
|
|
286
|
+
export function inferScreenName(texts, excludeTexts = [], fallback = 'Pantalla') {
|
|
287
|
+
const exclude = new Set(excludeTexts);
|
|
288
|
+
for (const t of texts) {
|
|
289
|
+
const trimmed = t.trim();
|
|
290
|
+
if (!trimmed || exclude.has(trimmed))
|
|
291
|
+
continue;
|
|
292
|
+
if (trimmed.length < 4 || trimmed.length > 40)
|
|
293
|
+
continue;
|
|
294
|
+
if (/^[\d.,\s%$€£¥]+$/.test(trimmed))
|
|
295
|
+
continue; // pure numbers / currency
|
|
296
|
+
if (/^\d{1,2}:\d{2}(:\d{2})?$/.test(trimmed))
|
|
297
|
+
continue; // clocks
|
|
298
|
+
if (/^v?\d+\.\d+/.test(trimmed))
|
|
299
|
+
continue; // version strings
|
|
300
|
+
if (/android|samsung|google/i.test(trimmed))
|
|
301
|
+
continue; // system labels
|
|
302
|
+
return trimmed;
|
|
303
|
+
}
|
|
304
|
+
return fallback;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Decide whether two element sets look like the same screen.
|
|
308
|
+
*
|
|
309
|
+
* Used to detect logout: when tapping a button on the authenticated screen
|
|
310
|
+
* leads back to a screen that resembles the original login screen, we know
|
|
311
|
+
* the user logged out.
|
|
312
|
+
*
|
|
313
|
+
* Threshold = % of `reference`'s element IDs that must appear in `current`.
|
|
314
|
+
* Default 0.7 means "70% of the reference IDs are present in current".
|
|
315
|
+
*/
|
|
316
|
+
export function isSameScreen(current, reference, threshold = 0.7) {
|
|
317
|
+
if (current.length === 0 || reference.length === 0)
|
|
318
|
+
return false;
|
|
319
|
+
const currentIds = new Set(current.map(e => e.elementId).filter(Boolean));
|
|
320
|
+
const refIds = [...new Set(reference.map(e => e.elementId).filter(Boolean))];
|
|
321
|
+
if (refIds.length === 0)
|
|
322
|
+
return false;
|
|
323
|
+
const overlap = refIds.filter(id => currentIds.has(id)).length;
|
|
324
|
+
return (overlap / refIds.length) >= threshold;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Rank navigable buttons on a screen by likely usefulness for BFS exploration.
|
|
328
|
+
*
|
|
329
|
+
* Ordering rules (no hardcoded names):
|
|
330
|
+
* 1. Buttons with visible text come before buttons without
|
|
331
|
+
* 2. Buttons whose text hints at navigation/action come before generic ones
|
|
332
|
+
* 3. Already-visited element IDs are excluded
|
|
333
|
+
*
|
|
334
|
+
* Excluded element types: TextView, ImageView, container types.
|
|
335
|
+
* Returned array can be safely tapped by the BFS explorer one by one.
|
|
336
|
+
*/
|
|
337
|
+
// Known system/third-party element ID prefixes that do NOT belong to the app under test.
|
|
338
|
+
// Tapping these causes Maestro to lose gRPC connection (UNAVAILABLE) because they navigate
|
|
339
|
+
// to a different app (Google search widget, Android launcher, etc.).
|
|
340
|
+
const SYSTEM_ELEMENT_PREFIXES = [
|
|
341
|
+
'googleapp_', // Google Search widget (overlay on home screen)
|
|
342
|
+
'com.google.', // Any Google app element
|
|
343
|
+
'com.android.', // Android system elements
|
|
344
|
+
'android:', // Android namespace elements
|
|
345
|
+
'com.samsung.', // Samsung system elements
|
|
346
|
+
'com.miui.', // Xiaomi/MIUI elements
|
|
347
|
+
'com.huawei.', // Huawei system elements
|
|
348
|
+
];
|
|
349
|
+
export function rankNavigableButtons(elements, visited, appPackage) {
|
|
350
|
+
const NAV_HINTS = /transfer|pagar|pago|enviar|cuenta|saldo|movimientos|hist[oó]rico|men[uú]|nuev[ao]|crear|consultar|inicio|home|configurar/i;
|
|
351
|
+
const LOGOUT_HINTS = /salir|logout|log[ -]?out|sign[ -]?out|signout|cerrar.*sesi[oó]n|exit|desconectar/i;
|
|
352
|
+
// Inputs are not navigation buttons — exclude them
|
|
353
|
+
const SKIP_TYPES = new Set(['EditText', 'CheckBox', 'RadioButton', 'Switch']);
|
|
354
|
+
const candidates = elements.filter(e => {
|
|
355
|
+
if (!e.elementId)
|
|
356
|
+
return false;
|
|
357
|
+
if (visited.has(e.elementId))
|
|
358
|
+
return false;
|
|
359
|
+
if (SKIP_TYPES.has(e.elementType))
|
|
360
|
+
return false;
|
|
361
|
+
if (!looksLikeButton(e))
|
|
362
|
+
return false;
|
|
363
|
+
// Exclude logout buttons to prevent BFS from closing the session
|
|
364
|
+
if (e.visibleText && LOGOUT_HINTS.test(e.visibleText))
|
|
365
|
+
return false;
|
|
366
|
+
if (e.elementId && LOGOUT_HINTS.test(e.elementId))
|
|
367
|
+
return false;
|
|
368
|
+
// Filter out system/external app elements — they break gRPC connection when tapped
|
|
369
|
+
if (SYSTEM_ELEMENT_PREFIXES.some(pfx => e.elementId.startsWith(pfx)))
|
|
370
|
+
return false;
|
|
371
|
+
// If we know the target app package, filter elements that clearly belong to a different app
|
|
372
|
+
if (appPackage && e.elementId.includes('.') && !e.elementId.startsWith(appPackage)) {
|
|
373
|
+
// Allow short IDs (no dots = likely just a resource name) and below:/text: selectors
|
|
374
|
+
const hasAppPrefix = SYSTEM_ELEMENT_PREFIXES.some(pfx => e.elementId.startsWith(pfx));
|
|
375
|
+
if (hasAppPrefix)
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
return true;
|
|
379
|
+
});
|
|
380
|
+
// Stable sort: native button types > nav-hinted text > btn_* id > text-only
|
|
381
|
+
return [...candidates].sort((a, b) => {
|
|
382
|
+
const scoreA = (BUTTON_NATIVE_TYPES.has(a.elementType) ? 4 : 0) +
|
|
383
|
+
(a.visibleText && NAV_HINTS.test(a.visibleText) ? 2 : 0) +
|
|
384
|
+
(a.elementId && BUTTON_ID_RE.test(a.elementId) ? 1 : 0) +
|
|
385
|
+
(a.visibleText ? 1 : 0);
|
|
386
|
+
const scoreB = (BUTTON_NATIVE_TYPES.has(b.elementType) ? 4 : 0) +
|
|
387
|
+
(b.visibleText && NAV_HINTS.test(b.visibleText) ? 2 : 0) +
|
|
388
|
+
(b.elementId && BUTTON_ID_RE.test(b.elementId) ? 1 : 0) +
|
|
389
|
+
(b.visibleText ? 1 : 0);
|
|
390
|
+
return scoreB - scoreA;
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Decide whether to (re)capture the current screen given an existing baseline.
|
|
395
|
+
*
|
|
396
|
+
* Spec: DISCOVERY_SPEC.md § 11.2 — should_capture() algorithm.
|
|
397
|
+
*
|
|
398
|
+
* Inputs:
|
|
399
|
+
* - currentFingerprint: hash of the screen the engine just observed
|
|
400
|
+
* - baseline: the matching ScreenBaseline (or null if no match)
|
|
401
|
+
* - opts.maxAgeDays: threshold to consider a verified baseline "expired"
|
|
402
|
+
* (default 30; align with spec § 12.4 versioning)
|
|
403
|
+
*
|
|
404
|
+
* Returns:
|
|
405
|
+
* { capture: true, reason: 'new_screen' | 'not_verified' | ... } — do capture
|
|
406
|
+
* { capture: false, reason: 'reuse_verified_baseline' } — skip
|
|
407
|
+
*/
|
|
408
|
+
export function shouldCapture(currentFingerprint, baseline, opts = {}) {
|
|
409
|
+
// 1. No baseline → fresh capture required
|
|
410
|
+
if (!baseline) {
|
|
411
|
+
return { capture: true, reason: 'new_screen' };
|
|
412
|
+
}
|
|
413
|
+
// 2. Baseline exists but tester hasn't validated it yet
|
|
414
|
+
if (baseline.status !== 'verified') {
|
|
415
|
+
return { capture: true, reason: `not_verified_status_${baseline.status}`, matched_baseline_id: baseline.id };
|
|
416
|
+
}
|
|
417
|
+
// 3. Baseline expired by configured age threshold
|
|
418
|
+
const maxAge = opts.maxAgeDays ?? 30;
|
|
419
|
+
if (baseline.verified_at) {
|
|
420
|
+
const verifiedAt = Date.parse(baseline.verified_at);
|
|
421
|
+
if (!Number.isNaN(verifiedAt)) {
|
|
422
|
+
const ageDays = (Date.now() - verifiedAt) / (1000 * 60 * 60 * 24);
|
|
423
|
+
if (ageDays > maxAge) {
|
|
424
|
+
return {
|
|
425
|
+
capture: true,
|
|
426
|
+
reason: `baseline_expired_${Math.round(ageDays)}d`,
|
|
427
|
+
matched_baseline_id: baseline.id,
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
// 4. Marked stale by an external signal (e.g. app version bump)
|
|
433
|
+
if (baseline.stale_reason) {
|
|
434
|
+
return { capture: true, reason: 'baseline_stale', matched_baseline_id: baseline.id };
|
|
435
|
+
}
|
|
436
|
+
// 5. Fingerprint mismatch → screen actually changed since baseline was verified
|
|
437
|
+
if (baseline.screen_fingerprint !== currentFingerprint) {
|
|
438
|
+
return { capture: true, reason: 'fingerprint_changed', matched_baseline_id: baseline.id };
|
|
439
|
+
}
|
|
440
|
+
// 6. All checks passed — reuse verified baseline (skip capture)
|
|
441
|
+
return { capture: false, reason: 'reuse_verified_baseline', matched_baseline_id: baseline.id };
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Look up the baseline entry that matches a given screen fingerprint, if any.
|
|
445
|
+
* Returns null when no baseline is registered for that fingerprint.
|
|
446
|
+
*/
|
|
447
|
+
export function findBaselineForFingerprint(baselines, fingerprint) {
|
|
448
|
+
if (!baselines || baselines.length === 0)
|
|
449
|
+
return null;
|
|
450
|
+
return baselines.find(b => b.screen_fingerprint === fingerprint) ?? null;
|
|
451
|
+
}
|
|
452
|
+
// ─── Corpus queries ───────────────────────────────────────────────────────────
|
|
453
|
+
/**
|
|
454
|
+
* Check whether an elementId was observed during Discovery.
|
|
455
|
+
* Returns the list of EvidenceRecord IDs that contain the element.
|
|
456
|
+
*/
|
|
457
|
+
export function getElementEvidence(corpus, elementId) {
|
|
458
|
+
return corpus.elementIndex[elementId] ?? [];
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Return all element IDs known to the corpus.
|
|
462
|
+
* This is the set of selectors that a STRICT test case is allowed to use.
|
|
463
|
+
*/
|
|
464
|
+
export function getKnownElementIds(corpus) {
|
|
465
|
+
return new Set(Object.keys(corpus.elementIndex));
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Calculate the grounded_score for a set of selectors.
|
|
469
|
+
*
|
|
470
|
+
* grounded_score = (number of selector IDs present in corpus) / (total selector IDs)
|
|
471
|
+
*
|
|
472
|
+
* A STRICT test case must have grounded_score === 1.0 (100%).
|
|
473
|
+
* A score below 1.0 indicates invented / hallucinated selectors.
|
|
474
|
+
*
|
|
475
|
+
* @param corpus The evidence corpus from a Discovery session
|
|
476
|
+
* @param selectorIds The element IDs used in the generated test suite
|
|
477
|
+
* @returns A number between 0.0 and 1.0
|
|
478
|
+
*/
|
|
479
|
+
export function calculateGroundedScore(corpus, selectorIds) {
|
|
480
|
+
if (selectorIds.length === 0)
|
|
481
|
+
return 1.0;
|
|
482
|
+
const known = getKnownElementIds(corpus);
|
|
483
|
+
const present = selectorIds.filter(id => known.has(id)).length;
|
|
484
|
+
return present / selectorIds.length;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Given a list of selector IDs, return which ones are NOT in the corpus.
|
|
488
|
+
* These are the "hallucinated" selectors that must be removed before a test
|
|
489
|
+
* can be promoted to STRICT status.
|
|
490
|
+
*/
|
|
491
|
+
export function getMissingSelectors(corpus, selectorIds) {
|
|
492
|
+
const known = getKnownElementIds(corpus);
|
|
493
|
+
return selectorIds.filter(id => !known.has(id));
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Serialize the corpus to a plain JSON-compatible object.
|
|
497
|
+
* The `elementIndex` and `screenIndex` (which are plain Record<string, string[]>)
|
|
498
|
+
* are already JSON-serializable.
|
|
499
|
+
*/
|
|
500
|
+
export function serializeCorpus(corpus) {
|
|
501
|
+
return {
|
|
502
|
+
...corpus,
|
|
503
|
+
elementIndex: corpus.elementIndex,
|
|
504
|
+
screenIndex: corpus.screenIndex,
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
// ─── Phase 6: Screen fingerprinting & evidence quality ────────────────────
|
|
508
|
+
/**
|
|
509
|
+
* Compute a deterministic fingerprint for a screen based on its element IDs
|
|
510
|
+
* and headline texts. Two screens with the same fingerprint are considered
|
|
511
|
+
* the same for baseline matching purposes.
|
|
512
|
+
*
|
|
513
|
+
* Algorithm: sort stable IDs + sort headline texts → JSON → SHA-256 → first 16 hex chars.
|
|
514
|
+
* Spec reference: DISCOVERY_SPEC.md § 12.1
|
|
515
|
+
*/
|
|
516
|
+
export function screenFingerprint(elements, texts) {
|
|
517
|
+
const stableIds = elements
|
|
518
|
+
.map(e => e.elementId)
|
|
519
|
+
.filter(id => id && !isEphemeralId(id))
|
|
520
|
+
.map(id => id.toLowerCase().trim())
|
|
521
|
+
.sort();
|
|
522
|
+
const headlineTexts = texts
|
|
523
|
+
.map(t => t.trim().toLowerCase())
|
|
524
|
+
.filter(t => t.length >= 4 && t.length <= 40)
|
|
525
|
+
.filter(t => !/^[\d.,\s%$€£¥]+$/.test(t))
|
|
526
|
+
.filter(t => !/^\d{1,2}:\d{2}/.test(t))
|
|
527
|
+
.sort();
|
|
528
|
+
const payload = JSON.stringify({ ids: stableIds, headlines: headlineTexts });
|
|
529
|
+
return createHash('sha256').update(payload).digest('hex').slice(0, 16);
|
|
530
|
+
}
|
|
531
|
+
/** Check whether an element ID is ephemeral (auto-generated, not stable). */
|
|
532
|
+
function isEphemeralId(id) {
|
|
533
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-/.test(id) || // UUIDs
|
|
534
|
+
/^\d{10,}$/.test(id) || // timestamps
|
|
535
|
+
/^id_\d+$/.test(id); // auto-generated
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Compute a SHA-256 hash of the evidence record payload for immutability proof.
|
|
539
|
+
* Excludes mutable audit fields (verified_by, rejected_by, evidence_status, etc.).
|
|
540
|
+
*/
|
|
541
|
+
export function computeEvidenceHash(record) {
|
|
542
|
+
// Destructure to exclude mutable fields from the hash
|
|
543
|
+
const { verified_by: _vb, verified_at: _va, rejected_by: _rb, rejected_at: _ra, rejection_reason: _rr, evidence_status: _es, evidence_hash: _eh, ...immutablePart } = record;
|
|
544
|
+
const payload = JSON.stringify(immutablePart, Object.keys(immutablePart).sort());
|
|
545
|
+
return createHash('sha256').update(payload).digest('hex');
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Derive the evidence quality from the components present in a record.
|
|
549
|
+
* Spec reference: DISCOVERY_SPEC.md § 6.3
|
|
550
|
+
*
|
|
551
|
+
* | Components present | Quality |
|
|
552
|
+
* |-----------------------------------------|------------------|
|
|
553
|
+
* | screenshot + hierarchy + texts + ids | complete |
|
|
554
|
+
* | hierarchy + texts + ids (no screenshot) | technical_only |
|
|
555
|
+
* | screenshot + texts (no ids) | visual_only |
|
|
556
|
+
* | anything else | incomplete |
|
|
557
|
+
*/
|
|
558
|
+
export function deriveEvidenceQuality(record) {
|
|
559
|
+
const hasScreenshot = !!(record.screenshot_after || record.screenshot_before);
|
|
560
|
+
const allElements = [...record.elements_after, ...record.elements_before];
|
|
561
|
+
const hasHierarchy = allElements.length > 0;
|
|
562
|
+
const hasIds = hasHierarchy && allElements.some(e => !!e.elementId);
|
|
563
|
+
const hasTexts = hasHierarchy && allElements.some(e => !!e.visibleText);
|
|
564
|
+
if (hasScreenshot && hasHierarchy && hasTexts && hasIds)
|
|
565
|
+
return 'complete';
|
|
566
|
+
if (hasHierarchy && hasTexts && hasIds)
|
|
567
|
+
return 'technical_only';
|
|
568
|
+
if (hasScreenshot && hasTexts)
|
|
569
|
+
return 'visual_only';
|
|
570
|
+
return 'incomplete';
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Migrate a pre-Phase 6 EvidenceRecord by filling in missing fields.
|
|
574
|
+
* Safe to call on already-migrated records (idempotent).
|
|
575
|
+
* Spec reference: DISCOVERY_SPEC.md § 6.4
|
|
576
|
+
*/
|
|
577
|
+
export function migrateRecord(record) {
|
|
578
|
+
const migrated = { ...record };
|
|
579
|
+
// captured_by → capture_mode
|
|
580
|
+
if (!migrated.capture_mode && migrated.captured_by) {
|
|
581
|
+
migrated.capture_mode = migrated.captured_by;
|
|
582
|
+
}
|
|
583
|
+
// Default evidence_status
|
|
584
|
+
if (!migrated.evidence_status) {
|
|
585
|
+
migrated.evidence_status = 'captured';
|
|
586
|
+
}
|
|
587
|
+
// Derive evidence_quality from content
|
|
588
|
+
if (!migrated.evidence_quality) {
|
|
589
|
+
migrated.evidence_quality = deriveEvidenceQuality(migrated);
|
|
590
|
+
}
|
|
591
|
+
// Compute screen_fingerprint if missing
|
|
592
|
+
if (!migrated.screen_fingerprint) {
|
|
593
|
+
const elements = migrated.elements_after.length > 0
|
|
594
|
+
? migrated.elements_after
|
|
595
|
+
: migrated.elements_before;
|
|
596
|
+
const texts = elements.map(e => e.visibleText).filter((t) => !!t);
|
|
597
|
+
migrated.screen_fingerprint = screenFingerprint(elements, texts);
|
|
598
|
+
}
|
|
599
|
+
// Compute evidence_hash if missing
|
|
600
|
+
if (!migrated.evidence_hash) {
|
|
601
|
+
migrated.evidence_hash = computeEvidenceHash(migrated);
|
|
602
|
+
}
|
|
603
|
+
return migrated;
|
|
604
|
+
}
|
|
605
|
+
function detectFieldKind(elementId, label) {
|
|
606
|
+
const id = elementId.toLowerCase();
|
|
607
|
+
const lbl = (label ?? '').toLowerCase();
|
|
608
|
+
// Order matters: stronger semantic signals come first.
|
|
609
|
+
if (/amount|monto|saldo|importe|valor|\$/i.test(id) || /\$|monto|importe|cantidad/i.test(lbl))
|
|
610
|
+
return 'monetary';
|
|
611
|
+
if (/password|pass|contrase|clave|pin|secret/i.test(id) || /contrase|clave|pin/i.test(lbl))
|
|
612
|
+
return 'password';
|
|
613
|
+
// Identifier takes precedence over email for transfer-recipient fields.
|
|
614
|
+
// Labels like "RUT o email del destinatario" contain "email" but are
|
|
615
|
+
// semantically destination identifiers, not email-only fields.
|
|
616
|
+
if (/recipient|destinatario|rut|dni|cedula|cuenta/i.test(id) ||
|
|
617
|
+
/destinatario|\brut\b|cuenta|c[ée]dula|\bdni\b/i.test(lbl))
|
|
618
|
+
return 'identifier';
|
|
619
|
+
if (/email/i.test(id) || /\bemail\b|correo electr/i.test(lbl))
|
|
620
|
+
return 'email';
|
|
621
|
+
if (/phone|tel|movil|celular/i.test(id) || /tel[eé]fono|celular|m[oó]vil/i.test(lbl))
|
|
622
|
+
return 'phone';
|
|
623
|
+
if (/desc|description|detalle|nota|comentario/i.test(id) || /descripci|detalle|nota/i.test(lbl))
|
|
624
|
+
return 'description';
|
|
625
|
+
if (/date|fecha|day|mes/i.test(id) || /fecha|d[ií]a/i.test(lbl))
|
|
626
|
+
return 'date';
|
|
627
|
+
return 'unknown';
|
|
628
|
+
}
|
|
629
|
+
// ── RECO templates by field kind (banking-aware) ─────────────────────────
|
|
630
|
+
/**
|
|
631
|
+
* Build a human-readable tag for a field. Prefers a semantic name based on
|
|
632
|
+
* the detected field kind over the visible text (which is often a placeholder
|
|
633
|
+
* like "$ 0" or "RUT o email" instead of the proper label).
|
|
634
|
+
*/
|
|
635
|
+
function semanticFieldTag(elementId, kind, label) {
|
|
636
|
+
// Map kind to a semantic Spanish label
|
|
637
|
+
const kindLabels = {
|
|
638
|
+
monetary: 'Monto',
|
|
639
|
+
identifier: 'Destinatario',
|
|
640
|
+
password: 'Contraseña',
|
|
641
|
+
email: 'Email',
|
|
642
|
+
phone: 'Teléfono',
|
|
643
|
+
description: 'Descripción',
|
|
644
|
+
date: 'Fecha',
|
|
645
|
+
unknown: '', // will fall back below
|
|
646
|
+
};
|
|
647
|
+
// If we have a semantic kind, use it
|
|
648
|
+
if (kindLabels[kind]) {
|
|
649
|
+
return `"${kindLabels[kind]}"`;
|
|
650
|
+
}
|
|
651
|
+
// Otherwise, use label if it's not a placeholder-looking value
|
|
652
|
+
// (placeholders are typically: "$ 0", short numbers, generic words like "Email o usuario")
|
|
653
|
+
const looksLikePlaceholder = label && (/^[\$€£¥]\s*\d+$/.test(label) || // "$ 0"
|
|
654
|
+
/^\d+([.,]\d+)?$/.test(label) || // pure numbers
|
|
655
|
+
label.length < 5 // too short
|
|
656
|
+
);
|
|
657
|
+
if (label && !looksLikePlaceholder) {
|
|
658
|
+
return `"${label}"`;
|
|
659
|
+
}
|
|
660
|
+
// Last resort: derive from elementId (et_amount → "amount" → "Monto"?)
|
|
661
|
+
return `"${elementId}"`;
|
|
662
|
+
}
|
|
663
|
+
function recosForField(elementId, kind, label, evidenceId) {
|
|
664
|
+
const tag = semanticFieldTag(elementId, kind, label);
|
|
665
|
+
switch (kind) {
|
|
666
|
+
case 'monetary': return [
|
|
667
|
+
{
|
|
668
|
+
title: `${tag}: monto sobre el saldo disponible`,
|
|
669
|
+
category: 'monetario', priority: 'alta',
|
|
670
|
+
origin_element: elementId, origin_evidence_id: evidenceId,
|
|
671
|
+
risk: 'El sistema podría aceptar transferencias sobre el saldo disponible, generando descubiertos no autorizados o errores backend no manejados.',
|
|
672
|
+
missing_evidence: `Capturar respuesta del sistema al ingresar ${tag} > saldo disponible.`,
|
|
673
|
+
recommendation: `Ejecutar Discovery interactivo con un valor superior al saldo en pantalla y registrar el comportamiento (validación inline / error backend / éxito inadvertido).`,
|
|
674
|
+
},
|
|
675
|
+
{
|
|
676
|
+
title: `${tag}: monto cero o negativo`,
|
|
677
|
+
category: 'monetario', priority: 'alta',
|
|
678
|
+
origin_element: elementId, origin_evidence_id: evidenceId,
|
|
679
|
+
risk: 'Valores 0, -1 o exponenciales pueden bypass de validaciones cliente y crear records de monto inválido en backend.',
|
|
680
|
+
missing_evidence: `Capturar reacción de la app a valores 0, -1, 0.001, 1e10.`,
|
|
681
|
+
recommendation: `Probar boundary values: 0, -1, 0.001, 999999999999. Capturar mensaje de validación si aparece.`,
|
|
682
|
+
},
|
|
683
|
+
{
|
|
684
|
+
title: `${tag}: monto con decimales o caracteres no numéricos`,
|
|
685
|
+
category: 'monetario', priority: 'media',
|
|
686
|
+
origin_element: elementId, origin_evidence_id: evidenceId,
|
|
687
|
+
risk: 'Algunos países usan coma decimal vs punto; ingresar formato incorrecto puede silently fallar el parsing.',
|
|
688
|
+
missing_evidence: `Probar "100,50" vs "100.50" vs "100abc".`,
|
|
689
|
+
recommendation: `Capturar comportamiento con 3 formatos numéricos distintos. Verificar que el caracter no numérico sea bloqueado o validado.`,
|
|
690
|
+
},
|
|
691
|
+
];
|
|
692
|
+
case 'identifier': return [
|
|
693
|
+
{
|
|
694
|
+
title: `${tag}: identificador con formato inválido`,
|
|
695
|
+
category: 'identificador', priority: 'alta',
|
|
696
|
+
origin_element: elementId, origin_evidence_id: evidenceId,
|
|
697
|
+
risk: 'Sin validación de formato, transferencias podrían enviarse a destinatarios inexistentes o malformados, dificultando la trazabilidad.',
|
|
698
|
+
missing_evidence: `Capturar respuesta a RUT inválido / email sin "@" / cuenta con caracteres especiales.`,
|
|
699
|
+
recommendation: `Probar valores: "11111111-K" (RUT inválido), "noemail", "''", string vacío con espacios. Registrar mensaje de error si aparece.`,
|
|
700
|
+
},
|
|
701
|
+
{
|
|
702
|
+
title: `${tag}: autoreferencia (transferencia a la misma cuenta origen)`,
|
|
703
|
+
category: 'identificador', priority: 'media',
|
|
704
|
+
origin_element: elementId, origin_evidence_id: evidenceId,
|
|
705
|
+
risk: 'Transferir a la propia cuenta podría generar transacciones circulares o confundir al usuario.',
|
|
706
|
+
missing_evidence: `Capturar comportamiento al ingresar el mismo identificador del titular.`,
|
|
707
|
+
recommendation: `Ejecutar el flujo con destinatario = cuenta origen. Verificar que la app advierta o bloquee.`,
|
|
708
|
+
},
|
|
709
|
+
];
|
|
710
|
+
case 'password': return [
|
|
711
|
+
{
|
|
712
|
+
title: `${tag}: contraseña con caracteres especiales / longitud máxima`,
|
|
713
|
+
category: 'seguridad', priority: 'alta',
|
|
714
|
+
origin_element: elementId, origin_evidence_id: evidenceId,
|
|
715
|
+
risk: 'Inputs como "\' OR 1=1 --" pueden indicar SQL injection vulnerabilities. Caracteres Unicode pueden romper hashing inseguro.',
|
|
716
|
+
missing_evidence: `Capturar respuesta a contraseñas con: SQL injection patterns, emoji, caracteres Unicode, longitud > 100 chars.`,
|
|
717
|
+
recommendation: `Ejecutar login con 4-5 valores adversariales conocidos. NO usar credenciales reales — solo verificar que la app rechace el formato sin filtrar el input.`,
|
|
718
|
+
},
|
|
719
|
+
];
|
|
720
|
+
case 'description':
|
|
721
|
+
case 'email':
|
|
722
|
+
case 'phone':
|
|
723
|
+
case 'date': return [
|
|
724
|
+
{
|
|
725
|
+
title: `${tag}: caracteres especiales / longitud máxima`,
|
|
726
|
+
category: 'texto', priority: 'media',
|
|
727
|
+
origin_element: elementId, origin_evidence_id: evidenceId,
|
|
728
|
+
risk: `Sin límite de longitud o validación de caracteres, este campo puede ser vector de XSS, SQL injection o causar overflow en backend.`,
|
|
729
|
+
missing_evidence: `Capturar comportamiento con longitud > 500 chars, emoji, HTML tags, caracteres de control.`,
|
|
730
|
+
recommendation: `Probar valores: "<script>", longitud máxima conocida, emoji, espacios al inicio/fin.`,
|
|
731
|
+
},
|
|
732
|
+
];
|
|
733
|
+
default: return [];
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
// ── Flujos parciales → RECO de recaptura ─────────────────────────────────
|
|
737
|
+
/**
|
|
738
|
+
* Build a human-readable label for a partial flow, distinguishing it from
|
|
739
|
+
* other partials with the same submit button (e.g. TRANSFERIR via btn_transfer
|
|
740
|
+
* vs PAGAR via btn_pay — both end at the same form_submit, but the flows differ).
|
|
741
|
+
*
|
|
742
|
+
* Strategy: derive the entry context from the screen_destination (which encodes
|
|
743
|
+
* the alias path in `[vía X]` when applicable) or from the screen_origin.
|
|
744
|
+
*/
|
|
745
|
+
function describePartialFlow(record) {
|
|
746
|
+
// Detect "[vía X]" suffix to extract the alias entry button
|
|
747
|
+
const aliasMatch = record.screen_destination.match(/\[vía\s+(.+?)\]/);
|
|
748
|
+
if (aliasMatch) {
|
|
749
|
+
return {
|
|
750
|
+
contextLabel: `vía ${aliasMatch[1]}`,
|
|
751
|
+
flowName: `${record.action_label || record.action_element} [vía ${aliasMatch[1]}]`,
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
// Otherwise: use the origin screen as context
|
|
755
|
+
// e.g. "Nueva Transferencia" → "vía Nueva Transferencia"
|
|
756
|
+
return {
|
|
757
|
+
contextLabel: `desde ${record.screen_origin}`,
|
|
758
|
+
flowName: `${record.action_label || record.action_element} (desde ${record.screen_origin})`,
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
function recosForPartialFlow(record) {
|
|
762
|
+
const { contextLabel, flowName } = describePartialFlow(record);
|
|
763
|
+
return {
|
|
764
|
+
title: `Recapturar flujo "${flowName}" con resolución manual`,
|
|
765
|
+
category: 'flujo', priority: 'alta',
|
|
766
|
+
origin_element: record.action_element, origin_evidence_id: record.evidenceId,
|
|
767
|
+
risk: `Sin pantalla final verificable (comprobante exitoso o error explícito) para el flujo ${contextLabel}, no se puede generar STRICT del happy path. El tester puede creer que el flujo está cubierto cuando no lo está.`,
|
|
768
|
+
missing_evidence: `Capturar la pantalla final tras submit exitoso (comprobante / confirmación / error backend) específicamente del flujo ${contextLabel}.`,
|
|
769
|
+
recommendation: `1) Resolver manualmente el paso bloqueante (PIN/2FA/OTP) accediendo ${contextLabel}. 2) Cuando llegues al estado final, ejecutar: \`flowspecqa capture --entity <X> --label "Comprobante de ${flowName}"\`. 3) Validar la captura desde la UI Baseline (Fase 10).`,
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
// ── GAPS templates ───────────────────────────────────────────────────────
|
|
773
|
+
function gapForButton(elementId, label) {
|
|
774
|
+
// Trivial navigation buttons are not real coverage gaps
|
|
775
|
+
const TRIVIAL = /^btn_(back|close|cancel|home|previous|atras|cerrar|cancelar)$/i;
|
|
776
|
+
if (TRIVIAL.test(elementId))
|
|
777
|
+
return null;
|
|
778
|
+
const tag = label ? `"${label}"` : `"${elementId}"`;
|
|
779
|
+
return {
|
|
780
|
+
action: `Tappear ${tag} y registrar destino`,
|
|
781
|
+
category: 'cobertura', priority: 'media',
|
|
782
|
+
origin_element: elementId,
|
|
783
|
+
impact: `El botón fue observado en la jerarquía pero nunca se ejercitó. Sin tappearlo, no se puede saber a qué pantalla lleva ni si su flujo derivado funciona correctamente.`,
|
|
784
|
+
recommendation: `Próximo Discovery agregará este elemento al BFS automáticamente. Para forzarlo ahora: ejecutar Discovery con el dispositivo en una pantalla donde ${tag} sea visible.`,
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
function gapForPartialFlow(record) {
|
|
788
|
+
const { contextLabel, flowName } = describePartialFlow(record);
|
|
789
|
+
return {
|
|
790
|
+
action: `Capturar resultado final del flujo "${flowName}"`,
|
|
791
|
+
category: 'evidencia', priority: 'alta',
|
|
792
|
+
origin_element: record.action_element, origin_evidence_id: record.evidenceId,
|
|
793
|
+
impact: `El flujo ${contextLabel} terminó en partial_flow — no hay screenshot del comprobante o estado final. Esto bloquea la generación de STRICT enterprise para este flujo crítico.`,
|
|
794
|
+
recommendation: `Manual: navegar al comprobante exitoso ${contextLabel} y ejecutar \`flowspecqa capture --label "Comprobante exitoso ${flowName}"\`.`,
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
export function classifyCorpus(corpus) {
|
|
798
|
+
const result = {
|
|
799
|
+
strict_count: 0, partial_count: 0, reco_count: 0, gaps_count: 0,
|
|
800
|
+
details: { strict: [], partial: [], reco: [], gaps: [] },
|
|
801
|
+
};
|
|
802
|
+
// ── Pass 1: Classify each EvidenceRecord into STRICT / PARTIAL ──────
|
|
803
|
+
for (const r of corpus.records) {
|
|
804
|
+
switch (r.result_type) {
|
|
805
|
+
case 'new_screen':
|
|
806
|
+
case 'validation_state':
|
|
807
|
+
case 'session_end':
|
|
808
|
+
case 'navigation_return':
|
|
809
|
+
case 'navigation': // legacy
|
|
810
|
+
case 'success': // legacy
|
|
811
|
+
case 'duplicate_route':
|
|
812
|
+
case 'known_screen':
|
|
813
|
+
result.strict_count++;
|
|
814
|
+
result.details.strict.push({
|
|
815
|
+
evidenceId: r.evidenceId,
|
|
816
|
+
description: `${r.action_type} ${r.action_element} → ${r.screen_destination}${r.result_type === 'duplicate_route' ? ' (alias)' : ''}`,
|
|
817
|
+
});
|
|
818
|
+
break;
|
|
819
|
+
case 'partial_flow':
|
|
820
|
+
case 'error': // legacy
|
|
821
|
+
result.partial_count++;
|
|
822
|
+
result.details.partial.push({
|
|
823
|
+
evidenceId: r.evidenceId,
|
|
824
|
+
description: r.result_description,
|
|
825
|
+
recommendation: `Resolver el paso bloqueante manualmente y capturar el estado final con \`flowspecqa capture --label "..."\`.`,
|
|
826
|
+
});
|
|
827
|
+
break;
|
|
828
|
+
// Otros → STRICT con descripción
|
|
829
|
+
case 'no_observable_change':
|
|
830
|
+
case 'no_change': // legacy
|
|
831
|
+
case 'validation': // legacy → use validation_state
|
|
832
|
+
result.strict_count++;
|
|
833
|
+
result.details.strict.push({
|
|
834
|
+
evidenceId: r.evidenceId,
|
|
835
|
+
description: r.result_description,
|
|
836
|
+
});
|
|
837
|
+
break;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
// ── Pass 2: Build RECO from form fields exercised but without edge cases ─
|
|
841
|
+
// Rule: only EditText fields counted (filter out TextViews like tv_tx_amount).
|
|
842
|
+
const editTextIds = new Set();
|
|
843
|
+
for (const rec of corpus.records) {
|
|
844
|
+
for (const el of [...rec.elements_before, ...rec.elements_after]) {
|
|
845
|
+
if (el.elementType === 'EditText' && el.elementId) {
|
|
846
|
+
editTextIds.add(el.elementId);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
// Find label and originating evidenceId for each EditText
|
|
851
|
+
const fieldLabels = new Map();
|
|
852
|
+
const fieldOriginEvId = new Map();
|
|
853
|
+
for (const rec of corpus.records) {
|
|
854
|
+
for (const el of [...rec.elements_before, ...rec.elements_after]) {
|
|
855
|
+
if (editTextIds.has(el.elementId) && !fieldLabels.has(el.elementId)) {
|
|
856
|
+
fieldLabels.set(el.elementId, el.visibleText);
|
|
857
|
+
fieldOriginEvId.set(el.elementId, rec.evidenceId);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
// Generate banking-context RECOs for each EditText
|
|
862
|
+
for (const fieldId of editTextIds) {
|
|
863
|
+
const label = fieldLabels.get(fieldId);
|
|
864
|
+
const evId = fieldOriginEvId.get(fieldId) ?? 'ev_001';
|
|
865
|
+
const kind = detectFieldKind(fieldId, label);
|
|
866
|
+
const recos = recosForField(fieldId, kind, label, evId);
|
|
867
|
+
for (const reco of recos) {
|
|
868
|
+
result.reco_count++;
|
|
869
|
+
result.details.reco.push(reco);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
// ── Pass 3: RECO for each partial_flow → recapture flow ─────────────────
|
|
873
|
+
for (const r of corpus.records) {
|
|
874
|
+
if (r.result_type === 'partial_flow' || r.result_type === 'error') {
|
|
875
|
+
const reco = recosForPartialFlow(r);
|
|
876
|
+
result.reco_count++;
|
|
877
|
+
result.details.reco.push(reco);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
// ── Pass 4: GAPS — pending coverage with action/impact/recommendation ──
|
|
881
|
+
const tappedElements = new Set();
|
|
882
|
+
for (const r of corpus.records) {
|
|
883
|
+
if (r.action_type === 'tap' || r.action_type === 'form_submit') {
|
|
884
|
+
tappedElements.add(r.action_element);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
// Buttons observed but never tapped (excluding trivial navigation)
|
|
888
|
+
const buttonTypes = new Set(['Button', 'ImageButton', 'TouchableOpacity']);
|
|
889
|
+
const buttonInfo = new Map();
|
|
890
|
+
for (const rec of corpus.records) {
|
|
891
|
+
for (const el of [...rec.elements_before, ...rec.elements_after]) {
|
|
892
|
+
if (buttonTypes.has(el.elementType) && el.elementId && !buttonInfo.has(el.elementId)) {
|
|
893
|
+
buttonInfo.set(el.elementId, { label: el.visibleText });
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
for (const [btnId, info] of buttonInfo) {
|
|
898
|
+
if (tappedElements.has(btnId))
|
|
899
|
+
continue;
|
|
900
|
+
const gap = gapForButton(btnId, info.label);
|
|
901
|
+
if (gap) {
|
|
902
|
+
result.gaps_count++;
|
|
903
|
+
result.details.gaps.push(gap);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
// GAP for each partial_flow → high priority recapture
|
|
907
|
+
for (const r of corpus.records) {
|
|
908
|
+
if (r.result_type === 'partial_flow' || r.result_type === 'error') {
|
|
909
|
+
const gap = gapForPartialFlow(r);
|
|
910
|
+
result.gaps_count++;
|
|
911
|
+
result.details.gaps.push(gap);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
return result;
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Produce a human-readable summary of the corpus for logging.
|
|
918
|
+
*/
|
|
919
|
+
export function corpusSummary(corpus) {
|
|
920
|
+
const known = Object.keys(corpus.elementIndex).length;
|
|
921
|
+
const screens = Object.keys(corpus.screenIndex).length;
|
|
922
|
+
const records = corpus.records.length;
|
|
923
|
+
const interactive = corpus.records.filter(r => (r.capture_mode ?? r.captured_by) === 'interactive').length;
|
|
924
|
+
return (`EvidenceCorpus — ${records} records | ${screens} screens | ${known} known elements` +
|
|
925
|
+
(interactive > 0 ? ` | ${interactive} interactive` : ''));
|
|
926
|
+
}
|
|
927
|
+
//# sourceMappingURL=evidence-corpus.js.map
|