Skip to content

refactor: deduplicate shared utilities + fix cookie store#21

Merged
Noelithub77 merged 1 commit into
Noelithub77:masterfrom
adi3433:refactor/deduplicate-shared-utils
Apr 9, 2026
Merged

refactor: deduplicate shared utilities + fix cookie store#21
Noelithub77 merged 1 commit into
Noelithub77:masterfrom
adi3433:refactor/deduplicate-shared-utils

Conversation

@adi3433
Copy link
Copy Markdown
Contributor

@adi3433 adi3433 commented Apr 8, 2026

Summary

  • Extract duplicated getSesskey() into shared services/sesskey.ts (was identical in scraper.ts and dashboard.ts)
  • Extract duplicated isLoginHtml() into utils/moodle-url.ts (was copy-pasted across 4 service files: assignment.ts, resources-scraper.ts, feedback-autofill.ts, lms-download.ts)
  • Fix cookie store: validate Date before assigning expires — malformed Set-Cookie headers created Invalid Date objects that could never be garbage-collected

Net: -29 lines. No behavioral changes. TypeScript compiles clean.

Test plan

  • Verify login + session refresh still works
  • Verify attendance scraping + dashboard timeline load correctly
  • Verify assignment details page loads
  • Verify course resources tree loads
  • Verify feedback autofill works
  • Verify LMS file download works

🤖 Generated with Claude Code

- Extract `getSesskey()` into `services/sesskey.ts` (was duplicated in scraper.ts and dashboard.ts)
- Extract `isLoginHtml()` into `utils/moodle-url.ts` (was copy-pasted across 4 service files)
- Fix cookie store: validate Date before assigning expires (malformed Set-Cookie headers created Invalid Date objects that were never cleaned up)

No behavioral changes — all imports updated, TypeScript compiles clean.
@adi3433 adi3433 requested a review from Noelithub77 as a code owner April 8, 2026 14:10
Copilot AI review requested due to automatic review settings April 8, 2026 14:10
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 8, 2026

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Improved cookie expiration date validation to prevent invalid date assignments.
  • Refactor

    • Consolidated duplicate login-detection and session-key retrieval logic into shared utility modules for better maintainability.

Walkthrough

This PR consolidates duplicate utility functions across multiple service files. The isLoginHtml helper is moved from four service files to a shared utility module, getSesskey is extracted into a dedicated service module, and cookie expiration validation is enhanced to check for invalid dates before assignment.

Changes

Cohort / File(s) Summary
Login Detection Consolidation
src/services/assignment.ts, src/services/feedback-autofill.ts, src/services/lms-download.ts, src/services/resources-scraper.ts, src/utils/moodle-url.ts
Removed local isLoginHtml implementations across four service files and centralized the logic in src/utils/moodle-url.ts. The utility detects login pages via whitespace normalization and marker matching (logintoken, id="login", /login/index.php).
Session Key Retrieval Consolidation
src/services/dashboard.ts, src/services/scraper.ts, src/services/sesskey.ts
Extracted getSesskey from two service files into a dedicated src/services/sesskey.ts module. The function fetches /my/, extracts sesskey via regex, and returns the value or null.
Cookie Expiration Validation
src/services/cookie-store.ts
Enhanced Set-Cookie expires attribute parsing to validate parsed dates (!Number.isNaN(parsed.getTime())) before assignment, preventing invalid date objects from being set.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

codex

Suggested reviewers

  • Noelithub77

Poem

🐰 Duplicate helpers scattered 'round,
Now consolidated, logic's sound!
From four files to one, utilities gleam,
Cookie dates validated in the stream.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main refactoring objectives: deduplicating shared utilities (getSesskey and isLoginHtml) across multiple service files and fixing the cookie store validation issue.
Description check ✅ Passed The description covers the main changes (deduplication of getSesskey and isLoginHtml, cookie store fix) and includes a test plan, but the template sections are not fully structured as required.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors duplicated Moodle session helpers into shared utilities and hardens cookie parsing to avoid persisting invalid expiry dates, reducing repeated logic across multiple LMS service modules.

