logwork-cli 1.1.1 → 1.3.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 (70) hide show
  1. package/README.md +53 -25
  2. package/RELEASE.md +4 -2
  3. package/bin/logwork.mjs +2 -2
  4. package/commands/commits.mjs +128 -13
  5. package/commands/history.mjs +0 -4
  6. package/commands/mcp.mjs +266 -0
  7. package/commands/quick.mjs +38 -23
  8. package/commands/reminder.mjs +41 -2
  9. package/commands/setup.mjs +197 -42
  10. package/commands/tui.mjs +1 -0
  11. package/docs/advanced.md +18 -7
  12. package/docs/mcp-setup.md +120 -26
  13. package/docs/operations-guide.md +50 -2
  14. package/docs/recipes.md +40 -0
  15. package/docs/security.md +23 -2
  16. package/examples/mcp/antigravity.mcp_config.json +2 -2
  17. package/examples/mcp/codex.config.toml +2 -2
  18. package/examples/mcp/copilot.mcp.json +2 -2
  19. package/lib/api-auth-forms.mjs +393 -0
  20. package/lib/api-auth-http.mjs +184 -0
  21. package/lib/api-auth-support.mjs +101 -0
  22. package/lib/api-auth-tokens.mjs +129 -0
  23. package/lib/api-auth.mjs +39 -813
  24. package/lib/api.mjs +38 -1422
  25. package/lib/apply-ledger.mjs +1 -1
  26. package/lib/batch-workflow.mjs +187 -2
  27. package/lib/commit-workflow.mjs +345 -23
  28. package/lib/config.mjs +7 -0
  29. package/lib/diagnostics.mjs +116 -4
  30. package/lib/jira-api.mjs +25 -3
  31. package/lib/jira-workflow.mjs +36 -6
  32. package/lib/launcher.mjs +303 -0
  33. package/lib/logwork-config.mjs +64 -13
  34. package/lib/manual-apply-state.mjs +15 -0
  35. package/lib/manual-commands.mjs +2 -2
  36. package/lib/manual-ink-app.mjs +142 -1282
  37. package/lib/manual-ink-draft-actions.mjs +227 -0
  38. package/lib/manual-ink-interaction.mjs +318 -0
  39. package/lib/manual-ink-session.mjs +41 -0
  40. package/lib/manual-ink-task-editor.mjs +338 -0
  41. package/lib/manual-ink-ui.mjs +38 -0
  42. package/lib/manual-ink-wizard.mjs +520 -0
  43. package/lib/manual-mcp.mjs +78 -20
  44. package/lib/manual-repl.mjs +171 -22
  45. package/lib/mcp-install.mjs +930 -0
  46. package/lib/mcp-server.mjs +51 -20
  47. package/lib/node-runtime.mjs +155 -0
  48. package/lib/paths.mjs +7 -0
  49. package/lib/project-mapping-workflow.mjs +32 -27
  50. package/lib/query-workflow.mjs +19 -1
  51. package/lib/reconciliation-workflow.mjs +1 -1
  52. package/lib/reminder-config.mjs +38 -2
  53. package/lib/reminder-scheduler.mjs +85 -18
  54. package/lib/reminder-service.mjs +42 -3
  55. package/lib/reminder-workflow.mjs +118 -22
  56. package/lib/repo-project-suggestions.mjs +285 -0
  57. package/lib/ro-api-diagnostics.mjs +109 -0
  58. package/lib/ro-api-entries.mjs +359 -0
  59. package/lib/ro-api-fields.mjs +290 -0
  60. package/lib/ro-api-http.mjs +68 -0
  61. package/lib/ro-api-projects.mjs +137 -0
  62. package/lib/ro-api-tasks.mjs +50 -0
  63. package/lib/ro-api-timesheet.mjs +413 -0
  64. package/lib/ro-delete-workflow.mjs +2 -1
  65. package/lib/ro-entry-reader.mjs +11 -6
  66. package/lib/ro-resubmit-workflow.mjs +2 -1
  67. package/lib/terminal-auth-prompts.mjs +7 -4
  68. package/lib/ui.mjs +121 -56
  69. package/package.json +11 -4
  70. package/skills/logwork/SKILL.md +10 -4
package/lib/api-auth.mjs CHANGED
@@ -1,8 +1,45 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { CONFIG } from './config.mjs';
3
3
  import { createTerminalCredentialProvider } from './terminal-auth-prompts.mjs';
4
- import { redactText } from './auth-redaction.mjs';
5
- import { fetchWithPolicy } from './http.mjs';
4
+ import {
5
+ assertSecureUrl,
6
+ originFromUrl,
7
+ readAuthorizationState,
8
+ recordAuthEvent,
9
+ safeApiAuthError,
10
+ safeJson,
11
+ safeUrlParts,
12
+ sameRedirectTarget
13
+ } from './api-auth-support.mjs';
14
+ import { createHttpSession } from './api-auth-http.mjs';
15
+ import {
16
+ parseHtmlForms,
17
+ readBodyHint,
18
+ readTitle,
19
+ selectNextKeycloakForm,
20
+ submitCredentialsForm,
21
+ submitDeviceForm,
22
+ submitOtpForm,
23
+ submitPasswordUpdateForm,
24
+ summarizeFormShapes
25
+ } from './api-auth-forms.mjs';
26
+ import {
27
+ collectJsonKeyPaths,
28
+ decodeJwtPayload,
29
+ extractRoSession
30
+ } from './api-auth-tokens.mjs';
31
+
32
+ export { createHttpSession, requestWithRedirects } from './api-auth-http.mjs';
33
+ export {
34
+ findKeycloakAuthUrl,
35
+ parseHtmlForms,
36
+ selectNextKeycloakForm,
37
+ submitCredentialsForm,
38
+ submitDeviceForm,
39
+ submitOtpForm,
40
+ submitPasswordUpdateForm
41
+ } from './api-auth-forms.mjs';
42
+ export { extractRoSession, extractRoToken } from './api-auth-tokens.mjs';
6
43
 
7
44
  export async function authenticateWithApi({
8
45
  ...options
@@ -198,216 +235,6 @@ export function buildKeycloakAuthorizeUrl({
198
235
  return url.toString();
199
236
  }
200
237
 
201
- export function createHttpSession({
202
- fetchImpl = fetch,
203
- allowedHosts = [],
204
- allowedOrigins = [],
205
- authorizationRedirectUri = null
206
- } = {}) {
207
- const jar = new CookieJar();
208
-
209
- return {
210
- jar,
211
- async request(url, options = {}) {
212
- return requestWithRedirects({
213
- fetchImpl,
214
- jar,
215
- url,
216
- options,
217
- allowedHosts,
218
- allowedOrigins,
219
- authorizationRedirectUri
220
- });
221
- }
222
- };
223
- }
224
-
225
- export async function requestWithRedirects({
226
- fetchImpl,
227
- jar,
228
- url,
229
- options = {},
230
- maxRedirects = 10,
231
- allowedHosts = [],
232
- allowedOrigins = [],
233
- authorizationRedirectUri = null,
234
- timeoutMs = CONFIG.httpTimeoutMs,
235
- retryDelayMs = CONFIG.httpRetryDelayMs,
236
- retries = CONFIG.httpReadRetries
237
- }) {
238
- let currentUrl = new URL(url).toString();
239
- let method = options.method || 'GET';
240
- let body = options.body;
241
- const headers = new Headers(options.headers || {});
242
- const allowedHostSet = new Set(allowedHosts.filter(Boolean).map((host) => String(host).toLowerCase()));
243
- const allowedOriginSet = new Set(allowedOrigins.filter(Boolean).map((origin) => String(origin).toLowerCase()));
244
-
245
- for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount += 1) {
246
- assertSecureUrl(currentUrl, 'Auth request');
247
- const cookie = jar.header(currentUrl);
248
- if (cookie) {
249
- headers.set('Cookie', cookie);
250
- }
251
- const response = await fetchWithPolicy(currentUrl, {
252
- ...options,
253
- fetchImpl,
254
- timeoutMs,
255
- retryDelayMs,
256
- retries,
257
- idempotent: isIdempotentMethod(method),
258
- method,
259
- body,
260
- headers,
261
- redirect: 'manual'
262
- });
263
- jar.store(currentUrl, response.headers);
264
-
265
- if (isRedirect(response.status)) {
266
- const location = response.headers.get('location');
267
- if (!location) {
268
- throw safeApiAuthError('Redirect response did not include a location header.');
269
- }
270
- const nextUrl = new URL(location, currentUrl).toString();
271
- assertAllowedRedirect(nextUrl, {
272
- allowedHosts: allowedHostSet,
273
- allowedOrigins: allowedOriginSet,
274
- authorizationRedirectUri
275
- });
276
- const redirectCode = readAuthorizationCode(nextUrl);
277
- if (redirectCode) {
278
- return {
279
- url: nextUrl,
280
- status: response.status,
281
- headers: response.headers,
282
- body: '',
283
- redirectCode,
284
- redirectUri: stripHash(nextUrl)
285
- };
286
- }
287
- currentUrl = nextUrl;
288
- method = 'GET';
289
- body = undefined;
290
- headers.delete('Content-Type');
291
- continue;
292
- }
293
-
294
- const text = await response.text();
295
- if (!response.ok) {
296
- throw safeApiAuthError(`API auth request failed with HTTP ${response.status}.`);
297
- }
298
- return {
299
- url: currentUrl,
300
- status: response.status,
301
- headers: response.headers,
302
- body: text
303
- };
304
- }
305
-
306
- throw safeApiAuthError('Too many redirects during API auth.');
307
- }
308
-
309
- export function findKeycloakAuthUrl(html, baseUrl) {
310
- const matches = String(html || '').match(/https:\/\/keycloak\.vinova\.sg\/auth\/realms\/resource\/protocol\/openid-connect\/auth[^"' <]+/i);
311
- if (matches?.[0]) {
312
- return decodeHtml(matches[0]);
313
- }
314
-
315
- const href = findAttributeValue(html, 'href', /keycloak\.vinova\.sg\/auth\/realms\/resource\/protocol\/openid-connect\/auth/i);
316
- if (href) {
317
- return new URL(decodeHtml(href), baseUrl).toString();
318
- }
319
-
320
- return null;
321
- }
322
-
323
- export function selectNextKeycloakForm(html, baseUrl, { preferDevice = false } = {}) {
324
- const forms = parseHtmlForms(html, baseUrl);
325
- const passwordUpdate = forms.find((form) => form.kind === 'password-update');
326
- const credentials = forms.find((form) => form.kind === 'credentials');
327
- const otp = forms.find((form) => form.kind === 'otp');
328
- const device = forms.find((form) => form.kind === 'device' || form.devices.length > 0);
329
-
330
- if (passwordUpdate) {
331
- return passwordUpdate;
332
- }
333
- if (credentials) {
334
- return credentials;
335
- }
336
- if (otp) {
337
- return otp;
338
- }
339
- if (preferDevice && device) {
340
- return {
341
- ...device,
342
- kind: 'device'
343
- };
344
- }
345
- if (device) {
346
- return device;
347
- }
348
-
349
- return forms.find((form) => form.kind === 'credentials')
350
- || null;
351
- }
352
-
353
- export function parseHtmlForms(html, baseUrl) {
354
- const forms = [];
355
- const source = String(html || '');
356
- const regex = /<form\b([^>]*)>([\s\S]*?)<\/form>/gi;
357
- let match;
358
- while ((match = regex.exec(source))) {
359
- const attrs = match[1];
360
- const inner = match[2];
361
- const action = resolveActionUrl(decodeHtml(readAttr(attrs, 'action') || ''), baseUrl);
362
- const method = (readAttr(attrs, 'method') || 'GET').toUpperCase();
363
- const fields = readInputFields(inner);
364
- const devices = readDeviceOptions(inner);
365
- const kind = classifyForm(fields, devices);
366
- forms.push({ action, method, fields, devices, kind });
367
- }
368
- return forms;
369
- }
370
-
371
- export async function submitCredentialsForm(session, form, { email, password }) {
372
- const body = bodyFromForm(form);
373
- body.set(usernameFieldName(form) || 'username', email);
374
- body.set(passwordFieldName(form) || 'password', password);
375
- return postForm(session, form.action, body);
376
- }
377
-
378
- export async function submitPasswordUpdateForm(session, form, {
379
- newPassword,
380
- confirmPassword
381
- }) {
382
- const fieldNames = passwordUpdateFieldNames(form);
383
- if (!fieldNames) {
384
- throw safeApiAuthError('Keycloak password update form did not contain the expected password fields.');
385
- }
386
- if (!newPassword || newPassword !== confirmPassword) {
387
- throw safeApiAuthError('New Resource Optimiser passwords must be non-empty and match.');
388
- }
389
-
390
- const body = bodyFromForm(form);
391
- body.set(fieldNames.newPassword, newPassword);
392
- body.set(fieldNames.confirmPassword, confirmPassword);
393
- return postForm(session, form.action, body);
394
- }
395
-
396
- export async function submitDeviceForm(session, form, device) {
397
- const body = bodyFromForm(form);
398
- body.set(device.name, device.value);
399
- return postForm(session, form.action, body);
400
- }
401
-
402
- export async function submitOtpForm(session, form, otp, selectedDevice = null) {
403
- const body = bodyFromForm(form);
404
- if (selectedDevice?.name && selectedDevice.value !== undefined) {
405
- body.set(selectedDevice.name, selectedDevice.value);
406
- }
407
- body.set(otpFieldName(form) || 'otp', otp);
408
- return postForm(session, form.action, body);
409
- }
410
-
411
238
  export async function exchangeAuthorizationCode(session, {
412
239
  keycloakTokenUrl,
413
240
  code,
@@ -506,34 +333,6 @@ export async function exchangeSigninKeycloakSession(session, {
506
333
  return finalSession;
507
334
  }
508
335
 
509
- export function extractRoToken(data, headers) {
510
- return extractRoSession(data, headers)?.accessToken || null;
511
- }
512
-
513
- export function extractRoSession(data, headers) {
514
- const accessToken = extractRoAccessToken(data, headers);
515
- if (!accessToken) {
516
- return null;
517
- }
518
- return {
519
- accessToken,
520
- refreshToken: extractRoRefreshToken(data)
521
- };
522
- }
523
-
524
- function extractRoAccessToken(data, headers) {
525
- const candidates = [
526
- readBearerHeader(headers),
527
- ...collectJwtCandidatesByKey(data, isAccessTokenKey)
528
- ].filter(Boolean);
529
- return candidates.find(isResourceOptimiserJwt) || null;
530
- }
531
-
532
- function extractRoRefreshToken(data) {
533
- const candidates = collectJwtCandidatesByKey(data, isRefreshTokenKey).filter(Boolean);
534
- return candidates.find(isResourceOptimiserJwt) || null;
535
- }
536
-
537
336
  export function readAuthContext(rawUrl) {
538
337
  let url;
539
338
  try {
@@ -583,22 +382,6 @@ function assertAllowedFormAction(form, context) {
583
382
  }
584
383
  }
585
384
 
586
- function assertAllowedRedirect(rawUrl, { allowedHosts, allowedOrigins, authorizationRedirectUri }) {
587
- const url = assertSecureUrl(rawUrl, 'Auth redirect');
588
- const origin = url.origin.toLowerCase();
589
- const host = url.host.toLowerCase();
590
- const originAllowed = allowedOrigins?.size
591
- ? allowedOrigins.has(origin)
592
- : allowedHosts.has(host);
593
- if (!originAllowed) {
594
- throw safeApiAuthError(`Blocked auth redirect to unexpected origin: ${url.origin || 'unknown-origin'}.`);
595
- }
596
-
597
- if (readAuthorizationCode(rawUrl) && !sameRedirectTarget(rawUrl, authorizationRedirectUri)) {
598
- throw safeApiAuthError('Blocked authorization code redirect to unexpected Resource Optimiser callback.');
599
- }
600
- }
601
-
602
385
  function assertExpectedAuthorizationRedirect(response, {
603
386
  expectedRedirectUri,
604
387
  expectedState
@@ -639,48 +422,6 @@ function assertExpectedOrigin(rawUrl, expectedOrigin, label) {
639
422
  }
640
423
  }
641
424
 
642
- function assertSecureUrl(rawUrl, label) {
643
- let url;
644
- try {
645
- url = new URL(rawUrl);
646
- } catch {
647
- throw safeApiAuthError(`${label} must be a valid URL.`);
648
- }
649
-
650
- if (!['http:', 'https:'].includes(url.protocol)) {
651
- throw safeApiAuthError(`${label} must use HTTP or HTTPS.`);
652
- }
653
-
654
- if (url.protocol === 'http:' && !isLocalHttpHost(url.hostname)) {
655
- throw safeApiAuthError(`${label} must use HTTPS unless it points to localhost or loopback.`);
656
- }
657
-
658
- return url;
659
- }
660
-
661
- function originFromUrl(rawUrl) {
662
- return assertSecureUrl(rawUrl, 'Origin URL').origin;
663
- }
664
-
665
- function postForm(session, action, body) {
666
- return session.request(action, {
667
- method: 'POST',
668
- headers: {
669
- Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
670
- 'Content-Type': 'application/x-www-form-urlencoded'
671
- },
672
- body
673
- });
674
- }
675
-
676
- function recordAuthEvent(recorder, name, details = {}) {
677
- try {
678
- recorder?.event?.(name, details);
679
- } catch {
680
- // Diagnostics must never break auth.
681
- }
682
- }
683
-
684
425
  function pageDiagnostics(response = {}) {
685
426
  const url = safeUrlParts(response.url);
686
427
  const forms = parseHtmlForms(response.body, response.url);
@@ -742,518 +483,3 @@ function formatSigninKeycloakDiagnostics(response, data) {
742
483
  'Retry with `logwork login`. If this keeps failing, inspect sanitized JSON key diagnostics from the error.'
743
484
  ].join(' ');
744
485
  }
745
-
746
- function safeUrlParts(rawUrl) {
747
- try {
748
- const url = new URL(rawUrl);
749
- return {
750
- host: url.host,
751
- path: url.pathname
752
- };
753
- } catch {
754
- return {
755
- host: 'unknown-host',
756
- path: '/unknown-path'
757
- };
758
- }
759
- }
760
-
761
- function readTitle(html) {
762
- const match = String(html || '').match(/<title[^>]*>([\s\S]*?)<\/title>/i);
763
- return match ? stripTags(decodeHtml(match[1])).slice(0, 120) : null;
764
- }
765
-
766
- function readBodyHint(html) {
767
- const bodyMatch = String(html || '').match(/<body[^>]*>([\s\S]*?)<\/body>/i);
768
- const body = String(bodyMatch ? bodyMatch[1] : html)
769
- .replace(/<script\b[\s\S]*?<\/script>/gi, ' ')
770
- .replace(/<style\b[\s\S]*?<\/style>/gi, ' ');
771
- const hint = stripTags(decodeHtml(body)).slice(0, 160);
772
- return hint || null;
773
- }
774
-
775
- function resolveActionUrl(action, baseUrl) {
776
- if (!action) {
777
- return baseUrl ? new URL(baseUrl).toString() : '';
778
- }
779
- if (!baseUrl) {
780
- return action;
781
- }
782
- return new URL(action, baseUrl).toString();
783
- }
784
-
785
- function bodyFromForm(form) {
786
- const body = new URLSearchParams();
787
- for (const field of form.fields) {
788
- if (field.name && field.value !== undefined) {
789
- body.set(field.name, field.value);
790
- }
791
- }
792
- return body;
793
- }
794
-
795
- function readBearerHeader(headers) {
796
- const value = headers?.get?.('authorization') || headers?.get?.('Authorization') || '';
797
- const match = String(value).match(/^Bearer\s+(.+)$/i);
798
- return match?.[1]?.trim() || null;
799
- }
800
-
801
- function collectJwtCandidates(value, seen = new Set()) {
802
- if (typeof value === 'string') {
803
- return value.split('.').length >= 3 ? [value] : [];
804
- }
805
- if (!value || typeof value !== 'object' || seen.has(value)) {
806
- return [];
807
- }
808
- seen.add(value);
809
-
810
- const candidates = [];
811
- if (Array.isArray(value)) {
812
- for (const item of value) {
813
- candidates.push(...collectJwtCandidates(item, seen));
814
- }
815
- return candidates;
816
- }
817
-
818
- for (const item of Object.values(value)) {
819
- candidates.push(...collectJwtCandidates(item, seen));
820
- }
821
- return candidates;
822
- }
823
-
824
- function collectJwtCandidatesByKey(value, keyMatcher, seen = new Set()) {
825
- if (!value || typeof value !== 'object' || seen.has(value)) {
826
- return [];
827
- }
828
- seen.add(value);
829
-
830
- const candidates = [];
831
- if (Array.isArray(value)) {
832
- for (const item of value) {
833
- candidates.push(...collectJwtCandidatesByKey(item, keyMatcher, seen));
834
- }
835
- return candidates;
836
- }
837
-
838
- for (const [key, item] of Object.entries(value)) {
839
- if (typeof item === 'string' && keyMatcher(key) && item.split('.').length >= 3) {
840
- candidates.push(item);
841
- }
842
- candidates.push(...collectJwtCandidatesByKey(item, keyMatcher, seen));
843
- }
844
- return candidates;
845
- }
846
-
847
- function isAccessTokenKey(key) {
848
- return /^(access[_-]?token|token|jwt)$/i.test(String(key || ''));
849
- }
850
-
851
- function isRefreshTokenKey(key) {
852
- return /^refresh[_-]?token$/i.test(String(key || ''));
853
- }
854
-
855
- function collectJsonKeyPaths(value, path = '', seen = new Set(), output = []) {
856
- if (!value || typeof value !== 'object' || seen.has(value)) {
857
- return output;
858
- }
859
- seen.add(value);
860
-
861
- if (Array.isArray(value)) {
862
- value.slice(0, 5).forEach((item, index) => {
863
- collectJsonKeyPaths(item, `${path}[${index}]`, seen, output);
864
- });
865
- return output;
866
- }
867
-
868
- for (const key of Object.keys(value)) {
869
- const nextPath = path ? `${path}.${key}` : key;
870
- output.push(nextPath);
871
- if (output.length >= 40) {
872
- return output;
873
- }
874
- collectJsonKeyPaths(value[key], nextPath, seen, output);
875
- }
876
- return output;
877
- }
878
-
879
- function isResourceOptimiserJwt(token) {
880
- const payload = decodeJwtPayload(token);
881
- if (!payload) {
882
- return false;
883
- }
884
- if (isKeycloakJwtPayload(payload)) {
885
- return false;
886
- }
887
- return Boolean(
888
- payload.id !== undefined
889
- || typeof payload.email === 'string'
890
- || typeof payload.db_url === 'string'
891
- || typeof payload.dbUrl === 'string'
892
- || typeof payload.user_id === 'number'
893
- || typeof payload.userId === 'number'
894
- );
895
- }
896
-
897
- function isKeycloakJwtPayload(payload) {
898
- const issuer = String(payload.iss || '').toLowerCase();
899
- return issuer.includes('keycloak')
900
- || payload.azp === 'localhost'
901
- || payload.realm_access !== undefined
902
- || payload.resource_access !== undefined;
903
- }
904
-
905
- function decodeJwtPayload(token) {
906
- const [, payload] = String(token || '').split('.');
907
- if (!payload) {
908
- return null;
909
- }
910
- try {
911
- return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
912
- } catch {
913
- return null;
914
- }
915
- }
916
-
917
- function classifyForm(fields, devices) {
918
- if (passwordUpdateFieldNames({ fields })) {
919
- return 'password-update';
920
- }
921
- if (passwordFieldName({ fields })) {
922
- return 'credentials';
923
- }
924
- if (otpFieldName({ fields })) {
925
- return 'otp';
926
- }
927
- if (devices.length > 0) {
928
- return 'device';
929
- }
930
- return 'unknown';
931
- }
932
-
933
- function readInputFields(html) {
934
- const fields = [];
935
- const regex = /<input\b([^>]*)>/gi;
936
- let match;
937
- while ((match = regex.exec(String(html || '')))) {
938
- const attrs = match[1];
939
- fields.push({
940
- name: decodeHtml(readAttr(attrs, 'name') || ''),
941
- id: decodeHtml(readAttr(attrs, 'id') || ''),
942
- type: decodeHtml(readAttr(attrs, 'type') || 'text'),
943
- value: decodeHtml(readAttr(attrs, 'value') || ''),
944
- autocomplete: decodeHtml(readAttr(attrs, 'autocomplete') || ''),
945
- inputmode: decodeHtml(readAttr(attrs, 'inputmode') || ''),
946
- placeholder: decodeHtml(readAttr(attrs, 'placeholder') || ''),
947
- ariaLabel: decodeHtml(readAttr(attrs, 'aria-label') || '')
948
- });
949
- }
950
- return fields.filter((field) => field.name);
951
- }
952
-
953
- function otpFieldName(form) {
954
- return form.fields.find(isOtpInputField)?.name;
955
- }
956
-
957
- function usernameFieldName(form) {
958
- return fieldName(form, ['username', 'email', 'login', 'user', 'userid', 'user_id']) ||
959
- form.fields.find((field) => isTextInputField(field) && fieldHint(field, /user|email|login|account|identifier/))?.name ||
960
- form.fields.find((field) => isTextInputField(field) && !isOtpInputField(field))?.name;
961
- }
962
-
963
- function passwordFieldName(form) {
964
- return fieldName(form, ['password', 'passwd', 'pass', 'pwd']) ||
965
- form.fields.find((field) => String(field.type || '').toLowerCase() === 'password')?.name;
966
- }
967
-
968
- function passwordUpdateFieldNames(form) {
969
- const passwordFields = form.fields.filter(
970
- (field) => String(field.type || '').toLowerCase() === 'password'
971
- );
972
- if (passwordFields.length < 2) {
973
- return null;
974
- }
975
-
976
- const newPassword = fieldName(form, [
977
- 'password-new',
978
- 'new-password',
979
- 'newPassword',
980
- 'passwordNew'
981
- ]) || passwordFields.find((field) => fieldHint(field, /(?:new.*password|password.*new)/i))?.name;
982
- const confirmPassword = fieldName(form, [
983
- 'password-confirm',
984
- 'confirm-password',
985
- 'confirmPassword',
986
- 'passwordConfirm',
987
- 'password-repeat',
988
- 'repeat-password'
989
- ]) || passwordFields.find((field) => fieldHint(field, /confirm|repeat/i))?.name;
990
-
991
- if (newPassword && confirmPassword && newPassword !== confirmPassword) {
992
- return { newPassword, confirmPassword };
993
- }
994
-
995
- return {
996
- newPassword: passwordFields[0].name,
997
- confirmPassword: passwordFields[1].name
998
- };
999
- }
1000
-
1001
- function fieldName(form, candidates) {
1002
- const lower = new Set(candidates.map((candidate) => candidate.toLowerCase()));
1003
- return form.fields.find((field) => lower.has(String(field.name || '').toLowerCase()))?.name;
1004
- }
1005
-
1006
- function isTextInputField(field) {
1007
- const type = String(field.type || 'text').toLowerCase();
1008
- return ['text', 'email', 'search', 'tel', 'url', ''].includes(type);
1009
- }
1010
-
1011
- function isOtpInputField(field) {
1012
- const name = String(field.name || '').toLowerCase();
1013
- const type = String(field.type || 'text').toLowerCase();
1014
- if (['hidden', 'radio', 'checkbox', 'submit', 'button'].includes(type)) {
1015
- return false;
1016
- }
1017
-
1018
- if (/^(otp|totp|mfa|mfa_code|two_factor|twofactor|authenticator_code|authenticatorCode)$/i.test(name)) {
1019
- return true;
1020
- }
1021
-
1022
- if (/(otp|totp|mfa|2fa|two[_-]?factor|authenticator|verification)/i.test(name)) {
1023
- return true;
1024
- }
1025
-
1026
- if (name !== 'code') {
1027
- return false;
1028
- }
1029
-
1030
- return fieldHint(field, /otp|totp|one-time|one time|verification|authenticator|2fa|mfa|sms|pin|numeric|number/);
1031
- }
1032
-
1033
- function fieldHint(field, pattern) {
1034
- const hint = [
1035
- field.id,
1036
- field.autocomplete,
1037
- field.inputmode,
1038
- field.placeholder,
1039
- field.ariaLabel
1040
- ].map((value) => String(value || '').toLowerCase()).join(' ');
1041
-
1042
- return pattern.test(hint);
1043
- }
1044
-
1045
- function readDeviceOptions(html) {
1046
- const devices = [];
1047
- const radioRegex = /<input\b([^>]*type=["']?radio["']?[^>]*)>/gi;
1048
- let radioMatch;
1049
- while ((radioMatch = radioRegex.exec(String(html || '')))) {
1050
- const attrs = radioMatch[1];
1051
- const name = decodeHtml(readAttr(attrs, 'name') || '');
1052
- const value = decodeHtml(readAttr(attrs, 'value') || '');
1053
- const id = decodeHtml(readAttr(attrs, 'id') || '');
1054
- if (!name || !value) {
1055
- continue;
1056
- }
1057
- devices.push({
1058
- type: 'radio',
1059
- name,
1060
- value,
1061
- label: readLabelFor(html, id) || readWrappingLabelForInput(html, attrs) || value
1062
- });
1063
- }
1064
-
1065
- const selectRegex = /<select\b([^>]*)>([\s\S]*?)<\/select>/gi;
1066
- let selectMatch;
1067
- while ((selectMatch = selectRegex.exec(String(html || '')))) {
1068
- const name = decodeHtml(readAttr(selectMatch[1], 'name') || '');
1069
- if (!name) {
1070
- continue;
1071
- }
1072
- const optionRegex = /<option\b([^>]*)>([\s\S]*?)<\/option>/gi;
1073
- let optionMatch;
1074
- while ((optionMatch = optionRegex.exec(selectMatch[2]))) {
1075
- const value = decodeHtml(readAttr(optionMatch[1], 'value') || '');
1076
- const label = stripTags(decodeHtml(optionMatch[2]));
1077
- if (value) {
1078
- devices.push({ type: 'select', name, value, label: label || value });
1079
- }
1080
- }
1081
- }
1082
-
1083
- return devices;
1084
- }
1085
-
1086
- function readLabelFor(html, id) {
1087
- if (!id) {
1088
- return null;
1089
- }
1090
- const escapedId = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1091
- const match = String(html || '').match(new RegExp(`<label\\b[^>]*for=["']${escapedId}["'][^>]*>([\\s\\S]*?)<\\/label>`, 'i'));
1092
- return match ? stripTags(decodeHtml(match[1])) : null;
1093
- }
1094
-
1095
- function readWrappingLabelForInput(html, inputAttrs) {
1096
- const inputValue = readAttr(inputAttrs, 'value');
1097
- const labels = String(html || '').match(/<label\b[^>]*>[\s\S]*?<\/label>/gi) || [];
1098
- for (const label of labels) {
1099
- const inputMatch = label.match(/<input\b([^>]*)>/i);
1100
- if (!inputMatch) {
1101
- continue;
1102
- }
1103
- const labelInputValue = readAttr(inputMatch[1], 'value');
1104
- const labelInputName = readAttr(inputMatch[1], 'name');
1105
- if (
1106
- inputValue !== null &&
1107
- labelInputValue === inputValue &&
1108
- labelInputName === readAttr(inputAttrs, 'name')
1109
- ) {
1110
- return stripTags(decodeHtml(label));
1111
- }
1112
- }
1113
- return null;
1114
- }
1115
-
1116
- function summarizeFormShapes(forms) {
1117
- return forms
1118
- .slice(0, 3)
1119
- .map((form, index) => {
1120
- const fields = form.fields
1121
- .slice(0, 8)
1122
- .map((field) => `${field.name || '(unnamed)'}:${field.type || 'text'}`)
1123
- .join(',');
1124
- const devices = form.devices.length ? ` devices=${form.devices.length}` : '';
1125
- return `form${index + 1}{kind=${form.kind || 'unknown'} fields=[${fields}]${devices}}`;
1126
- })
1127
- .join(' ');
1128
- }
1129
-
1130
- function readAttr(attrs, name) {
1131
- const match = String(attrs || '').match(new RegExp(`${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'));
1132
- return match?.[1] ?? match?.[2] ?? match?.[3] ?? null;
1133
- }
1134
-
1135
- function findAttributeValue(html, attr, pattern) {
1136
- const regex = new RegExp(`${attr}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'gi');
1137
- let match;
1138
- while ((match = regex.exec(String(html || '')))) {
1139
- const value = match[1] ?? match[2] ?? match[3] ?? '';
1140
- if (pattern.test(value)) {
1141
- return value;
1142
- }
1143
- }
1144
- return null;
1145
- }
1146
-
1147
- function readAuthorizationCode(rawUrl) {
1148
- const url = new URL(rawUrl);
1149
- return url.searchParams.get('code') || new URLSearchParams(url.hash.replace(/^#/, '')).get('code');
1150
- }
1151
-
1152
- function readAuthorizationState(rawUrl) {
1153
- const url = new URL(rawUrl);
1154
- return url.searchParams.get('state') || new URLSearchParams(url.hash.replace(/^#/, '')).get('state');
1155
- }
1156
-
1157
- function sameRedirectTarget(rawUrl, expectedRawUrl) {
1158
- if (!expectedRawUrl) {
1159
- return false;
1160
- }
1161
-
1162
- try {
1163
- const url = new URL(rawUrl);
1164
- const expected = new URL(expectedRawUrl);
1165
- return url.origin === expected.origin && url.pathname === expected.pathname;
1166
- } catch {
1167
- return false;
1168
- }
1169
- }
1170
-
1171
- function isLocalHttpHost(hostname) {
1172
- const host = String(hostname || '').replace(/^\[|\]$/g, '').toLowerCase();
1173
- return host === 'localhost' ||
1174
- host === '127.0.0.1' ||
1175
- host === '::1' ||
1176
- host.startsWith('127.');
1177
- }
1178
-
1179
- function stripHash(rawUrl) {
1180
- const url = new URL(rawUrl);
1181
- url.hash = '';
1182
- return url.toString();
1183
- }
1184
-
1185
- function isRedirect(status) {
1186
- return [301, 302, 303, 307, 308].includes(status);
1187
- }
1188
-
1189
- function isIdempotentMethod(method) {
1190
- return ['GET', 'HEAD', 'OPTIONS'].includes(String(method || 'GET').toUpperCase());
1191
- }
1192
-
1193
- function safeJson(text) {
1194
- try {
1195
- return JSON.parse(text);
1196
- } catch {
1197
- throw safeApiAuthError('Auth endpoint returned non-JSON response.');
1198
- }
1199
- }
1200
-
1201
- function safeApiAuthError(message) {
1202
- const error = new Error(redactText(message));
1203
- error.code = 'API_AUTH_FAILED';
1204
- return error;
1205
- }
1206
-
1207
- function decodeHtml(value) {
1208
- return String(value || '')
1209
- .replace(/&amp;/g, '&')
1210
- .replace(/&quot;/g, '"')
1211
- .replace(/&#39;/g, "'")
1212
- .replace(/&lt;/g, '<')
1213
- .replace(/&gt;/g, '>');
1214
- }
1215
-
1216
- function stripTags(value) {
1217
- return String(value || '').replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
1218
- }
1219
-
1220
- class CookieJar {
1221
- constructor() {
1222
- this.cookies = new Map();
1223
- }
1224
-
1225
- store(rawUrl, headers) {
1226
- const url = new URL(rawUrl);
1227
- const values = getSetCookieValues(headers);
1228
- for (const value of values) {
1229
- const [pair] = value.split(';');
1230
- const [name, cookieValue] = pair.split('=');
1231
- if (name && cookieValue !== undefined) {
1232
- this.cookies.set(`${url.hostname}:${name.trim()}`, `${name.trim()}=${cookieValue.trim()}`);
1233
- }
1234
- }
1235
- }
1236
-
1237
- header(rawUrl) {
1238
- const url = new URL(rawUrl);
1239
- return [...this.cookies.entries()]
1240
- .filter(([key]) => key.startsWith(`${url.hostname}:`))
1241
- .map(([, value]) => value)
1242
- .join('; ');
1243
- }
1244
- }
1245
-
1246
- function getSetCookieValues(headers) {
1247
- if (typeof headers.getSetCookie === 'function') {
1248
- return headers.getSetCookie();
1249
- }
1250
- const value = headers.get?.('set-cookie');
1251
- return value ? splitSetCookie(value) : [];
1252
- }
1253
-
1254
- function splitSetCookie(value) {
1255
- return String(value)
1256
- .split(/,(?=\s*[^;,\s]+=)/)
1257
- .map((item) => item.trim())
1258
- .filter(Boolean);
1259
- }