Commit Graph
15 Commits
Author SHA1 Message Date
Kai (Tam Nhu) TranandGitHub 5df2965642 Merge pull request #525 from kaitranntt/kai/feat/518-cursor-protobuf-executor
feat(cursor): add ConnectRPC protobuf encoder/decoder and HTTP/2 executor
2026-02-12 03:48:23 +07:00
Tam Nhu Tran 79ba1de4e2 fix(cursor): tighten rate limit detection string matching
Use specific patterns ('rate limit', 'resource_exhausted', 'too many
requests') instead of broad 'rate' or 'limit' substrings that would
false-positive on unrelated errors like 'character limit exceeded'.
2026-02-12 03:38:31 +07:00
Tam Nhu Tran c5e8241393 fix(cursor): address fourth-round review feedback for protobuf module 2026-02-12 03:27:58 +07:00
Tam Nhu Tran 66a93ee46f fix(cursor): address third-round review feedback for protobuf module
HIGH PRIORITY FIXES:
- Extract shared buffer parsing logic into parseProtobufFrames generator
  method (DRY violation fix) - both JSON and SSE transformers now use
  common frame parsing loop, eliminating ~60% code duplication
- Use COMPRESS_FLAG constants instead of hardcoded 0x01/0x02/0x03 in
  parseConnectRPCFrame for better maintainability

MEDIUM PRIORITY FIXES:
- Return empty buffer on gzip decompression failure (prevents silent
  data corruption) - ALREADY FIXED
- Add debug warning for unknown message roles in convertMessages
- Create GitHub issue #535 for FIELD namespace refactoring follow-up
- Add test coverage: transformProtobufToSSE, error paths, unknown roles

LOW PRIORITY FIXES:
- Rename checksum test to clarify timestamp granularity (~16 min)
- Fix debug log function name in SSE transformer - FIXED BY REFACTOR
- Add comment to TOOL_RESULT_RESULT field documenting future use

All tests pass (1593 pass, 0 fail)
All validation checks pass (typecheck + lint + format + tests)
2026-02-12 03:15:24 +07:00
Tam Nhu Tran a8a68c9599 fix(cursor): address third-round review feedback for auth module 2026-02-12 03:09:35 +07:00
Tam Nhu Tran e177a4b097 fix(cursor): address second-round review feedback for protobuf module
HIGH Priority:
- Add comprehensive unit tests (27 tests covering encoder, decoder, translator, executor)
  * encodeVarint/decodeVarint round-trip (0, 1, 127, 128, 16383, 0xFFFFFFFF)
  * encodeField/decodeField round-trip (VARINT, LEN string, LEN binary)
  * wrapConnectRPCFrame/parseConnectRPCFrame (compressed/uncompressed)
  * buildCursorRequest message translation (system, user, assistant, tool)
  * generateChecksum header format validation
  * buildHeaders output validation
  * transformProtobufToJSON basic conversion
- Create GitHub issue #531 for true streaming implementation
- Update TODO comment to reference issue #531

MEDIUM Priority:
- Export CursorCredentials from cursor-protobuf-schema.ts
- Add JSDoc grouping comments to FIELD constant for clarity
- Make hardcoded values configurable (CURSOR_CLIENT_VERSION, CURSOR_USER_AGENT)
- Add debug logging to 9 silent catch blocks (respects CCS_DEBUG env var)
- Fix stream check: stream !== false → stream === true

Bug Fixes:
- Fix decodeVarint to return unsigned values (>>> 0)
- Fix test assertion for Response.text() async API
2026-02-12 01:26:47 +07:00
Tam Nhu Tran 84a256d0ac fix(cursor): address second-round review feedback for auth module
- Add comprehensive unit tests for cursor-auth.test.ts
  - validateToken: valid/invalid tokens, short tokens, UUID formats, empty strings
  - extractUserInfo: JWT parsing, email handling, non-JWT tokens, malformed base64
  - saveCredentials/loadCredentials: round-trip, invalid JSON/types, missing fields
  - checkAuthStatus: authenticated/not authenticated, expired tokens, JWT exp, invalid dates
  - deleteCredentials: delete existing/non-existent files, multiple deletes
  - All tests use CCS_HOME env var for isolation, real file I/O, no mocks

- Fix dead try-catch around new Date() in checkAuthStatus()
  - Replace try-catch with isNaN check (new Date('garbage') returns Invalid Date, not throw)
  - Properly handle Invalid Date by checking isNaN(getTime())

- Fix email populated with sub claim in extractUserInfo()
  - Change email: decoded.email || decoded.sub to email: decoded.email || undefined
  - Prevent non-email values (UUIDs) from populating email field

- Add type guards for JSON.parse result in extractUserInfo()
  - Cast to Record<string, unknown> and validate types
  - Use typeof checks for email, userId, exp fields
2026-02-12 01:23:29 +07:00
Tam Nhu Tran b412ba2a9e fix(cursor): address remaining review items in auth module
- Enhanced extractUserInfo to return JWT exp claim for expiry detection
- Updated checkAuthStatus to use JWT exp when available, fallback to importedAt heuristic
- Added typeof validation for loadCredentials fields
- Added ENOENT detection for sqlite3 availability in queryStateDb
- Added deleteCredentials function for cleanup
- Updated PR #526 description to remove refreshToken mention
2026-02-12 01:07:25 +07:00
Tam Nhu Tran f3d532afd9 fix(cursor): address remaining LOW review items in protobuf module 2026-02-12 01:06:33 +07:00
Tam Nhu Tran 7e4f08004c fix(cursor): address code review feedback on auth module
- Sanitize SQL key parameter in queryStateDb to prevent injection
- Fix UUID regex: use exact {32} length, remove redundant hyphen from
  stripped character class
- Remove unused types from types.ts (YAGNI): CursorDaemonStatus,
  CursorModel, MessageRole, CursorMessage, CursorToolCall,
  CursorToolResult, ProtobufExtractResult — belong in their respective
  module PRs
2026-02-11 19:31:04 +07:00
Tam Nhu Tran 31f574118d fix(cursor): address code review feedback (attempt 1/5)
- Fix bitwise shift overflow in generateChecksum: use Math.trunc
  division for >>40/>>32 which wrap modulo 32 in JS
- Add FIXED64/FIXED32 bounds checks in protobuf decoder to prevent
  out-of-bounds slice on truncated buffers
- Consolidate COMPRESS_FLAG to single definition in schema (DRY):
  executor now imports from schema, added GZIP_ALT/GZIP_BOTH values
- Fix token split edge case: use indexOf+slice instead of split('::')[1]
  to handle tokens containing multiple :: delimiters
- Fix AbortSignal listener leak: store handler ref, use once:true,
  remove listener on request end/error
2026-02-11 19:27:39 +07:00
Tam Nhu Tran cc5a9039e4 fix(cursor): address code review edge cases in protobuf and executor
CRITICAL FIX:
- CursorCredentials interface now matches types.ts (machineId, ghostMode as top-level)
- Fixes runtime error when cursor-auth saves credentials and cursor-executor reads them

HIGH:
- Replace 18+ non-null assertions with guard clauses across executor and decoder
- Prefix unused params in translator (_model, _stream, _credentials)
- HTTP/2 client closes on connection error to prevent leak
- AbortSignal listener leak documented with TODO (inline arrow prevents cleanup)

MEDIUM:
- Export concatArrays from encoder, remove duplicate from protobuf.ts
- Varint decoder now enforces 5-byte max to prevent overflow
- Buffer slice bounds check prevents out-of-range read
- Empty messages array validation with explicit error
- Buffered streaming limitation documented with TODO comment

All edge cases from code review now addressed.
2026-02-11 19:13:58 +07:00
Tam Nhu Tran aeb580281f fix(cursor): harden auth security and add token expiry warning 2026-02-11 19:06:57 +07:00
Tam Nhu Tran 9daf9430bb feat(cursor): add core protobuf encoder/decoder and executor
- Split protobuf into 3 files: schema, encoder, decoder for <200 LOC constraint
- Implement ConnectRPC wire format encoding (varint, fields, messages, frames)
- Implement protobuf decoder with gzip decompression support
- Port Cursor executor with HTTP/2 support and checksum generation (Jyh cipher)
- Add OpenAI to Cursor message translator (system→user, tool results handling)
- Transform protobuf responses to both SSE and JSON formats
- Use Node.js built-in crypto/zlib (no uuid dependency)
- All files TypeScript strict mode compliant
2026-02-11 17:59:44 +07:00
Tam Nhu Tran 56270d99f3 feat(cursor): add auth module with SQLite auto-detect and types
- Add CursorCredentials, CursorAuthStatus, and related types
- Implement autoDetectTokens() using sqlite3 CLI (no native deps)
- Add validateToken() for token format validation
- Add extractUserInfo() for JWT decoding
- Add saveCredentials/loadCredentials using getCcsDir()
- Add checkAuthStatus() for auth verification
- Platform-specific state.vscdb paths (Linux/macOS/Windows)
- Graceful error handling for missing database/tokens

Refs: #519 (sub-task of #517)
2026-02-11 17:55:15 +07:00