Changes:

  • Extract shared getSesskey() into src/services/sesskey.ts and update callers.
  • Extract shared isLoginHtml() into src/utils/moodle-url.ts and replace copy-pasted implementations across services.
  • Validate parsed expires dates in the cookie store before assigning them.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/utils/moodle-url.ts Adds shared isLoginHtml(html) helper for detecting Moodle login pages.
src/services/sesskey.ts Introduces shared getSesskey() implementation for sesskey extraction.
src/services/scraper.ts Switches from local sesskey extraction to shared getSesskey().
src/services/resources-scraper.ts Replaces local isLoginHtml with shared utility import.
src/services/lms-download.ts Replaces local isLoginHtml with shared utility import.
src/services/feedback-autofill.ts Replaces local isLoginHtml with shared utility import.
src/services/dashboard.ts Switches from local sesskey extraction to shared getSesskey().
src/services/cookie-store.ts Guards against assigning Invalid Date to cookie expires.
src/services/assignment.ts Imports and uses shared isLoginHtml, removing local duplicate.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 8, 2026

Preview

QR Code

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/utils/moodle-url.ts (1)

5-10: Make login marker matching resilient to case/quote variations.

Line 5–Line 10 currently depend on exact substrings (double quotes + exact casing). A small regex-based check would avoid false negatives on equivalent HTML.

♻️ Suggested hardening
 export const isLoginHtml = (html: string): boolean => {
-  const normalized = html.replace(/\s+/g, " ");
+  const normalized = html.toLowerCase().replace(/\s+/g, " ");
   return (
-    normalized.includes('name="logintoken"') ||
-    normalized.includes('id="login"') ||
+    /name\s*=\s*["']logintoken["']/.test(normalized) ||
+    /id\s*=\s*["']login["']/.test(normalized) ||
     normalized.includes("/login/index.php")
   );
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/moodle-url.ts` around lines 5 - 10, The current checks on
normalized (the string produced by normalized = html.replace(/\s+/g, " ")) use
exact substring matches and fail for different casing or single quotes; replace
the three includes checks with case-insensitive regex tests that allow optional
whitespace and either single or double quotes (e.g., test for
name\s*=\s*['"]logintoken['"] and id\s*=\s*['"]login['"], and test for
/login/index.php with an i flag) so the return expression uses those
regex.test(normalized) calls instead of includes to make login marker matching
resilient to case/quote variations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/services/sesskey.ts`:
- Around line 9-10: The debug.scraper call is logging the raw sesskey
(match[1]), which leaks an authentication token; remove or replace that
raw-value log so you do not emit the full sesskey. Update the debug.scraper
invocation that currently references match[1] to either log a non-sensitive
message like "sesskey found" or a masked version (e.g., show only a fixed
prefix/suffix or fixed placeholder) while leaving the return of match[1]
unchanged; also scan the sesskey helper for any other logs that reference
match[1] and remove or mask them similarly.

---

Nitpick comments:
In `@src/utils/moodle-url.ts`:
- Around line 5-10: The current checks on normalized (the string produced by
normalized = html.replace(/\s+/g, " ")) use exact substring matches and fail for
different casing or single quotes; replace the three includes checks with
case-insensitive regex tests that allow optional whitespace and either single or
double quotes (e.g., test for name\s*=\s*['"]logintoken['"] and
id\s*=\s*['"]login['"], and test for /login/index.php with an i flag) so the
return expression uses those regex.test(normalized) calls instead of includes to
make login marker matching resilient to case/quote variations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 760973b0-b3dc-47f1-a3cd-3e0b1c9e93cd

📥 Commits

Reviewing files that changed from the base of the PR and between 834edb1 and fbc35ce.

📒 Files selected for processing (9)
  • src/services/assignment.ts
  • src/services/cookie-store.ts
  • src/services/dashboard.ts
  • src/services/feedback-autofill.ts
  • src/services/lms-download.ts
  • src/services/resources-scraper.ts
  • src/services/scraper.ts
  • src/services/sesskey.ts
  • src/utils/moodle-url.ts

Comment thread src/services/sesskey.ts
@Noelithub77 Noelithub77 merged commit 75bef69 into Noelithub77:master Apr 9, 2026
6 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants