Skip to content

Conversation

@transphorm
Copy link
Member

@transphorm transphorm commented Sep 11, 2025

https://docs.sentry.io/platforms/javascript/guides/node/logs/

Summary

  • add structured NFC logging helper and session context
  • track NFC scan lifecycle in JS and native modules
  • pass session identifiers across scanner bridge

Testing

  • yarn workspaces foreach -A -p -v --topological-dev run nice (failed: sort-exports errors)
  • yarn lint (failed: Unable to resolve module '@selfxyz/mobile-sdk-alpha/stores')
  • yarn build (failed: TS2448 block-scoped variable used before declaration)
  • yarn workspace @selfxyz/contracts build (failed: Couldn't find a script named "hardhat")
  • yarn types (failed: TS2448 block-scoped variable used before declaration)
  • yarn test (failed: workspace errors across multiple packages)

https://chatgpt.com/codex/tasks/task_b_68c26023ad40832dbfaff698aed24a3a

Summary by CodeRabbit

  • New Features

    • Session-scoped NFC telemetry: scans emit session-based events (start, progress, success, failure); scanning APIs now accept a sessionId to correlate sessions.
    • Proof flow telemetry: structured, contextual logging and status-handling utilities across proving lifecycle.
  • Chores

    • Centralized Sentry integration across iOS, Android and web; native build config and dependency updates to support reporting.
    • Added a typed test QR data export.
  • Tests

    • Added/updated unit and integration tests for proving status handling and session-aware NFC scanning.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 11, 2025

Walkthrough

Adds session-scoped Sentry telemetry across JS and native layers, updates PassportReader.scanPassport signatures to accept a sessionId, wires sessionId through scanner flows and tests, adds proving telemetry/refactors, and enables Sentry Gradle/SDK declarations in Android/iOS project files.

Changes

Cohort / File(s) Summary
Android: Gradle & module build
app/android/app/build.gradle, app/android/react-native-passport-reader/android/build.gradle
Apply Sentry RN Gradle script in app-level Gradle and add io.sentry:sentry-android:8.20.0 dependency to the passport-reader module.
Android: NFC native module
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
Add Sentry imports/helper, emit breadcrumbs/errors across NFC scan lifecycle (logNfc), prefer opts.sessionId when present, and remove trailing whitespace from a public message constant.
iOS: Objective‑C bridge
app/ios/PassportReader.m
Update RCT_EXTERN_METHOD(scanPassport...) signature to include new sessionId: NSString * parameter.
iOS: Swift module
app/ios/PassportReader.swift
Add Sentry imports/helper, add currentSessionId, accept/store sessionId in scanPassport, and emit breadcrumbs/errors via logNfc throughout flow; update E2E stub signature.
iOS: Xcode project
app/ios/Self.xcodeproj/project.pbxproj
Remove empty inputPaths/outputPaths from CocoaPods shell phases and convert OTHER_LDFLAGS to an array for Debug/Release.
JS: shared Sentry API
app/src/Sentry.ts, app/src/Sentry.web.ts
Add BaseContext, whitelist/sanitizers, introduce NFCScanContext and ProofContext, and export logEvent, logNFCEvent, and logProofEvent that use breadcrumbs for info/warn and scoped captures for errors.
JS: UI / scan orchestration
app/src/screens/document/DocumentNFCScanScreen.tsx
Generate per-scan sessionId, build baseContext, log lifecycle/focus/UX events, and pass sessionId into scan call.
JS: scanner wiring & types
app/src/utils/nfcScanner.ts, app/src/utils/passportReader.ts, app/src/types/react-native-passport-reader.d.ts
Add sessionId (and optional userId) to inputs/ScanOptions, propagate sessionId into native calls for Android/iOS, and update TS declaration for scanPassport.
JS: proving telemetry & logic
app/src/utils/proving/provingMachine.ts
Replace ad‑hoc logs with structured logProofEvent calls, add timing and platform context, refactor payload/WebSocket resolution into helpers, and expand telemetry across proving flow.
Tests & mocks
app/tests/utils/nfcScanner.test.ts, app/tests/utils/proving/actorMock.ts, app/tests/utils/proving/statusHandlers.test.ts, app/tests/utils/proving/provingMachine.integration.test.ts
Update tests to include sessionId and expect PassportReader calls to include it; extend actorMock with on() and improve unsubscribe cleanup; add new unit/integration tests for proving status handling.
Common types/assets
common/src/utils/aadhaar/assets/dataInput.d.ts
Add ambient export testQRData declaration.

Sequence Diagram(s)

sequenceDiagram
  participant UI as DocumentNFCScanScreen
  participant JS as nfcScanner / passportReader
  participant Native as PassportReader (iOS/Android)
  participant Sentry as Sentry SDK

  rect rgba(200,230,255,0.18)
    UI->>JS: start scan (generate sessionId)
    JS->>Sentry: logNFCEvent info "scan_start" (baseContext)
  end

  rect rgba(220,255,220,0.16)
    JS->>Native: scanPassport(..., sessionId)
    Native->>Sentry: logNfc Breadcrumbs / captureMessage (session_id tag)
  end

  alt scan success
    Native-->>JS: scan result
    JS->>Sentry: logNFCEvent info "scan_success" (stage: complete)
    JS-->>UI: parsed result
  else scan error
    Native-->>JS: error
    JS->>Sentry: logNFCEvent error "scan_failed" (error details)
    JS-->>UI: throw/reject
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • seshanthS
  • aaronmgdr
  • shazarre

Poem

Session sparks, a UUID hums,
Breadcrumbs trace the paths it runs,
Native whispers, JS keeps score,
Errors caught and logged once more,
Observability on the roam 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "[SELF-723] feat: add structured NFC and Proof logging" is concise and accurately summarizes the primary change (adding structured/logging instrumentation for NFC and proof flows), includes the issue tag for traceability, and avoids noisy file lists or emojis; it clearly communicates the PR intent to reviewers. It aligns with the changes across JavaScript and native modules described in the changeset and is neither misleading nor overly generic. Therefore it serves well as a single-line PR summary.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-sentry-structured-logging-for-nfc

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • Failed to retrieve linked issues from the platform client.

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.

@transphorm transphorm changed the title feat: add structured NFC logging [SELF-723] feat: add structured NFC logging Sep 11, 2025
@transphorm transphorm marked this pull request as ready for review September 11, 2025 20:28
return "nfc_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(8)}"
}

private fun logNfc(level: SentryLevel, message: String, stage: String, extras: Map<String, Any?> = emptyMap()) {
Copy link
Member Author

Choose a reason for hiding this comment

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

updated kotlin logic to send capture message on error but to send breadcrumbs during other calls

private var analytics: SelfAnalytics?
private var currentSessionId: String?

private func logNfc(level: SentryLevel, message: String, stage: String, useCANBool: Bool, sessionId: String, extras: [String: Any] = [:]) {
Copy link
Member Author

Choose a reason for hiding this comment

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

updated swift logic with the same breadcrumb for logs logic

Copy link
Contributor

@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: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (2)

205-246: scan_type mis-logged on first breadcrumb due to late opts assignment.

logNfc derives scan_type from this.opts, but this.opts is set after the first logNfc call. First breadcrumb will incorrectly log "mrz" when useCan = true.

Assign opts before session logging:

 @ReactMethod
 fun scan(opts: ReadableMap, promise: Promise) {
-        currentSessionId = if (opts.hasKey("sessionId")) opts.getString("sessionId") else generateSessionId()
+        // Store early so logNfc can derive scan_type correctly
+        this.opts = opts
+        currentSessionId = if (opts.hasKey("sessionId")) opts.getString("sessionId") else generateSessionId()
         apduLogger.setContext("session_id", currentSessionId!!)
@@
-        logNfc(SentryLevel.INFO, "scan_start", "start")
+        logNfc(SentryLevel.INFO, "scan_start", "start")
@@
-        this.opts = opts
         this.scanPromise = promise

740-753: Missing Sentry error capture on scan failure.

Failures in onPostExecute don't log to Sentry via logNfc. Parity with iOS (and your earlier not-supported/not-enabled cases) will help incident triage.

             if (result != null) {
                 // Log.w(TAG, exceptionStack(result))
                 if (result is IOException) {
                     logAnalyticsError("nfc_scan_failed_disconnect", "Lost connection to chip on card")
                     scanPromise?.reject("E_SCAN_FAILED_DISCONNECT", "Lost connection to chip on card")
                 } else {
                     logAnalyticsError("nfc_scan_failed", "Scan failed: ${result.message}")
                     scanPromise?.reject("E_SCAN_FAILED", result)
                 }
+                logNfc(
+                    SentryLevel.ERROR,
+                    "scan_failed",
+                    "error",
+                    mapOf("type" to result.javaClass.simpleName, "message" to (result.message ?: ""))
+                )
 
             apduLogger.clearContext()
             resetState()
                 return
             }
app/ios/PassportReader.swift (1)

144-156: Export ObjC selector & update JS call sites to include sessionId

Swift shows @objc(scanPassport:dateOfBirth:dateOfExpiry:canNumber:useCan:skipPACE:skipCA:extendedMode:usePacePolling:sessionId:resolve:reject:) at app/ios/PassportReader.swift (lines 144, 500), but there is no Objective‑C bridge export (.m RCT_EXTERN_METHOD/RCT_EXPORT_METHOD) and no JS call sites passing sessionId.

  • Add/update the Obj‑C bridge (e.g. app/ios/PassportReader.m or your RCT_EXTERN file) to export the exact selector including sessionId (scanPassport:dateOfBirth:dateOfExpiry:canNumber:useCan:skipPACE:skipCA:extendedMode:usePacePolling:sessionId:resolve:reject:).
  • Update all NativeModules.PassportReader.scanPassport(...) JS call sites to pass the new sessionId argument (or add a JS wrapper for backward compatibility).
app/src/utils/passportReader.ts (1)

25-38: Android: forward sessionId from the JS wrapper to native (default '')

index.android.js currently strips sessionId before calling RNPassportReader.scan; wrapping AndroidPassportReader.scan in app/src/utils/passportReader.ts won't reach native. Update the module JS wrapper (and the package patch) to forward sessionId (default '').

Apply this change in app/android/react-native-passport-reader/index.android.js:

- function scan({ documentNumber, dateOfBirth, dateOfExpiry, canNumber, useCan, quality=1 }) {
+ function scan({ documentNumber, dateOfBirth, dateOfExpiry, canNumber, useCan, quality=1, sessionId = '' }) {
   assert(typeof documentNumber === 'string', 'expected string "documentNumber"')
   assert(isDate(dateOfBirth), 'expected string "dateOfBirth" in format "yyMMdd"')
   assert(isDate(dateOfExpiry), 'expected string "dateOfExpiry" in format "yyMMdd"')
-  return RNPassportReader.scan({ documentNumber, dateOfBirth, dateOfExpiry, quality, useCan, canNumber })
+  return RNPassportReader.scan({ documentNumber, dateOfBirth, dateOfExpiry, quality, useCan, canNumber, sessionId })
 }

Also update patches/react-native-passport-reader+1.0.3.patch (the node_modules patch) with the same change so the shipped JS wrapper forwards sessionId.

app/src/screens/document/DocumentNFCScanScreen.tsx (1)

526-559: Critical: Android NFC listener uses the wrong emitter — use DeviceEventEmitter or guard NativeEventEmitter (RNPassportReader).

RNPassportReader (getName() = "RNPassportReader") emits "NativeEvent" via DeviceEventManagerModule.RCTDeviceEventEmitter; new NativeEventEmitter(NativeModules.nativeModule) can be undefined and crash on Android. Replace the emitter init with a safe platform-aware fallback, for example:

import { NativeEventEmitter, NativeModules, DeviceEventEmitter, Platform } from 'react-native';

const emitter =
Platform.OS === 'android'
? DeviceEventEmitter
: (NativeModules.RNPassportReader ? new NativeEventEmitter(NativeModules.RNPassportReader) : null);

File: app/src/screens/document/DocumentNFCScanScreen.tsx (lines 526–559).

app/src/Sentry.ts (1)

84-101: Remove userId from breadcrumbs (PII) and sanitize NFC breadcrumbs pre-send.

Current policy comment says “Disable collection of PII data,” but logNFCEvent includes user_id in breadcrumb data. Breadcrumbs are attached to error events and are not scrubbed by beforeSend, which only removes event.user. This risks PII leakage.

  • Drop user_id from breadcrumb data.
  • Add beforeBreadcrumb to strip any residual sensitive fields from NFC breadcrumbs.

Apply:

   sentryInit({
     dsn: SENTRY_DSN,
@@
-    beforeSend(event) {
+    beforeSend(event) {
       // Remove PII data
       if (event.user) {
         delete event.user.ip_address;
         delete event.user.id;
       }
       return event;
     },
+    beforeBreadcrumb(breadcrumb) {
+      // Sanitize NFC breadcrumbs to avoid PII leakage
+      if (breadcrumb?.category === 'nfc' && breadcrumb.data) {
+        const { user_id, email, phone, ...rest } = breadcrumb.data as Record<string, unknown>;
+        return { ...breadcrumb, data: rest };
+      }
+      return breadcrumb;
+    },
   const data = {
     session_id: context.sessionId,
     platform: context.platform,
     scan_type: context.scanType,
     stage: context.stage,
-    user_id: context.userId,
     ...extra,
   };

If user correlation is required, prefer ephemeral, non-reversible pseudonyms (e.g., HMAC(userId, server-side secret)) and apply the same sanitization here.

Also applies to: 131-179

🧹 Nitpick comments (1)
app/src/screens/document/DocumentNFCScanScreen.tsx (1)

268-311: Two separate 30s timeout blocks are redundant and risk double handling.

You set and clear scanTimeoutRef twice with near-identical callbacks. Consolidate to a single timer to avoid duplicate analytics, modal, and state transitions.

Apply this diff to unify the timeout:

-      scanTimeoutRef.current = setTimeout(() => {
-        scanCancelledRef.current = true;
-        trackEvent(PassportEvents.NFC_SCAN_FAILED, {
-          error: 'timeout',
-        });
-        logNFCEvent('warn', 'scan_timeout', {
-          ...baseContext,
-          stage: 'timeout',
-        });
-        openErrorModal('Scan timed out. Please try again.');
-        setIsNfcSheetOpen(false);
-        logNFCEvent('info', 'sheet_close', {
-          ...baseContext,
-          stage: 'ui',
-        });
-      }, 30000);
-
-      // Mark NFC scanning as active to prevent analytics flush interference
-      setNfcScanningActive(true);
-
-      if (scanTimeoutRef.current) {
-        clearTimeout(scanTimeoutRef.current);
-        scanTimeoutRef.current = null;
-      }
-      scanTimeoutRef.current = setTimeout(() => {
+      const onScanTimeout = () => {
         scanCancelledRef.current = true;
-        setNfcScanningActive(false); // Clear scanning state on timeout
+        setNfcScanningActive(false);
         trackEvent(PassportEvents.NFC_SCAN_FAILED, {
           error: 'timeout',
         });
         trackNfcEvent(PassportEvents.NFC_SCAN_FAILED, {
           error: 'timeout',
         });
         logNFCEvent('warn', 'scan_timeout', {
           ...baseContext,
           stage: 'timeout',
         });
         openErrorModal('Scan timed out. Please try again.');
         setIsNfcSheetOpen(false);
         logNFCEvent('info', 'sheet_close', {
           ...baseContext,
           stage: 'ui',
         });
-      }, 30000);
+      };
+
+      // Mark NFC scanning as active to prevent analytics flush interference
+      setNfcScanningActive(true);
+
+      if (scanTimeoutRef.current) {
+        clearTimeout(scanTimeoutRef.current);
+      }
+      scanTimeoutRef.current = setTimeout(onScanTimeout, 30000);
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b26aca0 and 70d31f6.

📒 Files selected for processing (13)
  • app/android/app/build.gradle (1 hunks)
  • app/android/react-native-passport-reader/android/build.gradle (1 hunks)
  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (21 hunks)
  • app/ios/PassportReader.m (1 hunks)
  • app/ios/PassportReader.swift (7 hunks)
  • app/ios/Self.xcodeproj/project.pbxproj (2 hunks)
  • app/src/Sentry.ts (2 hunks)
  • app/src/Sentry.web.ts (2 hunks)
  • app/src/screens/document/DocumentNFCScanScreen.tsx (16 hunks)
  • app/src/types/react-native-passport-reader.d.ts (2 hunks)
  • app/src/utils/nfcScanner.ts (5 hunks)
  • app/src/utils/passportReader.ts (3 hunks)
  • app/tests/utils/nfcScanner.test.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
app/android/**/*

⚙️ CodeRabbit configuration file

app/android/**/*: Review Android-specific code for:

  • Platform-specific implementations
  • Performance considerations
  • Security best practices for mobile

Files:

  • app/android/react-native-passport-reader/android/build.gradle
  • app/android/app/build.gradle
  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
app/ios/**/*

⚙️ CodeRabbit configuration file

app/ios/**/*: Review iOS-specific code for:

  • Platform-specific implementations
  • Performance considerations
  • Security best practices for mobile

Files:

  • app/ios/PassportReader.m
  • app/ios/PassportReader.swift
  • app/ios/Self.xcodeproj/project.pbxproj
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/technical-specification.mdc)

**/*.{ts,tsx}: Define IdentityCommitment with fields: commitment (Poseidon hash), nullifier (domain-separated), timestamp (UTC number), version (circuit version), documentType ('passport' | 'eu_id_card')
Define DSCKeyCommitment with fields: publicKeyHash (Poseidon hash), certificateChain (hashes), revocationStatus (boolean), issuer (country code)
Define VerificationConfig with fields: circuitVersion (semver), complianceRules array, timeWindow (seconds, 24h), clockDrift (±5 min), trustAnchors, revocationRoots, timeSource (NTP), nullifierScope (domain separation)

Files:

  • app/src/utils/nfcScanner.ts
  • app/src/utils/passportReader.ts
  • app/src/types/react-native-passport-reader.d.ts
  • app/src/screens/document/DocumentNFCScanScreen.tsx
  • app/src/Sentry.web.ts
  • app/src/Sentry.ts
  • app/tests/utils/nfcScanner.test.ts
app/src/**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

app/src/**/*.{ts,tsx,js,jsx}: Review React Native TypeScript code for:

  • Component architecture and reusability
  • State management patterns
  • Performance optimizations
  • TypeScript type safety
  • React hooks usage and dependencies
  • Navigation patterns

Files:

  • app/src/utils/nfcScanner.ts
  • app/src/utils/passportReader.ts
  • app/src/types/react-native-passport-reader.d.ts
  • app/src/screens/document/DocumentNFCScanScreen.tsx
  • app/src/Sentry.web.ts
  • app/src/Sentry.ts
**/*.{test,spec}.{ts,js,tsx,jsx}

⚙️ CodeRabbit configuration file

**/*.{test,spec}.{ts,js,tsx,jsx}: Review test files for:

  • Test coverage completeness
  • Test case quality and edge cases
  • Mock usage appropriateness
  • Test readability and maintainability

Files:

  • app/tests/utils/nfcScanner.test.ts
🧠 Learnings (12)
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to native/android/**/*.{kt,kts} : Android NFC: implement RNPassportReaderModule in Kotlin

Applied to files:

  • app/android/react-native-passport-reader/android/build.gradle
  • app/src/utils/nfcScanner.ts
  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
  • app/ios/PassportReader.swift
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to native/ios/**/*.{swift} : iOS NFC: implement custom PassportReader as a Swift module

Applied to files:

  • app/ios/PassportReader.m
  • app/src/utils/nfcScanner.ts
  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
  • app/ios/PassportReader.swift
📚 Learning: 2025-08-29T15:31:15.924Z
Learnt from: CR
PR: selfxyz/self#0
File: packages/mobile-sdk-alpha/AGENTS.md:0-0
Timestamp: 2025-08-29T15:31:15.924Z
Learning: Applies to packages/mobile-sdk-alpha/{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Ensure parseNFCResponse() works with representative, synthetic NFC data

Applied to files:

  • app/src/utils/nfcScanner.ts
  • app/src/screens/document/DocumentNFCScanScreen.tsx
  • app/tests/utils/nfcScanner.test.ts
📚 Learning: 2025-08-29T15:31:15.924Z
Learnt from: CR
PR: selfxyz/self#0
File: packages/mobile-sdk-alpha/AGENTS.md:0-0
Timestamp: 2025-08-29T15:31:15.924Z
Learning: Applies to packages/mobile-sdk-alpha/{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Test isPassportDataValid() with realistic synthetic passport data (never real user data)

Applied to files:

  • app/src/utils/passportReader.ts
  • app/tests/utils/nfcScanner.test.ts
📚 Learning: 2025-08-29T15:30:12.210Z
Learnt from: CR
PR: selfxyz/self#0
File: app/AGENTS.md:0-0
Timestamp: 2025-08-29T15:30:12.210Z
Learning: Test NFC functionality when applicable

Applied to files:

  • app/src/screens/document/DocumentNFCScanScreen.tsx
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Support MRZ-derived keys, CAN, PACE, and BAC fallback for NFC authentication

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Establish NFC secure channels using PACE/BAC

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to noir/crates/dg1/src/dg1/dg1.nr : Document verification processing using ICAO standards and DSC verification with multiple signature algorithms in dg1.nr

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Passport verification workflow: NFC data extraction → MRZ validation → DSC verification → Register proof → compliance via ZK → attestation

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
📚 Learning: 2025-08-02T23:53:45.928Z
Learnt from: transphorm
PR: selfxyz/self#823
File: app/ios/Self.xcodeproj/project.pbxproj:320-332
Timestamp: 2025-08-02T23:53:45.928Z
Learning: When reviewing autogenerated scripts in Xcode project files (like React Native Firebase's embedded shell scripts), avoid suggesting edits since these are regenerated during pod install and cannot be manually modified by users.

Applied to files:

  • app/ios/Self.xcodeproj/project.pbxproj
📚 Learning: 2025-08-29T15:31:15.924Z
Learnt from: CR
PR: selfxyz/self#0
File: packages/mobile-sdk-alpha/AGENTS.md:0-0
Timestamp: 2025-08-29T15:31:15.924Z
Learning: Applies to packages/mobile-sdk-alpha/{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Verify extractMRZInfo() using published sample MRZ strings (e.g., ICAO examples)

Applied to files:

  • app/tests/utils/nfcScanner.test.ts
📚 Learning: 2025-08-29T15:31:15.924Z
Learnt from: CR
PR: selfxyz/self#0
File: packages/mobile-sdk-alpha/AGENTS.md:0-0
Timestamp: 2025-08-29T15:31:15.924Z
Learning: Applies to packages/mobile-sdk-alpha/{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Never use real user PII in tests; use only synthetic, anonymized, or approved test vectors

Applied to files:

  • app/tests/utils/nfcScanner.test.ts
🧬 Code graph analysis (7)
app/ios/PassportReader.m (1)
app/src/utils/cameraScanner.ts (2)
  • useNavigationStore (7-62)
  • mrzInfo (35-56)
app/src/utils/nfcScanner.ts (2)
app/src/Sentry.ts (2)
  • logNFCEvent (131-179)
  • NFCScanContext (18-24)
app/src/mocks/react-native-passport-reader.ts (2)
  • reset (29-32)
  • PassportReader (8-28)
app/src/screens/document/DocumentNFCScanScreen.tsx (2)
app/src/Sentry.ts (1)
  • logNFCEvent (131-179)
app/src/utils/utils.ts (1)
  • sanitizeErrorMessage (23-31)
app/src/Sentry.web.ts (1)
app/src/Sentry.ts (3)
  • NFCScanContext (18-24)
  • logNFCEvent (131-179)
  • isSentryDisabled (129-129)
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (1)
app/ios/PassportReader.swift (1)
  • logNfc (54-81)
app/ios/PassportReader.swift (1)
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (1)
  • logNfc (955-988)
app/src/Sentry.ts (1)
app/src/Sentry.web.ts (3)
  • NFCScanContext (17-23)
  • logNFCEvent (123-171)
  • isSentryDisabled (121-121)
⏰ Context from checks skipped due to timeout of 300000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: build-ios
  • GitHub Check: build-android
  • GitHub Check: test
  • GitHub Check: e2e-ios
  • GitHub Check: analyze-android
  • GitHub Check: analyze-ios
🔇 Additional comments (11)
app/src/Sentry.web.ts (3)

7-7: LGTM: addBreadcrumb import is appropriate for NFC breadcrumbs.


14-14: LGTM: withScope is correctly used for scoped error capture.


17-23: PII minimization — remove userId from NFCScanContext or replace with a one-way hash
Remove the optional userId from app/src/Sentry.web.ts (lines 17–23) or require a caller-provided one-way hash/anonymous id; verify no logging/telemetry paths record raw userId.

app/ios/PassportReader.swift (2)

162-164: Good: session-scoped start breadcrumb aligns with Android.

Session assignment and scan_start logging look correct.


352-359: Good: success/error Sentry capture provides end-of-flow signal.

Consistent with the structured logging strategy.

app/src/utils/passportReader.ts (1)

47-74: iOS sessionId plumbing is correct and normalized.

Forwarding sessionId to scanPassport and normalizing the JSON response looks good. This should keep Sentry/NFC logs correlated across the session.

app/src/types/react-native-passport-reader.d.ts (1)

13-14: API surface alignment looks good.

sessionId?: string on ScanOptions and required sessionId: string on scanPassport(...) match the platform behavior you implemented (iOS requires, Android optional with default on JS).

Also applies to: 31-32

app/ios/PassportReader.m (1)

23-35: Bridge signature updated correctly.

Adding sessionId:(NSString *)sessionId before resolve/reject aligns with the JS invocation order you implemented.

app/src/screens/document/DocumentNFCScanScreen.tsx (1)

317-329: Session-scoped logging and plumbing look consistent.

Passing sessionId: sessionIdRef.current into scan(...) and emitting scan_success with duration metadata is coherent with the structured logging approach.

Also applies to: 347-355

app/src/utils/nfcScanner.ts (1)

56-63: Reduce telemetry noise & PII risk: downgrade module_unavailable to warn and emit a single error

module_unavailable is an operational condition — logging it as 'error' then letting the top-level catch also emit 'scan_failed' doubles error signals and can surface unnecessary PII. Change module_unavailable to 'warn' and gate the top-level 'scan_failed' for the unavailability sentinel so only one actionable error is recorded.

-    logNFCEvent('error', 'module_unavailable', {
+    logNFCEvent('warn', 'module_unavailable', {
      ...context,
      stage: 'init',
    });

Apply same change at app/src/utils/nfcScanner.ts (also applies to lines: 63-64, 65-79, 92-96, 117-120).

Optional: add a small classifyNFCError helper that maps errors to structured error_code values (unavailable, permission_denied, tag_removed, timeout) and emit a single structured 'scan_failed' when appropriate.

app/tests/utils/nfcScanner.test.ts (1)

141-142: LGTM: tests reflect the updated signature and session threading.

Inputs include sessionId, and expectations pass it through correctly. No PII in test vectors; MRZ uses public ICAO-style samples.

Also applies to: 176-177, 192-193, 208-208, 240-241

apply plugin: "org.jetbrains.kotlin.android"
apply plugin: 'kotlin-android'
apply plugin: 'com.google.gms.google-services'
apply from: "../../../node_modules/@sentry/react-native/sentry.gradle"
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Guard Sentry Gradle script to avoid CI breakage and accidental symbol/sourcemap uploads

Apply only if the script exists and DSN is set. This prevents noisy tasks on debug/PR builds and failures when node_modules aren’t present.

-apply from: "../../../node_modules/@sentry/react-native/sentry.gradle"
+def sentryGradle = file("../../../node_modules/@sentry/react-native/sentry.gradle")
+if (sentryGradle.exists() && System.getenv("SENTRY_DSN")) {
+  apply from: sentryGradle
+}

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "PWD: $(pwd)"
echo "---- app/android/app/build.gradle (first 120 lines) ----"
if [ -f app/android/app/build.gradle ]; then
  sed -n '1,120p' app/android/app/build.gradle || true
else
  echo "MISSING: app/android/app/build.gradle"
fi

echo
echo "---- grep for sentry.gradle references ----"
rg -n --hidden -S "@sentry/react-native/sentry.gradle" -g '!*node_modules*' -C3 || true

echo
echo "---- node_modules/@sentry/react-native/sentry.gradle exists? ----"
if [ -f node_modules/@sentry/react-native/sentry.gradle ]; then
  echo "FOUND: node_modules/@sentry/react-native/sentry.gradle"
  sed -n '1,80p' node_modules/@sentry/react-native/sentry.gradle || true
else
  echo "NOT FOUND: node_modules/@sentry/react-native/sentry.gradle"
fi

echo
echo "---- android/sentry.properties exists? ----"
if [ -f android/sentry.properties ]; then
  echo "FOUND: android/sentry.properties"
  sed -n '1,200p' android/sentry.properties || true
else
  echo "NOT FOUND: android/sentry.properties"
fi

echo
echo "---- search for SENTRY_* env var usages in repo (exclude node_modules) ----"
rg -n --hidden -S 'SENTRY_AUTH_TOKEN|SENTRY_DSN|SENTRY_PROPERTIES|SENTRY_DISABLE_AUTO_UPLOAD' -g '!*node_modules*' -C2 || true

echo
echo "---- search for Sentry.init in JS/TS (exclude node_modules) ----"
rg -n --hidden -S 'Sentry\\.init' -g '!*node_modules*' -C2 || true

echo
echo "---- search for any sentry.properties filenames in repo (exclude node_modules) ----"
rg -n --hidden -S 'sentry.properties' -g '!*node_modules*' -C2 || true

echo
echo "Done."

Length of output: 5852


Guard Sentry Gradle script to avoid CI breakage and accidental symbol/sourcemap uploads

app/android/app/build.gradle applies "../../../node_modules/@sentry/react-native/sentry.gradle" unguarded; node_modules may be missing in CI/PRs and this will fail the Gradle build — apply only when the script exists and SENTRY_DSN is set.

File: app/android/app/build.gradle (around line 6)

-apply from: "../../../node_modules/@sentry/react-native/sentry.gradle"
+def sentryGradle = file("../../../node_modules/@sentry/react-native/sentry.gradle")
+if (sentryGradle.exists() && System.getenv("SENTRY_DSN")) {
+  apply from: sentryGradle
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
apply from: "../../../node_modules/@sentry/react-native/sentry.gradle"
def sentryGradle = file("../../../node_modules/@sentry/react-native/sentry.gradle")
if (sentryGradle.exists() && System.getenv("SENTRY_DSN")) {
apply from: sentryGradle
}
🤖 Prompt for AI Agents
In app/android/app/build.gradle around line 6, the unguarded apply of
"../../../node_modules/@sentry/react-native/sentry.gradle" can fail in CI/PRs
when node_modules is absent or SENTRY is not configured; modify the file to
conditionally apply the Sentry Gradle script only when the script file exists
and the SENTRY_DSN (or equivalent Sentry env var) is set, i.e., check for the
existence of the node_modules sentry.gradle path and verify
System.getenv("SENTRY_DSN") (or project property) is non-empty before calling
apply from.

Comment on lines +45 to +46
implementation "io.sentry:sentry-android:8.20.0"

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Avoid double-packaging Sentry; switch to compileOnly to prevent classpath/version conflicts

@sentry/react-native already pulls in io.sentry:sentry-android. Declaring it here as implementation risks duplicate classes or version skew. Use compileOnly so the app supplies the runtime.

-    implementation "io.sentry:sentry-android:8.20.0"
+    compileOnly "io.sentry:sentry-android:8.20.0"

Run to verify duplicates and RN Sentry versions:


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "Gradle refs to sentry-android:"
rg -nP '\bio\.sentry:sentry-android\b' -g '**/*.gradle'
echo
echo "package.json refs to @sentry/react-native:"
rg -n '"@sentry/react-native"' -g '**/package.json' -C2

Length of output: 511


Change Sentry Android dependency to compileOnly to avoid double‑packaging/version skew

app/android/react-native-passport-reader/android/build.gradle:45 currently has implementation "io.sentry:sentry-android:8.20.0" while package.json lists @sentry/[email protected] — @sentry/react-native ships the native Android SDK, so keeping an implementation dependency can duplicate classes or produce runtime version conflicts; switch to compileOnly (or remove the explicit dependency and align versions / adjust Sentry AGP autoInstallation). (github.com)

-    implementation "io.sentry:sentry-android:8.20.0"
+    compileOnly "io.sentry:sentry-android:8.20.0"

File: app/android/react-native-passport-reader/android/build.gradle:45

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
implementation "io.sentry:sentry-android:8.20.0"
compileOnly "io.sentry:sentry-android:8.20.0"
🤖 Prompt for AI Agents
In app/android/react-native-passport-reader/android/build.gradle around lines
45-46, the dependency implementation "io.sentry:sentry-android:8.20.0" conflicts
with @sentry/[email protected] (which already ships the native SDK);
change that implementation to compileOnly "io.sentry:sentry-android:8.20.0" (or
remove the explicit dependency entirely) to avoid double-packaging and version
skew, and ensure the project relies on the native SDK provided by
@sentry/react-native (or align versions / disable Sentry AGP auto-installation
if you choose to keep an explicit native dependency).

Comment on lines 621 to +624
val dg14Hash = if (chipAuthSucceeded) digest.digest(dg14Encoded) else ByteArray(0)
val dg1Hash = digest.digest(dg1File.encoded)
val dg2Hash = digest.digest(dg2File.encoded)

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Crash risk: dg2File is never initialized but its hash is computed.

DG2 read is commented out above, yet dg2Hash is computed from dg2File.encoded. This will throw UninitializedPropertyAccessException at runtime.

Minimal fix:

-                val dg2Hash = digest.digest(dg2File.encoded)
+                val dg2Hash = if (::dg2File.isInitialized) digest.digest(dg2File.encoded) else ByteArray(0)

Optionally reinstate DG2 reading if you intend to validate it.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
val dg14Hash = if (chipAuthSucceeded) digest.digest(dg14Encoded) else ByteArray(0)
val dg1Hash = digest.digest(dg1File.encoded)
val dg2Hash = digest.digest(dg2File.encoded)
val dg14Hash = if (chipAuthSucceeded) digest.digest(dg14Encoded) else ByteArray(0)
val dg1Hash = digest.digest(dg1File.encoded)
val dg2Hash = if (::dg2File.isInitialized) digest.digest(dg2File.encoded) else ByteArray(0)
🤖 Prompt for AI Agents
In
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
around lines 621-624, the code computes dg2Hash from dg2File.encoded even though
dg2File may never be initialized (DG2 read was commented out), which will throw
UninitializedPropertyAccessException; fix by guarding access to dg2File (only
compute digest if dg2File was successfully read/initialized) or set dg2Hash to
an empty ByteArray/default value when DG2 is absent, or alternatively re-enable
the DG2 read logic above so dg2File is always initialized before computing its
hash. Ensure any branch you add keeps types consistent and preserves
chipAuthSucceeded logic for DG14.

Comment on lines +54 to +81
private func logNfc(level: SentryLevel, message: String, stage: String, useCANBool: Bool, sessionId: String, extras: [String: Any] = [:]) {
let data: [String: Any] = [
"session_id": sessionId,
"platform": "ios",
"scan_type": useCANBool ? "can" : "mrz",
"stage": stage
].merging(extras) { (_, new) in new }

if level == .error {
// For errors, capture a message (this will include all previous breadcrumbs)
SentrySDK.configureScope { scope in
scope.setTag(value: sessionId, key: "session_id")
scope.setTag(value: "ios", key: "platform")
scope.setTag(value: useCANBool ? "can" : "mrz", key: "scan_type")
scope.setTag(value: stage, key: "stage")
for (key, value) in extras {
scope.setExtra(value: value, key: key)
}
}
SentrySDK.capture(message: message)
} else {
// For info/warn, add as breadcrumb only
let breadcrumb = Breadcrumb(level: level, category: "nfc")
breadcrumb.message = message
breadcrumb.data = data.mapValues { "\($0)" }
SentrySDK.addBreadcrumb(breadcrumb)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use a temporary Sentry scope for errors to prevent tag/extra leakage across sessions.

configureScope mutates the global scope; the session_id/scan_type/stage and extras will persist beyond this event. Android correctly uses withScope.

-        if level == .error {
-            // For errors, capture a message (this will include all previous breadcrumbs)
-            SentrySDK.configureScope { scope in
-                scope.setTag(value: sessionId, key: "session_id")
-                scope.setTag(value: "ios", key: "platform")
-                scope.setTag(value: useCANBool ? "can" : "mrz", key: "scan_type")
-                scope.setTag(value: stage, key: "stage")
-                for (key, value) in extras {
-                    scope.setExtra(value: value, key: key)
-                }
-            }
-            SentrySDK.capture(message: message)
-        } else {
+        if level == .error {
+            // Capture with a temporary scope so tags/extras don't leak
+            SentrySDK.withScope { scope in
+                scope.setTag(value: sessionId, key: "session_id")
+                scope.setTag(value: "ios", key: "platform")
+                scope.setTag(value: useCANBool ? "can" : "mrz", key: "scan_type")
+                scope.setTag(value: stage, key: "stage")
+                for (key, value) in extras {
+                    scope.setExtra(value: value, key: key)
+                }
+                SentrySDK.capture(message: message)
+            }
+        } else {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private func logNfc(level: SentryLevel, message: String, stage: String, useCANBool: Bool, sessionId: String, extras: [String: Any] = [:]) {
let data: [String: Any] = [
"session_id": sessionId,
"platform": "ios",
"scan_type": useCANBool ? "can" : "mrz",
"stage": stage
].merging(extras) { (_, new) in new }
if level == .error {
// For errors, capture a message (this will include all previous breadcrumbs)
SentrySDK.configureScope { scope in
scope.setTag(value: sessionId, key: "session_id")
scope.setTag(value: "ios", key: "platform")
scope.setTag(value: useCANBool ? "can" : "mrz", key: "scan_type")
scope.setTag(value: stage, key: "stage")
for (key, value) in extras {
scope.setExtra(value: value, key: key)
}
}
SentrySDK.capture(message: message)
} else {
// For info/warn, add as breadcrumb only
let breadcrumb = Breadcrumb(level: level, category: "nfc")
breadcrumb.message = message
breadcrumb.data = data.mapValues { "\($0)" }
SentrySDK.addBreadcrumb(breadcrumb)
}
}
private func logNfc(level: SentryLevel, message: String, stage: String, useCANBool: Bool, sessionId: String, extras: [String: Any] = [:]) {
let data: [String: Any] = [
"session_id": sessionId,
"platform": "ios",
"scan_type": useCANBool ? "can" : "mrz",
"stage": stage
].merging(extras) { (_, new) in new }
if level == .error {
// Capture with a temporary scope so tags/extras don't leak
SentrySDK.withScope { scope in
scope.setTag(value: sessionId, key: "session_id")
scope.setTag(value: "ios", key: "platform")
scope.setTag(value: useCANBool ? "can" : "mrz", key: "scan_type")
scope.setTag(value: stage, key: "stage")
for (key, value) in extras {
scope.setExtra(value: value, key: key)
}
SentrySDK.capture(message: message)
}
} else {
// For info/warn, add as breadcrumb only
let breadcrumb = Breadcrumb(level: level, category: "nfc")
breadcrumb.message = message
breadcrumb.data = data.mapValues { "\($0)" }
SentrySDK.addBreadcrumb(breadcrumb)
}
}
🤖 Prompt for AI Agents
In app/ios/PassportReader.swift around lines 54 to 81, the code uses
SentrySDK.configureScope which mutates the global scope and can leak
session_id/scan_type/stage and extras across events; change this to use a
temporary scope via SentrySDK.withScope (or the equivalent API) so tags and
extras are applied only to this single error capture, set the tags and extras
inside the withScope closure identical to the current configureScope logic, then
call SentrySDK.capture(message:) from within that closure so the metadata does
not persist globally.

Comment on lines +788 to +791
OTHER_LDFLAGS = (
"$(inherited)",
" ",
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove stray empty linker flag to avoid build/link instability.

OTHER_LDFLAGS includes a lone " " entry. Some Xcode/ld versions treat this as an invalid flag and can fail or produce hard-to-diagnose warnings.

Apply in both Debug and Release:

-                OTHER_LDFLAGS = (
-                    "$(inherited)",
-                    " ",
-                );
+                OTHER_LDFLAGS = (
+                    "$(inherited)",
+                );

Also applies to: 881-884

🤖 Prompt for AI Agents
In app/ios/Self.xcodeproj/project.pbxproj around lines 788-791 (and also apply
same change at 881-884), OTHER_LDFLAGS contains a stray entry of a single space
(" ") which can be treated as an invalid linker flag; remove that lone " " entry
from the OTHER_LDFLAGS array for both Debug and Release configurations so only
valid flags (e.g. "$(inherited)" and any real flags) remain, ensuring no extra
empty strings/whitespace entries are left in the lists.

Comment on lines +166 to 175
logNFCEvent(
'error',
'nfc_error_modal',
{
...baseContext,
stage: 'error',
},
{ message: sanitizeErrorMessage(message) },
);
showModal({
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Sanitize console errors to avoid leaking document data in device logs.

You already sanitize before sending analytics/Sentry. Mirror that for console output to prevent PII/MRZ appearing in device logs (especially on user reports).

Apply this diff:

-      logNFCEvent(
+      logNFCEvent(
         'error',
         'nfc_error_modal',
         {
           ...baseContext,
           stage: 'error',
         },
         { message: sanitizeErrorMessage(message) },
       );
-          console.error('Passport Parsed Failed:', e);
-          const errMsg = sanitizeErrorMessage(
-            e instanceof Error ? e.message : String(e),
-          );
+          const errMsg = sanitizeErrorMessage(
+            e instanceof Error ? e.message : String(e),
+          );
+          console.error('Passport Parsed Failed:', errMsg);
-        console.error('NFC Scan Unsuccessful:', e);
-        const message = e instanceof Error ? e.message : String(e);
-        const sanitized = sanitizeErrorMessage(message);
+        const message = e instanceof Error ? e.message : String(e);
+        const sanitized = sanitizeErrorMessage(message);
+        console.error('NFC Scan Unsuccessful:', sanitized);

Also applies to: 433-440, 454-457

🤖 Prompt for AI Agents
In app/src/screens/document/DocumentNFCScanScreen.tsx around lines 166-175 (and
similarly at 433-440 and 454-457), console output and modal payloads are
currently using the raw error message which can leak PII/MRZ; update those calls
to pass the sanitized string returned from sanitizeErrorMessage(message) instead
of the raw message. Specifically, replace any
console.log/console.error/console.warn and any showModal or UI error props that
use message with sanitizedMessage = sanitizeErrorMessage(message) and use
sanitizedMessage for device logs and modal content while keeping existing
analytics/Sentry usage unchanged.

Comment on lines 123 to 171
export const logNFCEvent = (
level: 'info' | 'warn' | 'error',
message: string,
context: NFCScanContext,
extra?: Record<string, unknown>,
) => {
if (isSentryDisabled) {
return;
}

// Prepare data for breadcrumbs and messages
const data = {
session_id: context.sessionId,
platform: context.platform,
scan_type: context.scanType,
stage: context.stage,
user_id: context.userId,
...extra,
};

if (level === 'error') {
// For errors, capture a message (this will include all previous breadcrumbs)
withScope(scope => {
scope.setLevel('error');
scope.setTag('session_id', context.sessionId);
scope.setTag('platform', context.platform);
scope.setTag('scan_type', context.scanType);
scope.setTag('stage', context.stage);
if (context.userId) {
scope.setUser({ id: context.userId });
}
if (extra) {
Object.entries(extra).forEach(([key, value]) => {
scope.setExtra(key, value);
});
}
sentryCaptureMessage(message);
});
} else {
// For info/warn, add as breadcrumb only
addBreadcrumb({
message,
level: level === 'warn' ? 'warning' : 'info',
category: 'nfc',
data,
timestamp: Date.now() / 1000,
});
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Do not log sensitive NFC data (MRZ/CAN/keys); sanitize extras and drop user identifiers from telemetry

Current code may forward raw MRZ/CAN or session secrets via extra and includes user identifiers. This is a privacy/security risk. Sanitize extras and avoid setting user data.

 export const logNFCEvent = (
@@
 ) => {
   if (isSentryDisabled) {
     return;
   }
 
-  // Prepare data for breadcrumbs and messages
-  const data = {
+  // Prepare data for breadcrumbs and messages (sanitized; no PII/MRZ/CAN)
+  const sanitizedExtra = sanitizeNfcExtra(extra);
+  const data = {
     session_id: context.sessionId,
     platform: context.platform,
     scan_type: context.scanType,
     stage: context.stage,
-    user_id: context.userId,
-    ...extra,
+    ...sanitizedExtra,
   };
 
   if (level === 'error') {
     // For errors, capture a message (this will include all previous breadcrumbs)
     withScope(scope => {
       scope.setLevel('error');
       scope.setTag('session_id', context.sessionId);
       scope.setTag('platform', context.platform);
       scope.setTag('scan_type', context.scanType);
       scope.setTag('stage', context.stage);
-      if (context.userId) {
-        scope.setUser({ id: context.userId });
-      }
-      if (extra) {
-        Object.entries(extra).forEach(([key, value]) => {
-          scope.setExtra(key, value);
-        });
-      }
+      if (sanitizedExtra) {
+        Object.entries(sanitizedExtra).forEach(([key, value]) => {
+          scope.setExtra(key, value);
+        });
+      }
       sentryCaptureMessage(message);
     });
   } else {
     // For info/warn, add as breadcrumb only
     addBreadcrumb({
       message,
       level: level === 'warn' ? 'warning' : 'info',
       category: 'nfc',
       data,
       timestamp: Date.now() / 1000,
     });
   }
 };

Add helper (same file or shared util):

// Deny-list obvious NFC secrets/identifiers.
const SENSITIVE_NFC_KEYS = new Set([
  'mrz','can','bac','pacekey','kenc','kmac','kseed','docnumber','passportnumber','chipid','nonce'
]);

export function sanitizeNfcExtra(extra?: Record<string, unknown>) {
  if (!extra) return undefined;
  const out: Record<string, unknown> = {};
  for (const [k, v] of Object.entries(extra)) {
    if (!SENSITIVE_NFC_KEYS.has(k.toLowerCase())) out[k] = v;
  }
  return Object.keys(out).length ? out : undefined;
}

Comment on lines +43 to 45
sessionId: string;
userId?: string;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate sessionId early (non-empty) to preserve traceability and prevent malformed events.

Even though sessionId is typed required, runtime calls can still pass '' or whitespace. Add a guard before logging/scan to fail fast with a clear message.

 export const scan = async (inputs: Inputs) => {
   await configureNfcAnalytics();

+  if (!inputs.sessionId || inputs.sessionId.trim().length === 0) {
+    // Do not log this—missing session breaks correlation and may leak into breadcrumbs.
+    throw new TypeError('NFC scan requires a non-empty sessionId');
+  }
+
   const baseContext = {
     sessionId: inputs.sessionId,
     userId: inputs.userId,
     platform: Platform.OS as 'ios' | 'android',
     scanType: inputs.useCan ? 'can' : 'mrz',
   } as const;

Also applies to: 53-64

🤖 Prompt for AI Agents
In app/src/utils/nfcScanner.ts around lines 43-45 (and similarly for lines
53-64), add an early runtime guard that validates sessionId is non-empty after
trimming (reject '', whitespace-only or null/undefined) before any logging or
scanning occurs; if invalid, log a clear error including the invalid value and
either throw an Error or return a rejected Promise (match existing function
async/sync pattern) so the caller fails fast and malformed events are not
emitted.

Copy link
Contributor

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (1)

569-573: Capture errors to Sentry for actionable diagnostics

You added Sentry breadcrumbs but do not capture errors on failure paths, losing the breadcrumb trail. Capture error events with context.

             } catch (e: Exception) {
                 logAnalyticsError("nfc_reading_failed", "NFC reading failed: ${e.message}")
+                logNfc(
+                    SentryLevel.ERROR,
+                    "scan_failed",
+                    "error",
+                    mapOf("error_type" to e.javaClass.simpleName, "message" to (e.message ?: ""))
+                )
                 eventMessageEmitter(Messages.RESET)
                 return e
             }
             } catch (e: Exception) {
                 logAnalyticsError("nfc_chip_auth_failed", "Chip authentication failed: ${e.message}")
                 Log.w(TAG, e)
+                logNfc(
+                    SentryLevel.ERROR,
+                    "chip_auth_failed",
+                    "chip_auth",
+                    mapOf("error_type" to e.javaClass.simpleName, "message" to (e.message ?: ""))
+                )
             }
                     } else {
                         logAnalyticsError("nfc_signature_verification_failed", "Signature verification failed")
                         logAnalyticsError("nfc_passive_auth_failed", "Signature verification failed")
+                        logNfc(
+                            SentryLevel.ERROR,
+                            "passive_auth_failed",
+                            "verify",
+                            mapOf("reason" to "signature_verification_failed")
+                        )
                     }
                 } else {
                     logAnalyticsError("nfc_passive_auth_failed", "Data group hashes do not match")
+                    logNfc(
+                        SentryLevel.ERROR,
+                        "passive_auth_failed",
+                        "verify",
+                        mapOf("reason" to "hash_mismatch")
+                    )
                 }
             if (result != null) {
                 // Log.w(TAG, exceptionStack(result))
                 if (result is IOException) {
                     logAnalyticsError("nfc_scan_failed_disconnect", "Lost connection to chip on card")
                     scanPromise?.reject("E_SCAN_FAILED_DISCONNECT", "Lost connection to chip on card")
                 } else {
                     logAnalyticsError("nfc_scan_failed", "Scan failed: ${result.message}")
                     scanPromise?.reject("E_SCAN_FAILED", result)
                 }
+                logNfc(
+                    SentryLevel.ERROR,
+                    "scan_failed",
+                    "error",
+                    mapOf("error_type" to result.javaClass.simpleName, "message" to (result.message ?: ""))
+                )
 
                 apduLogger.clearContext()

Also applies to: 603-605, 723-725, 728-729, 741-748

♻️ Duplicate comments (2)
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (1)

621-624: Crash risk: dg2File used before initialization

DG2 reading is commented out above, yet dg2Hash is computed from dg2File.encoded. This will throw UninitializedPropertyAccessException at runtime.

Minimal guard:

-                val dg2Hash = digest.digest(dg2File.encoded)
+                val dg2Hash = if (::dg2File.isInitialized) digest.digest(dg2File.encoded) else ByteArray(0)

Optionally also skip computing dg2Hash entirely if DG2 isn’t read. Ensure any comparisons don’t assume DG2 presence.

app/ios/PassportReader.swift (1)

62-74: Use a temporary Sentry scope for errors to avoid tag/extra leakage

configureScope mutates the global scope and can leak session-scoped tags/extras across unrelated events. Use withScope for error captures.

-        if level == .error {
-            // For errors, capture a message (this will include all previous breadcrumbs)
-            SentrySDK.configureScope { scope in
-                scope.setTag(value: sessionId, key: "session_id")
-                scope.setTag(value: "ios", key: "platform")
-                scope.setTag(value: useCANBool ? "can" : "mrz", key: "scan_type")
-                scope.setTag(value: stage, key: "stage")
-                for (key, value) in extras {
-                    scope.setExtra(value: value, key: key)
-                }
-            }
-            SentrySDK.capture(message: message)
-        } else {
+        if level == .error {
+            // Capture with a temporary scope so tags/extras don't leak
+            SentrySDK.withScope { scope in
+                scope.setTag(value: sessionId, key: "session_id")
+                scope.setTag(value: "ios", key: "platform")
+                scope.setTag(value: useCANBool ? "can" : "mrz", key: "scan_type")
+                scope.setTag(value: stage, key: "stage")
+                for (key, value) in extras {
+                    scope.setExtra(value: value, key: key)
+                }
+                SentrySDK.capture(message: message)
+            }
+        } else {
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70d31f6 and d536aa2.

📒 Files selected for processing (2)
  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (21 hunks)
  • app/ios/PassportReader.swift (7 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
app/android/**/*

⚙️ CodeRabbit configuration file

app/android/**/*: Review Android-specific code for:

  • Platform-specific implementations
  • Performance considerations
  • Security best practices for mobile

Files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
app/ios/**/*

⚙️ CodeRabbit configuration file

app/ios/**/*: Review iOS-specific code for:

  • Platform-specific implementations
  • Performance considerations
  • Security best practices for mobile

Files:

  • app/ios/PassportReader.swift
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to native/android/**/*.{kt,kts} : Android NFC: implement RNPassportReaderModule in Kotlin
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to native/android/**/*.{kt,kts} : Android NFC: implement RNPassportReaderModule in Kotlin

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
  • app/ios/PassportReader.swift
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to native/ios/**/*.{swift} : iOS NFC: implement custom PassportReader as a Swift module

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
  • app/ios/PassportReader.swift
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Support MRZ-derived keys, CAN, PACE, and BAC fallback for NFC authentication

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Establish NFC secure channels using PACE/BAC

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to noir/crates/dg1/src/dg1/dg1.nr : Document verification processing using ICAO standards and DSC verification with multiple signature algorithms in dg1.nr

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Passport verification workflow: NFC data extraction → MRZ validation → DSC verification → Register proof → compliance via ZK → attestation

Applied to files:

  • app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
🧬 Code graph analysis (2)
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (1)
app/ios/PassportReader.swift (1)
  • logNfc (54-81)
app/ios/PassportReader.swift (2)
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt (1)
  • logNfc (955-988)
app/src/utils/nfcScanner.ts (5)
  • response (187-262)
  • setModalProofStep (81-114)
  • response (116-185)
  • setModalProofStep (14-47)
  • setModalProofStep (49-79)
⏰ Context from checks skipped due to timeout of 300000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: build-android
  • GitHub Check: build-ios
  • GitHub Check: test
  • GitHub Check: e2e-ios
  • GitHub Check: analyze-android

Comment on lines +206 to +218
currentSessionId = if (opts.hasKey("sessionId")) opts.getString("sessionId") else generateSessionId()

apduLogger.setContext("session_id", currentSessionId!!)

// Log scan start
logAnalyticsEvent("nfc_scan_started", mapOf(
"use_can" to (opts.getBoolean(PARAM_USE_CAN) ?: false),
"has_document_number" to (!opts.getString(PARAM_DOC_NUM).isNullOrEmpty()),
"has_can_number" to (!opts.getString(PARAM_CAN).isNullOrEmpty()),
"platform" to "android"
))


logNfc(SentryLevel.INFO, "scan_start", "start")
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Prevent NPE on sessionId and ensure accurate scan_type in initial breadcrumb

currentSessionId can be null if sessionId key exists but value is null, and the first logNfc call computes scan_type from this.opts before it's assigned, defaulting to "mrz" even when useCan=true.

Apply this reordering and null-safe assignment:

 @ReactMethod
 fun scan(opts: ReadableMap, promise: Promise) {
-        currentSessionId = if (opts.hasKey("sessionId")) opts.getString("sessionId") else generateSessionId()
-
-        apduLogger.setContext("session_id", currentSessionId!!)
+        // Store opts early so logNfc resolves scan_type correctly
+        this.opts = opts
+        val sessionId = (if (opts.hasKey("sessionId")) opts.getString("sessionId") else null) ?: generateSessionId()
+        currentSessionId = sessionId
+        apduLogger.setContext("session_id", sessionId)

         // Log scan start
         logAnalyticsEvent("nfc_scan_started", mapOf(
-            "use_can" to (opts.getBoolean(PARAM_USE_CAN) ?: false),
+            "use_can" to (if (opts.hasKey(PARAM_USE_CAN)) opts.getBoolean(PARAM_USE_CAN) else false),
             "has_document_number" to (!opts.getString(PARAM_DOC_NUM).isNullOrEmpty()),
             "has_can_number" to (!opts.getString(PARAM_CAN).isNullOrEmpty()),
             "platform" to "android"
         ))
 
         logNfc(SentryLevel.INFO, "scan_start", "start")
@@
-        this.opts = opts
         this.scanPromise = promise

Also applies to: 243-246

🤖 Prompt for AI Agents
In
app/android/react-native-passport-reader/android/src/main/java/io/tradle/nfc/RNPassportReaderModule.kt
around lines 206-218 (and similarly adjust lines 243-246), currentSessionId is
assigned unsafely which can be null if the "sessionId" key exists but its value
is null, and logNfc is called before currentSessionId is set causing scan_type
to be derived from opts incorrectly; fix by first computing a null-safe
sessionId: if opts.hasKey("sessionId") get the string and fall back to
generateSessionId() when null, assign to currentSessionId, set
apduLogger.setContext("session_id", currentSessionId!!), then compute scan_type
using the updated opts/use_can state and only after that call logAnalyticsEvent
and logNfc; apply the same null-safe assignment and call-order reorder at lines
243-246.

Comment on lines 355 to 358
} catch {
logNfc(level: .warning, message: "scan_failed", stage: "error", useCANBool: useCANBool, sessionId: sessionId, extras: ["error": error.localizedDescription])
reject("E_PASSPORT_READ", error.localizedDescription, error)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Log scan failures at error level (and include error_type)

Warning level won’t trigger Sentry event capture; use .error to preserve breadcrumbs with an event.

-        logNfc(level: .warning, message: "scan_failed", stage: "error", useCANBool: useCANBool, sessionId: sessionId, extras: ["error": error.localizedDescription])
+        logNfc(
+          level: .error,
+          message: "scan_failed",
+          stage: "error",
+          useCANBool: useCANBool,
+          sessionId: sessionId,
+          extras: ["error": error.localizedDescription, "error_type": String(describing: type(of: error))]
+        )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch {
logNfc(level: .warning, message: "scan_failed", stage: "error", useCANBool: useCANBool, sessionId: sessionId, extras: ["error": error.localizedDescription])
reject("E_PASSPORT_READ", error.localizedDescription, error)
}
} catch {
logNfc(
level: .error,
message: "scan_failed",
stage: "error",
useCANBool: useCANBool,
sessionId: sessionId,
extras: ["error": error.localizedDescription, "error_type": String(describing: type(of: error))]
)
reject("E_PASSPORT_READ", error.localizedDescription, error)
}
🤖 Prompt for AI Agents
In app/ios/PassportReader.swift around lines 355 to 358, change the scan failure
log to use .error (not .warning) so Sentry will capture an event, and add an
"error_type" field to the extras (e.g., error.localizedDescription or
String(describing: type(of: error))) so the log includes the concrete error
type; keep the reject call as-is but update the logNfc call parameters
accordingly.

* feat: add proof event logging

* refactor: unify sentry event logging

* fix types

* fix mock

* simplify

* code rabbit feedback
Copy link
Contributor

@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: 5

♻️ Duplicate comments (1)
app/src/Sentry.web.ts (1)

212-254: Mirror native fix: remove user identifiers and sanitize extras

Same PII risk as native: drop user_id from breadcrumb data, avoid scope.setUser, and sanitize context/extra before tagging/logging.

-  const { sessionId, userId, platform, stage, ...rest } = context;
-  const data = {
-    session_id: sessionId,
-    user_id: userId,
-    platform,
-    stage,
-    ...rest,
-    ...extra,
-  };
+  const { sessionId, userId, platform, stage, ...rest } = context;
+  const sanitizedRest = sanitizeContextData(rest);
+  const sanitizedExtra = sanitizeExtra(extra);
+  const data = {
+    session_id: sessionId,
+    platform,
+    stage,
+    ...sanitizedRest,
+    ...(sanitizedExtra || {}),
+  };
@@
-      Object.entries(rest).forEach(([key, value]) => {
+      Object.entries(sanitizedRest).forEach(([key, value]) => {
         const sanitizedKey = sanitizeTagKey(key);
         if (sanitizedKey) {
           const sanitizedValue = sanitizeTagValue(value);
           scope.setTag(sanitizedKey, sanitizedValue);
         }
       });
-      if (userId) {
-        scope.setUser({ id: userId });
-      }
-      if (extra) {
-        Object.entries(extra).forEach(([key, value]) => {
-          scope.setExtra(key, value);
-        });
-      }
+      if (sanitizedExtra) {
+        Object.entries(sanitizedExtra).forEach(([key, value]) => {
+          scope.setExtra(key, value);
+        });
+      }

Reuse the same sanitizeExtra/sanitizeContextData helpers as suggested for app/src/Sentry.ts.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d536aa2 and 55faac5.

📒 Files selected for processing (6)
  • app/src/Sentry.ts (2 hunks)
  • app/src/Sentry.web.ts (2 hunks)
  • app/src/utils/nfcScanner.ts (5 hunks)
  • app/src/utils/proving/provingMachine.ts (25 hunks)
  • app/tests/utils/proving/actorMock.ts (1 hunks)
  • common/src/utils/aadhaar/assets/dataInput.d.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/src/utils/nfcScanner.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/technical-specification.mdc)

**/*.{ts,tsx}: Define IdentityCommitment with fields: commitment (Poseidon hash), nullifier (domain-separated), timestamp (UTC number), version (circuit version), documentType ('passport' | 'eu_id_card')
Define DSCKeyCommitment with fields: publicKeyHash (Poseidon hash), certificateChain (hashes), revocationStatus (boolean), issuer (country code)
Define VerificationConfig with fields: circuitVersion (semver), complianceRules array, timeWindow (seconds, 24h), clockDrift (±5 min), trustAnchors, revocationRoots, timeSource (NTP), nullifierScope (domain separation)

Files:

  • common/src/utils/aadhaar/assets/dataInput.d.ts
  • app/tests/utils/proving/actorMock.ts
  • app/src/utils/proving/provingMachine.ts
  • app/src/Sentry.web.ts
  • app/src/Sentry.ts
common/src/**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

common/src/**/*.{ts,tsx,js,jsx}: Review shared utilities for:

  • Reusability and modular design
  • Type safety and error handling
  • Side-effect management
  • Documentation and naming clarity

Files:

  • common/src/utils/aadhaar/assets/dataInput.d.ts
app/src/**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

app/src/**/*.{ts,tsx,js,jsx}: Review React Native TypeScript code for:

  • Component architecture and reusability
  • State management patterns
  • Performance optimizations
  • TypeScript type safety
  • React hooks usage and dependencies
  • Navigation patterns

Files:

  • app/src/utils/proving/provingMachine.ts
  • app/src/Sentry.web.ts
  • app/src/Sentry.ts
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to native/android/**/*.{kt,kts} : Android NFC: implement RNPassportReaderModule in Kotlin
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Passport verification workflow: NFC data extraction → MRZ validation → DSC verification → Register proof → compliance via ZK → attestation

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Applies to **/*.{ts,tsx} : Define IdentityCommitment with fields: commitment (Poseidon hash), nullifier (domain-separated), timestamp (UTC number), version (circuit version), documentType ('passport' | 'eu_id_card')

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to contracts/contracts/IdentityVerificationHubImplV2.sol : Identity Verification Hub: manage multi-step verification for passports and EU ID cards, handle document attestation via ZK proofs, and implement E-PASSPORT and EU_ID_CARD paths in IdentityVerificationHubImplV2.sol

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-29T15:31:15.924Z
Learnt from: CR
PR: selfxyz/self#0
File: packages/mobile-sdk-alpha/AGENTS.md:0-0
Timestamp: 2025-08-29T15:31:15.924Z
Learning: Applies to packages/mobile-sdk-alpha/{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Test isPassportDataValid() with realistic synthetic passport data (never real user data)

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to src/**/*.{tsx} : Implement comprehensive error boundaries in React components

Applied to files:

  • app/src/Sentry.web.ts
  • app/src/Sentry.ts
🧬 Code graph analysis (5)
common/src/utils/aadhaar/assets/dataInput.d.ts (1)
common/src/utils/aadhaar/assets/dataInput.ts (1)
  • testQRData (1-4)
app/tests/utils/proving/actorMock.ts (1)
app/src/screens/MainScreen.tsx (1)
  • subscription (135-137)
app/src/utils/proving/provingMachine.ts (7)
common/src/utils/types.ts (2)
  • DocumentCategory (16-16)
  • PassportData (35-50)
packages/mobile-sdk-alpha/src/stores/protocolStore.ts (1)
  • useProtocolStore (63-321)
app/src/stores/selfAppStore.tsx (1)
  • useSelfAppStore (27-160)
common/src/utils/circuits/registerInputs.ts (2)
  • generateTEEInputsRegister (110-121)
  • generateTEEInputsDSC (27-37)
app/src/utils/proving/provingInputs.ts (1)
  • generateTEEInputsDisclose (10-31)
common/src/utils/proving.ts (2)
  • encryptAES256GCM (47-60)
  • getPayload (62-97)
app/src/Sentry.ts (2)
  • logProofEvent (271-276)
  • ProofContext (96-99)
app/src/Sentry.web.ts (1)
app/src/Sentry.ts (6)
  • NFCScanContext (92-94)
  • ProofContext (96-99)
  • logEvent (209-262)
  • isSentryDisabled (204-204)
  • logNFCEvent (264-269)
  • logProofEvent (271-276)
app/src/Sentry.ts (1)
app/src/Sentry.web.ts (6)
  • NFCScanContext (91-93)
  • ProofContext (95-98)
  • logEvent (201-254)
  • isSentryDisabled (196-196)
  • logNFCEvent (256-261)
  • logProofEvent (263-268)
🔇 Additional comments (1)
app/src/Sentry.ts (1)

165-167: Sentry Session Replay supported — confirm @sentry/react-native ≥ 6.5.0

Session Replay options (replaysSessionSampleRate, replaysOnErrorSampleRate) are supported as of Sep 12, 2025 (requires SDK ≥ 6.5.0). Check package.json / lockfile to confirm your @sentry/react-native version; if below 6.5.0, upgrade or remove these options. For production, keep sampling low and enforce user consent / PII controls.

Comment on lines +220 to +261
const { sessionId, userId, platform, stage, ...rest } = context;
const data = {
session_id: sessionId,
user_id: userId,
platform,
stage,
...rest,
...extra,
};

if (level === 'error') {
withScope(scope => {
scope.setLevel('error');
scope.setTag('session_id', sessionId);
scope.setTag('platform', platform);
scope.setTag('stage', stage);
Object.entries(rest).forEach(([key, value]) => {
const sanitizedKey = sanitizeTagKey(key);
if (sanitizedKey) {
const sanitizedValue = sanitizeTagValue(value);
scope.setTag(sanitizedKey, sanitizedValue);
}
});
if (userId) {
scope.setUser({ id: userId });
}
if (extra) {
Object.entries(extra).forEach(([key, value]) => {
scope.setExtra(key, value);
});
}
sentryCaptureMessage(message);
});
} else {
addBreadcrumb({
message,
level: level === 'warn' ? 'warning' : 'info',
category,
data,
timestamp: Date.now() / 1000,
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Drop user identifiers and sanitize extras before logging

Breadcrumb data currently includes user_id and unsanitized extras, contradicting “Disable PII” and risking MRZ/CAN leakage. Remove user_id, avoid scope.setUser, and sanitize context/extra.

-  const { sessionId, userId, platform, stage, ...rest } = context;
-  const data = {
-    session_id: sessionId,
-    user_id: userId,
-    platform,
-    stage,
-    ...rest,
-    ...extra,
-  };
+  const { sessionId, userId, platform, stage, ...rest } = context;
+  const sanitizedRest = sanitizeContextData(rest);
+  const sanitizedExtra = sanitizeExtra(extra);
+  const data = {
+    session_id: sessionId,
+    platform,
+    stage,
+    ...sanitizedRest,
+    ...(sanitizedExtra || {}),
+  };
@@
-      Object.entries(rest).forEach(([key, value]) => {
+      Object.entries(sanitizedRest).forEach(([key, value]) => {
         const sanitizedKey = sanitizeTagKey(key);
         if (sanitizedKey) {
           const sanitizedValue = sanitizeTagValue(value);
           scope.setTag(sanitizedKey, sanitizedValue);
         }
       });
-      if (userId) {
-        scope.setUser({ id: userId });
-      }
-      if (extra) {
-        Object.entries(extra).forEach(([key, value]) => {
-          scope.setExtra(key, value);
-        });
-      }
+      if (sanitizedExtra) {
+        Object.entries(sanitizedExtra).forEach(([key, value]) => {
+          scope.setExtra(key, value);
+        });
+      }

Add these helpers (outside this hunk, e.g., after sanitizeTagKey):

// Deny-list sensitive NFC/proof fields and drop values entirely
const SENSITIVE_KEYS = new Set([
  'mrz','can','bac','pacekey','kenc','kmac','kseed','docnumber','passportnumber',
  'chipid','nonce','dg1','dg2','name','firstname','lastname','dob','expiry','mrzfull'
]);

function sanitizeExtra(extra?: Record<string, unknown>) {
  if (!extra) return undefined;
  const out: Record<string, unknown> = {};
  for (const [k, v] of Object.entries(extra)) {
    if (!SENSITIVE_KEYS.has(k.toLowerCase())) out[k] = v;
  }
  return Object.keys(out).length ? out : undefined;
}

function sanitizeContextData(rest: Record<string, unknown>) {
  const out: Record<string, unknown> = {};
  for (const [k, v] of Object.entries(rest)) {
    if (!SENSITIVE_KEYS.has(k.toLowerCase())) out[k] = v;
  }
  return out;
}
🤖 Prompt for AI Agents
In app/src/Sentry.ts around lines 220 to 261, the breadcrumb and scope handling
currently include user identifiers and unsanitized extras/context; update the
code to drop user identifiers (remove session_id/user_id from breadcrumb data
and do not call scope.setUser or setTag for session/user ids), and sanitize
extras and context before logging by using the provided helpers (add the
SENSITIVE_KEYS, sanitizeExtra, and sanitizeContextData functions elsewhere in
the file as suggested). Specifically: build breadcrumb data without
user_id/session_id and with sanitizeContextData(rest) and sanitizeExtra(extra);
in the error scope, do not call scope.setUser or setTag for user/session,
iterate only sanitized context keys from sanitizeContextData(rest) when setting
tags, and call scope.setExtra with sanitized extra entries only.

Comment on lines +1376 to +1395
/**
* Creates a ProofContext with sane defaults for logging proof events
*/
const createProofContext = (
stage: string,
overrides: Partial<ProofContext> = {},
): ProofContext => {
const selfApp = useSelfAppStore.getState().selfApp;
const provingState = useProvingStore.getState();

return {
sessionId: provingState.uuid || 'unknown-session',
userId: selfApp?.userId,
circuitType: provingState.circuitType || null,
currentState: provingState.currentState || 'unknown-state',
stage,
platform: getPlatform(),
...overrides,
};
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix TS2448: createProofContext used before declaration

createProofContext is referenced earlier in the file; as a const it’s not hoisted, causing TS2448. Convert to a function declaration to hoist safely.

-const createProofContext = (
-  stage: string,
-  overrides: Partial<ProofContext> = {},
-): ProofContext => {
+function createProofContext(
+  stage: string,
+  overrides: Partial<ProofContext> = {},
+): ProofContext {
   const selfApp = useSelfAppStore.getState().selfApp;
   const provingState = useProvingStore.getState();
 
   return {
     sessionId: provingState.uuid || 'unknown-session',
     userId: selfApp?.userId,
     circuitType: provingState.circuitType || null,
     currentState: provingState.currentState || 'unknown-state',
     stage,
     platform: getPlatform(),
     ...overrides,
   };
-};
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* Creates a ProofContext with sane defaults for logging proof events
*/
const createProofContext = (
stage: string,
overrides: Partial<ProofContext> = {},
): ProofContext => {
const selfApp = useSelfAppStore.getState().selfApp;
const provingState = useProvingStore.getState();
return {
sessionId: provingState.uuid || 'unknown-session',
userId: selfApp?.userId,
circuitType: provingState.circuitType || null,
currentState: provingState.currentState || 'unknown-state',
stage,
platform: getPlatform(),
...overrides,
};
};
/**
* Creates a ProofContext with sane defaults for logging proof events
*/
function createProofContext(
stage: string,
overrides: Partial<ProofContext> = {},
): ProofContext {
const selfApp = useSelfAppStore.getState().selfApp;
const provingState = useProvingStore.getState();
return {
sessionId: provingState.uuid || 'unknown-session',
userId: selfApp?.userId,
circuitType: provingState.circuitType || null,
currentState: provingState.currentState || 'unknown-state',
stage,
platform: getPlatform(),
...overrides,
};
}
🤖 Prompt for AI Agents
In app/src/utils/proving/provingMachine.ts around lines 1376 to 1395,
createProofContext is declared as a const which isn't hoisted and is referenced
earlier causing TS2448; convert this const arrow function into a named function
declaration (function createProofContext(stage: string, overrides:
Partial<ProofContext> = {}): ProofContext { ... }) so it is hoisted, keep the
same body and return shape, and ensure imports/types remain unchanged.

Comment on lines +13 to +21
on: jest.fn((eventType: string, handler: (event: any) => void) => {
(actorMock as any)._eventHandler = handler;
return {
unsubscribe: jest.fn(() => {
// Properly clean up event handler to prevent memory leak
(actorMock as any)._eventHandler = null;
}),
};
}),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure unsubscribe API parity: add remove() alongside unsubscribe()

Some call sites expect subscription.remove() (see MainScreen.tsx). Add remove aliases to prevent test flakiness.

   on: jest.fn((eventType: string, handler: (event: any) => void) => {
     (actorMock as any)._eventHandler = handler;
     return {
-      unsubscribe: jest.fn(() => {
+      unsubscribe: jest.fn(() => {
         // Properly clean up event handler to prevent memory leak
         (actorMock as any)._eventHandler = null;
-      }),
+      }),
+      remove: jest.fn(() => {
+        (actorMock as any)._eventHandler = null;
+      }),
     };
   }),
@@
     (actorMock as any)._callback = cb;
     return {
-      unsubscribe: jest.fn(() => {
+      unsubscribe: jest.fn(() => {
         // Properly clean up callback to prevent memory leak
         (actorMock as any)._callback = null;
-      }),
+      }),
+      remove: jest.fn(() => {
+        (actorMock as any)._callback = null;
+      }),
     };
   }),

Also applies to: 24-29

🤖 Prompt for AI Agents
In app/tests/utils/proving/actorMock.ts around lines 13-21 (and similarly lines
24-29), the mock subscription object only exposes unsubscribe(), but some code
expects a remove() alias; update the mock to provide remove as an alias to
unsubscribe (and ensure both functions perform the same cleanup of (actorMock as
any)._eventHandler = null) so tests that call subscription.remove() work and no
memory leak remains.

Comment on lines +1 to +3
export declare const testQRData: {
testQRData: string;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure Aadhaar QR test payload never ships to prod or into Sentry logs.

The referenced dataInput.ts contains a very large QR-like string. Keep it test-only (move to fixtures/, exclude from public barrels, or alias to an empty module in prod) and add Sentry scrubbing/redaction for Aadhaar/QR payloads to prevent accidental PII leakage.

🤖 Prompt for AI Agents
In common/src/utils/aadhaar/assets/dataInput.d.ts lines 1-3 the module currently
declares a large Aadhaar QR test payload that must never be shipped; move the
actual test QR string out of source and into a test-only fixture (e.g.,
common/src/utils/aadhaar/__fixtures__/testQRData.ts) and update imports in tests
to point to that fixture, remove the export from any public barrel index so it
is not bundled, and add a conditional alias (or empty module) in production
builds to ensure the payload is not included; additionally, update application
Sentry scrubbing rules (before capture) to redact Aadhaar/QR-like payloads by
pattern (e.g., regex matching base64/QR content or labelled aadhaar/qr fields)
so those values are replaced with a fixed redaction token before sending.

🛠️ Refactor suggestion

Remove redundant .d.ts next to .ts to avoid duplicate exports and type drift.

dataInput.ts already exports testQRData with a concrete type; co-locating a .d.ts with the same export risks duplicate symbol errors across toolchains and creates a second, unsynchronized source of truth. Rely on the .ts types and delete this file.

Apply this diff:

- export declare const testQRData: {
-   testQRData: string;
- };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export declare const testQRData: {
testQRData: string;
};
🤖 Prompt for AI Agents
common/src/utils/aadhaar/assets/dataInput.d.ts lines 1-3: this declaration file
duplicates the export from dataInput.ts and can cause duplicate symbols and type
drift; remove common/src/utils/aadhaar/assets/dataInput.d.ts entirely and let
the existing dataInput.ts provide the testQRData export and its types.

@transphorm transphorm changed the title [SELF-723] feat: add structured NFC logging [SELF-723] feat: add structured NFC and Proof logging Sep 12, 2025
Copy link
Contributor

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/src/utils/proving/provingMachine.ts (1)

491-494: Remove undeclared selfApp field from store state

selfApp is not part of ProvingState and will cause a type error on the Zustand initial state. It’s obtained from useSelfAppStore when needed; keep it out of this store.

Apply this diff:

-    selfApp: null,
♻️ Duplicate comments (1)
app/src/utils/proving/provingMachine.ts (1)

1486-1502: Fix TS2448: createProofContext used before declaration (convert to hoisted function)

As declared, createProofContext is a const and is referenced earlier, triggering TS2448. Convert to a function declaration so it’s hoisted.

Apply this diff:

-const createProofContext = (
-  stage: string,
-  overrides: Partial<ProofContext> = {},
-): ProofContext => {
+function createProofContext(
+  stage: string,
+  overrides: Partial<ProofContext> = {},
+): ProofContext {
   const selfApp = useSelfAppStore.getState().selfApp;
   const provingState = useProvingStore.getState();

   return {
     sessionId: provingState.uuid || 'unknown-session',
     userId: selfApp?.userId,
     circuitType: provingState.circuitType || null,
     currentState: provingState.currentState || 'unknown-state',
     stage,
     platform: getPlatform(),
     ...overrides,
   };
-};
+}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 55faac5 and fda6fbe.

📒 Files selected for processing (4)
  • app/src/utils/proving/provingMachine.ts (25 hunks)
  • app/src/utils/proving/statusHandlers.ts (1 hunks)
  • app/tests/utils/proving/provingMachine.integration.test.ts (1 hunks)
  • app/tests/utils/proving/statusHandlers.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/technical-specification.mdc)

**/*.{ts,tsx}: Define IdentityCommitment with fields: commitment (Poseidon hash), nullifier (domain-separated), timestamp (UTC number), version (circuit version), documentType ('passport' | 'eu_id_card')
Define DSCKeyCommitment with fields: publicKeyHash (Poseidon hash), certificateChain (hashes), revocationStatus (boolean), issuer (country code)
Define VerificationConfig with fields: circuitVersion (semver), complianceRules array, timeWindow (seconds, 24h), clockDrift (±5 min), trustAnchors, revocationRoots, timeSource (NTP), nullifierScope (domain separation)

Files:

  • app/tests/utils/proving/statusHandlers.test.ts
  • app/tests/utils/proving/provingMachine.integration.test.ts
  • app/src/utils/proving/statusHandlers.ts
  • app/src/utils/proving/provingMachine.ts
**/*.{test,spec}.{ts,js,tsx,jsx}

⚙️ CodeRabbit configuration file

**/*.{test,spec}.{ts,js,tsx,jsx}: Review test files for:

  • Test coverage completeness
  • Test case quality and edge cases
  • Mock usage appropriateness
  • Test readability and maintainability

Files:

  • app/tests/utils/proving/statusHandlers.test.ts
  • app/tests/utils/proving/provingMachine.integration.test.ts
app/src/**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

app/src/**/*.{ts,tsx,js,jsx}: Review React Native TypeScript code for:

  • Component architecture and reusability
  • State management patterns
  • Performance optimizations
  • TypeScript type safety
  • React hooks usage and dependencies
  • Navigation patterns

Files:

  • app/src/utils/proving/statusHandlers.ts
  • app/src/utils/proving/provingMachine.ts
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to native/android/**/*.{kt,kts} : Android NFC: implement RNPassportReaderModule in Kotlin
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to native/ios/**/*.{swift} : iOS NFC: implement custom PassportReader as a Swift module
📚 Learning: 2025-08-29T15:31:15.924Z
Learnt from: CR
PR: selfxyz/self#0
File: packages/mobile-sdk-alpha/AGENTS.md:0-0
Timestamp: 2025-08-29T15:31:15.924Z
Learning: Applies to packages/mobile-sdk-alpha/{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Write integration tests that exercise the real validation logic (not mocks)

Applied to files:

  • app/tests/utils/proving/provingMachine.integration.test.ts
📚 Learning: 2025-08-26T14:49:11.190Z
Learnt from: shazarre
PR: selfxyz/self#936
File: app/src/screens/passport/PassportNFCScanScreen.tsx:28-31
Timestamp: 2025-08-26T14:49:11.190Z
Learning: SelfClientProvider is wrapped in app/App.tsx, providing context for useSelfClient() hook usage throughout the React Native app navigation stacks.

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-29T15:31:15.924Z
Learnt from: CR
PR: selfxyz/self#0
File: packages/mobile-sdk-alpha/AGENTS.md:0-0
Timestamp: 2025-08-29T15:31:15.924Z
Learning: Applies to packages/mobile-sdk-alpha/{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Test isPassportDataValid() with realistic synthetic passport data (never real user data)

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Passport verification workflow: NFC data extraction → MRZ validation → DSC verification → Register proof → compliance via ZK → attestation

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Applies to **/*.{ts,tsx} : Define IdentityCommitment with fields: commitment (Poseidon hash), nullifier (domain-separated), timestamp (UTC number), version (circuit version), documentType ('passport' | 'eu_id_card')

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to contracts/contracts/IdentityVerificationHubImplV2.sol : Identity Verification Hub: manage multi-step verification for passports and EU ID cards, handle document attestation via ZK proofs, and implement E-PASSPORT and EU_ID_CARD paths in IdentityVerificationHubImplV2.sol

Applied to files:

  • app/src/utils/proving/provingMachine.ts
🧬 Code graph analysis (4)
app/tests/utils/proving/statusHandlers.test.ts (1)
app/src/utils/proving/statusHandlers.ts (3)
  • parseStatusMessage (94-108)
  • StatusMessage (25-29)
  • handleStatusCode (34-89)
app/tests/utils/proving/provingMachine.integration.test.ts (1)
app/src/utils/proving/provingMachine.ts (1)
  • useProvingStore (368-1481)
app/src/utils/proving/statusHandlers.ts (1)
app/src/screens/ProveScreen.tsx (6)
  • newSocket (55-127)
  • setIsConnecting (129-169)
  • newSocket (122-126)
  • result (83-108)
  • generatingProof (21-247)
  • console (69-71)
app/src/utils/proving/provingMachine.ts (12)
common/src/utils/index.ts (8)
  • DocumentCategory (6-6)
  • PassportData (6-6)
  • SelfApp (14-14)
  • encryptAES256GCM (35-35)
  • getCircuitNameFromPassportData (60-60)
  • getSolidityPackedUserContextData (27-27)
  • getPayload (36-36)
  • EndpointType (12-12)
common/src/types/index.ts (2)
  • DocumentCategory (1-1)
  • PassportData (1-1)
packages/mobile-sdk-alpha/src/stores/protocolStore.ts (1)
  • useProtocolStore (63-321)
packages/mobile-sdk-alpha/src/stores/selfAppStore.tsx (1)
  • useSelfAppStore (23-147)
common/src/utils/circuits/registerInputs.ts (2)
  • generateTEEInputsRegister (110-121)
  • generateTEEInputsDSC (27-37)
packages/mobile-sdk-alpha/src/processing/generate-disclosure-inputs.ts (1)
  • generateTEEInputsDisclose (11-30)
common/src/utils/appType.ts (2)
  • SelfApp (18-34)
  • EndpointType (14-14)
common/src/utils/proving.ts (2)
  • encryptAES256GCM (47-60)
  • getPayload (62-97)
app/src/Sentry.ts (2)
  • logProofEvent (271-276)
  • ProofContext (96-99)
common/src/utils/attest.ts (2)
  • getPublicKey (81-86)
  • verifyAttestation (257-358)
app/src/utils/proving/statusHandlers.ts (2)
  • parseStatusMessage (94-108)
  • handleStatusCode (34-89)
app/src/utils/notifications/notificationService.ts (1)
  • registerDeviceToken (42-93)
🔇 Additional comments (9)
app/src/utils/proving/statusHandlers.ts (2)

34-89: Status handling logic is sound and side-effect free

Clear mapping of statuses to state updates, actor events, and analytics. The early returns for terminal statuses (3/5 and 4) keep control flow simple. No issues from a correctness or safety perspective.


94-108: Robust parsing with explicit error signaling

Graceful handling of invalid JSON and non-object inputs is appropriate. This prevents undefined behavior downstream in the Socket.IO listener.

app/tests/utils/proving/statusHandlers.test.ts (2)

16-49: Good coverage for parseStatusMessage edge cases

Covers valid, invalid, and non-object inputs with precise error messages. No changes needed.


51-174: End-to-end assertions for all actionable statuses

Validates failure and success branches, including register-specific analytics, and the no-op paths. Tests match the production logic exactly.

app/tests/utils/proving/provingMachine.integration.test.ts (4)

141-183: Realistic Socket.IO flow with EventEmitter is effective

Asserting stored socket, state updates, actor events, and disconnect behavior on status 3 is solid. This gives high confidence in the wiring.


185-234: Success paths validated for both register and non-register circuits

Covers the nuance of register-specific behavior without overfitting to analytics internals. Looks good.


236-249: Invalid JSON handling is correct and non-disruptive

Ensures PROVE_ERROR is sent while keeping the connection open. Matches the store logic.


251-276: Non-actionable status is a no-op as intended

Verifies no disconnect, no actor messages, and connection persistence. Nice.

app/src/utils/proving/provingMachine.ts (1)

55-56: Confirm SDK export for useSelfAppStore

useSelfAppStore is exported at packages/mobile-sdk-alpha/src/stores/selfAppStore.tsx and re‑exported in packages/mobile-sdk-alpha/src/stores/index.ts, so the source-level import '@selfxyz/mobile-sdk-alpha/stores' is correct. The lint/build error indicates the package's public exports or Metro/tsconfig mapping isn't exposing './stores'. Action: either import from the SDK root if packages/mobile-sdk-alpha/src/index.ts re-exports it (import { useSelfAppStore } from '@selfxyz/mobile-sdk-alpha') or add "./stores" to packages/mobile-sdk-alpha/package.json "exports" (or update Metro/tsconfig aliases and ensure the SDK is built).

Locations: app/src/utils/proving/provingMachine.ts:55–56; packages/mobile-sdk-alpha/src/stores/index.ts; packages/mobile-sdk-alpha/src/stores/selfAppStore.tsx; packages/mobile-sdk-alpha/package.json.

Comment on lines +79 to +90
const resolveWebSocketUrl = (
circuitType: 'disclose' | 'register' | 'dsc',
passportData: PassportData,
circuitName: string,
): string | undefined => {
const { documentCategory } = passportData;
const circuitsMapping =
useProtocolStore.getState()[documentCategory].circuits_dns_mapping;
const mappingKey = getMappingKey(circuitType, documentCategory);

return circuitsMapping?.[mappingKey]?.[circuitName];
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard against missing protocol store mapping to avoid runtime crash

If the protocol store for the current document isn’t loaded, accessing circuits_dns_mapping will throw. Add a null-safe guard.

Apply this diff:

 const resolveWebSocketUrl = (
   circuitType: 'disclose' | 'register' | 'dsc',
   passportData: PassportData,
   circuitName: string,
 ): string | undefined => {
   const { documentCategory } = passportData;
-  const circuitsMapping =
-    useProtocolStore.getState()[documentCategory].circuits_dns_mapping;
+  const docStore = useProtocolStore.getState()[documentCategory];
+  if (!docStore || !docStore.circuits_dns_mapping) {
+    return undefined;
+  }
+  const circuitsMapping = docStore.circuits_dns_mapping;
   const mappingKey = getMappingKey(circuitType, documentCategory);

   return circuitsMapping?.[mappingKey]?.[circuitName];
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const resolveWebSocketUrl = (
circuitType: 'disclose' | 'register' | 'dsc',
passportData: PassportData,
circuitName: string,
): string | undefined => {
const { documentCategory } = passportData;
const circuitsMapping =
useProtocolStore.getState()[documentCategory].circuits_dns_mapping;
const mappingKey = getMappingKey(circuitType, documentCategory);
return circuitsMapping?.[mappingKey]?.[circuitName];
};
const resolveWebSocketUrl = (
circuitType: 'disclose' | 'register' | 'dsc',
passportData: PassportData,
circuitName: string,
): string | undefined => {
const { documentCategory } = passportData;
const docStore = useProtocolStore.getState()[documentCategory];
if (!docStore || !docStore.circuits_dns_mapping) {
return undefined;
}
const circuitsMapping = docStore.circuits_dns_mapping;
const mappingKey = getMappingKey(circuitType, documentCategory);
return circuitsMapping?.[mappingKey]?.[circuitName];
};
🤖 Prompt for AI Agents
In app/src/utils/proving/provingMachine.ts around lines 79 to 90, the code
directly indexes useProtocolStore.getState()[documentCategory] which will throw
if the protocol entry for the current documentCategory is missing; add a
null-safe guard: retrieve the protocol entry into a variable, check if it exists
(if not, return undefined), then read circuits_dns_mapping from that variable
and proceed to compute mappingKey and return the mapping; ensure you don’t call
getMappingKey or index into circuitsMapping when the protocol or
circuits_dns_mapping is undefined.

Comment on lines 99 to 139
const document: DocumentCategory = passportData.documentCategory;
const protocolStore = useProtocolStore.getState();
const selfApp = useSelfAppStore.getState().selfApp;

let inputs,
circuitName,
endpointType,
endpoint,
circuitTypeWithDocumentExtension;

switch (circuitType) {
case 'register':
({ inputs, circuitName, endpointType, endpoint } =
generateTEEInputsRegister(
secret as string,
passportData,
protocolStore[document].dsc_tree,
env,
));
circuitTypeWithDocumentExtension = `${circuitType}${document === 'passport' ? '' : '_id'}`;
break;
case 'dsc':
({ inputs, circuitName, endpointType, endpoint } = generateTEEInputsDSC(
passportData,
protocolStore[document].csca_tree as string[][],
env,
));
circuitTypeWithDocumentExtension = `${circuitType}${document === 'passport' ? '' : '_id'}`;
break;
case 'disclose':
({ inputs, circuitName, endpointType, endpoint } =
generateTEEInputsDisclose(
secret as string,
passportData,
selfApp as SelfApp,
));
circuitTypeWithDocumentExtension = `disclose`;
break;
default:
throw new Error('Invalid circuit type:' + circuitType);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Harden _generateCircuitInputs against unloaded trees

Directly indexing protocolStore[document].dsc_tree/csca_tree without checks risks undefined access. Add docStore guards and explicit error messages.

Apply this diff:

   const protocolStore = useProtocolStore.getState();
   const selfApp = useSelfAppStore.getState().selfApp;

+  const docStore = protocolStore[document];
+  if (!docStore) {
+    throw new Error(`Protocol store not loaded for document: ${document}`);
+  }
+
   let inputs,
       circuitName,
       endpointType,
       endpoint,
       circuitTypeWithDocumentExtension;

   switch (circuitType) {
     case 'register':
-      ({ inputs, circuitName, endpointType, endpoint } =
-        generateTEEInputsRegister(
-          secret as string,
-          passportData,
-          protocolStore[document].dsc_tree,
-          env,
-        ));
+      if (!docStore.dsc_tree) {
+        throw new Error('DSC tree not loaded');
+      }
+      ({ inputs, circuitName, endpointType, endpoint } =
+        generateTEEInputsRegister(
+          secret as string,
+          passportData,
+          docStore.dsc_tree,
+          env,
+        ));
       circuitTypeWithDocumentExtension = `${circuitType}${document === 'passport' ? '' : '_id'}`;
       break;
     case 'dsc':
-      ({ inputs, circuitName, endpointType, endpoint } = generateTEEInputsDSC(
-        passportData,
-        protocolStore[document].csca_tree as string[][],
-        env,
-      ));
+      if (!docStore.csca_tree) {
+        throw new Error('CSCA tree not loaded');
+      }
+      ({ inputs, circuitName, endpointType, endpoint } = generateTEEInputsDSC(
+        passportData,
+        docStore.csca_tree as string[][],
+        env,
+      ));
       circuitTypeWithDocumentExtension = `${circuitType}${document === 'passport' ? '' : '_id'}`;
       break;

Also applies to: 111-117, 121-127

🤖 Prompt for AI Agents
In app/src/utils/proving/provingMachine.ts around lines 99-139 (also affects
111-117 and 121-127): the code indexes
protocolStore[document].dsc_tree/csca_tree directly which can be undefined; add
guards that read const docStore = protocolStore[document] and validate docStore
exists and that the expected tree (dsc_tree or csca_tree) is present and has the
correct shape before calling generateTEEInputs*. If a required tree is missing
or invalid, throw a clear, descriptive Error (e.g., `Missing protocol store for
${document}` or `Missing dsc_tree for ${document}`) so callers fail fast;
replace direct indexing with safe checks/optional chaining and pass the
validated tree to generateTEEInputs*.

Comment on lines 721 to 756
const result = handleStatusCode(data, get().circuitType);

// Handle state updates
if (result.stateUpdate) {
set(result.stateUpdate);
}

// Handle analytics
result.analytics?.forEach(({ event, data: eventData }) => {
if (event === 'SOCKETIO_PROOF_FAILURE') {
logProofEvent('error', 'TEE processing failed', context, {
failure: 'PROOF_FAILED_TEE_PROCESSING',
error_code: eventData?.error_code,
reason: eventData?.reason,
});
} else if (event === 'SOCKETIO_PROOF_SUCCESS') {
logProofEvent('info', 'TEE processing succeeded', context);
}
selfClient.trackEvent(event as any, eventData);
});
actor!.send({ type: 'PROVE_FAILURE' });
socket?.disconnect();
set({ socketConnection: null });
} else if (data.status === 4) {
socket?.disconnect();
set({ socketConnection: null });
if (get().circuitType === 'register') {
selfClient.trackEvent(ProofEvents.REGISTER_COMPLETED);

// Handle actor events
if (result.actorEvent) {
if (result.actorEvent.type === 'PROVE_FAILURE') {
console.error(
'Proof generation/verification failed (status 3 or 5).',
);
console.error(data);
}
actor!.send(result.actorEvent);
}

// Handle disconnection
if (result.shouldDisconnect) {
socket?.disconnect();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Narrow circuitType before passing to handleStatusCode

get().circuitType can be null; handleStatusCode expects a string. This can surface as a type/runtime edge case. Default to 'disclose' or assert non-null.

Apply this diff:

-          const result = handleStatusCode(data, get().circuitType);
+          const circuit = get().circuitType ?? 'disclose';
+          const result = handleStatusCode(data, circuit);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const result = handleStatusCode(data, get().circuitType);
// Handle state updates
if (result.stateUpdate) {
set(result.stateUpdate);
}
// Handle analytics
result.analytics?.forEach(({ event, data: eventData }) => {
if (event === 'SOCKETIO_PROOF_FAILURE') {
logProofEvent('error', 'TEE processing failed', context, {
failure: 'PROOF_FAILED_TEE_PROCESSING',
error_code: eventData?.error_code,
reason: eventData?.reason,
});
} else if (event === 'SOCKETIO_PROOF_SUCCESS') {
logProofEvent('info', 'TEE processing succeeded', context);
}
selfClient.trackEvent(event as any, eventData);
});
actor!.send({ type: 'PROVE_FAILURE' });
socket?.disconnect();
set({ socketConnection: null });
} else if (data.status === 4) {
socket?.disconnect();
set({ socketConnection: null });
if (get().circuitType === 'register') {
selfClient.trackEvent(ProofEvents.REGISTER_COMPLETED);
// Handle actor events
if (result.actorEvent) {
if (result.actorEvent.type === 'PROVE_FAILURE') {
console.error(
'Proof generation/verification failed (status 3 or 5).',
);
console.error(data);
}
actor!.send(result.actorEvent);
}
// Handle disconnection
if (result.shouldDisconnect) {
socket?.disconnect();
}
const circuit = get().circuitType ?? 'disclose';
const result = handleStatusCode(data, circuit);
// Handle state updates
if (result.stateUpdate) {
set(result.stateUpdate);
}
// Handle analytics
result.analytics?.forEach(({ event, data: eventData }) => {
if (event === 'SOCKETIO_PROOF_FAILURE') {
logProofEvent('error', 'TEE processing failed', context, {
failure: 'PROOF_FAILED_TEE_PROCESSING',
error_code: eventData?.error_code,
reason: eventData?.reason,
});
} else if (event === 'SOCKETIO_PROOF_SUCCESS') {
logProofEvent('info', 'TEE processing succeeded', context);
}
selfClient.trackEvent(event as any, eventData);
});
// Handle actor events
if (result.actorEvent) {
if (result.actorEvent.type === 'PROVE_FAILURE') {
console.error(
'Proof generation/verification failed (status 3 or 5).',
);
console.error(data);
}
actor!.send(result.actorEvent);
}
// Handle disconnection
if (result.shouldDisconnect) {
socket?.disconnect();
}
🤖 Prompt for AI Agents
In app/src/utils/proving/provingMachine.ts around lines 721 to 756,
get().circuitType may be null but handleStatusCode requires a non-null string;
change the call to pass a narrowed/defaulted string (e.g. get().circuitType ??
'disclose') or assert non-null before calling. Update the code so result is
computed using handleStatusCode(data, get().circuitType ?? 'disclose') (or add a
guard that throws/logs if circuitType is null) to ensure a string is always
passed and avoid runtime/type errors.

Copy link
Contributor

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
app/src/utils/proving/provingMachine.ts (3)

824-840: Avoid DOM constructors in React Native (MessageEvent/CloseEvent are undefined).

Creating new MessageEvent/CloseEvent crashes in RN. Pass a plain event-like object instead.

       get()._handleWebSocketMessage(
-        new MessageEvent('error', {
-          data: JSON.stringify({ error: 'WebSocket connection error' }),
-        }),
+        { data: JSON.stringify({ error: 'WebSocket connection error' }) } as unknown as MessageEvent,
         selfClient,
       );
       if (
         currentState === 'init_tee_connexion' ||
         currentState === 'proving' ||
         currentState === 'listening_for_status'
       ) {
         console.error(
           `TEE WebSocket closed unexpectedly during ${currentState}.`,
         );
         get()._handleWebSocketMessage(
-          new MessageEvent('error', {
-            data: JSON.stringify({ error: 'WebSocket closed unexpectedly' }),
-          }),
+          { data: JSON.stringify({ error: 'WebSocket closed unexpectedly' }) } as unknown as MessageEvent,
           selfClient,
         );
       }

Also applies to: 842-874


512-512: Remove undeclared selfApp field from ProvingState.

This property isn’t defined in the ProvingState interface and breaks type-checking.

-    selfApp: null,

1209-1257: Add a connection timeout for the TEE WebSocket handshake.

Without a timeout, initTeeConnection can hang indefinitely on network issues.

-      return new Promise(resolve => {
+      return new Promise(resolve => {
         const ws = new WebSocket(wsRpcUrl);
+        const timeoutMs = 15000;
+        const timer = setTimeout(() => {
+          handleConnectError('timeout');
+        }, timeoutMs);

         const handleConnectSuccess = () => {
+          clearTimeout(timer);
           logProofEvent('info', 'TEE connection succeeded', baseContext, {
             duration_ms: Date.now() - startTime,
           });
           selfClient.trackEvent(ProofEvents.TEE_CONN_SUCCESS);
           resolve(true);
         };
         const handleConnectError = (msg: string = 'connect_error') => {
+          clearTimeout(timer);
           logProofEvent('error', 'TEE connection failed', baseContext, {
             failure: 'PROOF_FAILED_CONNECTION',
             error: msg,
             duration_ms: Date.now() - startTime,
           });
           selfClient.trackEvent(ProofEvents.TEE_CONN_FAILED, { message: msg });
           resolve(false);
         };
♻️ Duplicate comments (4)
app/src/utils/proving/provingMachine.ts (4)

1512-1528: Fix TS2448: createProofContext used before declaration (convert to a function).

The const arrow form isn’t hoisted and is referenced earlier in the file, causing TS2448 and runtime TDZ risk. Convert to a function declaration.

-const createProofContext = (
-  stage: string,
-  overrides: Partial<ProofContext> = {},
-): ProofContext => {
+function createProofContext(
+  stage: string,
+  overrides: Partial<ProofContext> = {},
+): ProofContext {
   const selfApp = useSelfAppStore.getState().selfApp;
   const provingState = useProvingStore.getState();

   return {
     sessionId: provingState.uuid || 'unknown-session',
     userId: selfApp?.userId,
     circuitType: provingState.circuitType || null,
     currentState: provingState.currentState || 'unknown-state',
     stage,
     platform: getPlatform(),
     ...overrides,
   };
-};
+}

111-158: Harden _generateCircuitInputs against missing protocol trees.

Accessing dsc_tree/csca_tree without checks will fail if the store hasn’t finished loading.

   const protocolStore = useProtocolStore.getState();
   const selfApp = useSelfAppStore.getState().selfApp;

+  const docStore = protocolStore[document];
+  if (!docStore) {
+    throw new Error(`Protocol store not loaded for document: ${document}`);
+  }
+
   let inputs,
       circuitName,
       endpointType,
       endpoint,
       circuitTypeWithDocumentExtension;

   switch (circuitType) {
     case 'register':
-      ({ inputs, circuitName, endpointType, endpoint } =
-        generateTEEInputsRegister(
-          secret as string,
-          passportData,
-          protocolStore[document].dsc_tree,
-          env,
-        ));
+      if (!docStore.dsc_tree) {
+        throw new Error('DSC tree not loaded');
+      }
+      ({ inputs, circuitName, endpointType, endpoint } =
+        generateTEEInputsRegister(
+          secret as string,
+          passportData,
+          docStore.dsc_tree,
+          env,
+        ));
       circuitTypeWithDocumentExtension = `${circuitType}${document === 'passport' ? '' : '_id'}`;
       break;
     case 'dsc':
-      ({ inputs, circuitName, endpointType, endpoint } = generateTEEInputsDSC(
-        passportData,
-        protocolStore[document].csca_tree as string[][],
-        env,
-      ));
+      if (!docStore.csca_tree) {
+        throw new Error('CSCA tree not loaded');
+      }
+      ({ inputs, circuitName, endpointType, endpoint } = generateTEEInputsDSC(
+        passportData,
+        docStore.csca_tree as string[][],
+        env,
+      ));
       circuitTypeWithDocumentExtension = `${circuitType}${document === 'passport' ? '' : '_id'}`;
       break;

739-741: Don’t pass a possibly null circuitType into handleStatusCode.

Default to a safe value to avoid runtime edge-cases.

-          const result = handleStatusCode(data, get().circuitType as string);
+          const circuit = get().circuitType ?? 'disclose';
+          const result = handleStatusCode(data, circuit);

81-92: Guard circuits_dns_mapping access to prevent undefined access.

If the store slice or mapping isn’t loaded yet, this can throw. Return undefined early.

   const { documentCategory } = passportData;
-  const circuitsMapping =
-    useProtocolStore.getState()[documentCategory].circuits_dns_mapping;
+  const docStore = useProtocolStore.getState()[documentCategory];
+  if (!docStore || !docStore.circuits_dns_mapping) {
+    return undefined;
+  }
+  const circuitsMapping = docStore.circuits_dns_mapping;
   const mappingKey = getMappingKey(circuitType, documentCategory);

   return circuitsMapping?.[mappingKey]?.[circuitName];
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fda6fbe and 21b2e26.

📒 Files selected for processing (1)
  • app/src/utils/proving/provingMachine.ts (24 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/technical-specification.mdc)

**/*.{ts,tsx}: Define IdentityCommitment with fields: commitment (Poseidon hash), nullifier (domain-separated), timestamp (UTC number), version (circuit version), documentType ('passport' | 'eu_id_card')
Define DSCKeyCommitment with fields: publicKeyHash (Poseidon hash), certificateChain (hashes), revocationStatus (boolean), issuer (country code)
Define VerificationConfig with fields: circuitVersion (semver), complianceRules array, timeWindow (seconds, 24h), clockDrift (±5 min), trustAnchors, revocationRoots, timeSource (NTP), nullifierScope (domain separation)

Files:

  • app/src/utils/proving/provingMachine.ts
app/src/**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

app/src/**/*.{ts,tsx,js,jsx}: Review React Native TypeScript code for:

  • Component architecture and reusability
  • State management patterns
  • Performance optimizations
  • TypeScript type safety
  • React hooks usage and dependencies
  • Navigation patterns

Files:

  • app/src/utils/proving/provingMachine.ts
🧠 Learnings (5)
📚 Learning: 2025-08-29T15:31:15.924Z
Learnt from: CR
PR: selfxyz/self#0
File: packages/mobile-sdk-alpha/AGENTS.md:0-0
Timestamp: 2025-08-29T15:31:15.924Z
Learning: Applies to packages/mobile-sdk-alpha/{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Test isPassportDataValid() with realistic synthetic passport data (never real user data)

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-26T14:49:11.190Z
Learnt from: shazarre
PR: selfxyz/self#936
File: app/src/screens/passport/PassportNFCScanScreen.tsx:28-31
Timestamp: 2025-08-26T14:49:11.190Z
Learning: SelfClientProvider is wrapped in app/App.tsx, providing context for useSelfClient() hook usage throughout the React Native app navigation stacks.

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Passport verification workflow: NFC data extraction → MRZ validation → DSC verification → Register proof → compliance via ZK → attestation

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:55:07.940Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursor/rules/technical-specification.mdc:0-0
Timestamp: 2025-08-24T18:55:07.940Z
Learning: Applies to **/*.{ts,tsx} : Define IdentityCommitment with fields: commitment (Poseidon hash), nullifier (domain-separated), timestamp (UTC number), version (circuit version), documentType ('passport' | 'eu_id_card')

Applied to files:

  • app/src/utils/proving/provingMachine.ts
📚 Learning: 2025-08-24T18:52:25.796Z
Learnt from: CR
PR: selfxyz/self#0
File: .cursorrules:0-0
Timestamp: 2025-08-24T18:52:25.796Z
Learning: Applies to contracts/contracts/IdentityVerificationHubImplV2.sol : Identity Verification Hub: manage multi-step verification for passports and EU ID cards, handle document attestation via ZK proofs, and implement E-PASSPORT and EU_ID_CARD paths in IdentityVerificationHubImplV2.sol

Applied to files:

  • app/src/utils/proving/provingMachine.ts
🧬 Code graph analysis (1)
app/src/utils/proving/provingMachine.ts (8)
common/src/utils/index.ts (8)
  • DocumentCategory (6-6)
  • PassportData (6-6)
  • SelfApp (14-14)
  • encryptAES256GCM (35-35)
  • getCircuitNameFromPassportData (60-60)
  • getSolidityPackedUserContextData (27-27)
  • getPayload (36-36)
  • EndpointType (12-12)
common/src/utils/types.ts (2)
  • DocumentCategory (16-16)
  • PassportData (35-50)
common/src/utils/circuits/registerInputs.ts (3)
  • generateTEEInputsRegister (110-121)
  • generateTEEInputsDSC (27-37)
  • generateTEEInputsDiscloseStateless (39-108)
common/src/utils/proving.ts (2)
  • encryptAES256GCM (47-60)
  • getPayload (62-97)
app/src/Sentry.web.ts (2)
  • logProofEvent (263-268)
  • ProofContext (95-98)
app/src/Sentry.ts (2)
  • logProofEvent (271-276)
  • ProofContext (96-99)
packages/mobile-sdk-alpha/src/constants/analytics.ts (1)
  • ProofEvents (105-165)
app/src/utils/proving/statusHandlers.ts (2)
  • parseStatusMessage (94-108)
  • handleStatusCode (34-89)
⏰ Context from checks skipped due to timeout of 300000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: test
  • GitHub Check: build-ios
  • GitHub Check: build-android
  • GitHub Check: e2e-ios
  • GitHub Check: analyze-android
  • GitHub Check: analyze-ios

Comment on lines +1168 to 1176
let circuitName;
if (circuitType === 'disclose') {
circuitName = 'disclose';
if (passportData.documentCategory === 'passport') {
wsRpcUrl = circuitsMapping?.DISCLOSE?.[circuitName];
} else {
wsRpcUrl = circuitsMapping?.DISCLOSE_ID?.[circuitName];
}
} else {
circuitName = getCircuitNameFromPassportData(
passportData,
get().circuitType as 'register' | 'dsc',
circuitType as 'register' | 'dsc',
);
if (get().circuitType === 'register') {
if (passportData.documentCategory === 'passport') {
wsRpcUrl = circuitsMapping?.REGISTER?.[circuitName];
} else {
wsRpcUrl = circuitsMapping?.REGISTER_ID?.[circuitName];
}
} else {
if (passportData.documentCategory === 'passport') {
wsRpcUrl = circuitsMapping?.DSC?.[circuitName];
} else {
wsRpcUrl = circuitsMapping?.DSC_ID?.[circuitName];
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix disclose circuitName: 'disclose' won’t match circuits_dns_mapping keys.

For disclose, mapping keys are typically 'vc_and_disclose' or 'vc_and_disclose_id'; using 'disclose' yields no URL.

-      let circuitName;
-      if (circuitType === 'disclose') {
-        circuitName = 'disclose';
-      } else {
+      let circuitName;
+      if (circuitType === 'disclose') {
+        circuitName =
+          (passportData as PassportData).documentCategory === 'passport'
+            ? 'vc_and_disclose'
+            : 'vc_and_disclose_id';
+      } else {
         circuitName = getCircuitNameFromPassportData(
           passportData,
           circuitType as 'register' | 'dsc',
         );
       }

Also applies to: 1178-1186

🤖 Prompt for AI Agents
In app/src/utils/proving/provingMachine.ts around lines 1168-1176 and 1178-1186,
the code sets circuitName to the literal 'disclose' which does not match the
circuits_dns_mapping keys (they expect 'vc_and_disclose' or
'vc_and_disclose_id'); change the logic so that for circuitType === 'disclose'
you derive the correct mapping key — either call the helper that resolves
circuit names (e.g., extend/getCircuitNameFromPassportData to accept 'disclose')
or set circuitName conditionally (use 'vc_and_disclose_id' when passportData
indicates an identity/id present, otherwise 'vc_and_disclose'); apply the same
fix in the second occurrence so both places use the proper mapping keys instead
of the literal 'disclose'.

@transphorm
Copy link
Member Author

tested registering and proving in prod and staging and everything worked

@transphorm transphorm merged commit 99165c9 into dev Sep 13, 2025
29 of 30 checks passed
@transphorm transphorm deleted the codex/implement-sentry-structured-logging-for-nfc branch September 13, 2025 00:12
Nesopie pushed a commit that referenced this pull request Sep 17, 2025
* feat: add structured NFC logging

* fix ci

* Fix: add deps

* logging fixes. use breadcrumbs

* fix android build

* update SeverityLevel

* [SELF-705] feat: add proof event logging (#1057)

* feat: add proof event logging

* refactor: unify sentry event logging

* fix types

* fix mock

* simplify

* code rabbit feedback

* fix tests

---------

Co-authored-by: seshanthS <[email protected]>
Nesopie added a commit that referenced this pull request Sep 17, 2025
* feat: add aadhaar support to the ts sdk

* feat: aadhaar support to go sdk

* chore: refactor

* move clearPassportData, markCurrentDocumentAsRegistered, reStorePassportDataWithRightCSCA to SDK (#1041)

* Move self app store to mobile sdk (#1040)

* chore(mobile-sdk-alpha): remove unused tslib dependency (#1053)

* remove tslib -- seems unused

* remove deps accidentally added to root

* build file

* remove unused imports (#1055)

* fix: sha256 signed attr tests (#1058)

* fix mock screen launch (#1059)

* Hotfix: Belgium ID cards (#1061)

* feat: parse belgium TD1 mrz android

* feat: Parse Belgium TD1 MRZ IOS

* fix: OFAC trees not found (#1060)

* fix: relax OFAC tree response validation

* test: cover OFAC tree edge cases

* fix stateless

* revert and fix types

* fix tests

* [SELF-723] feat: add structured NFC and Proof logging (#1048)

* feat: add structured NFC logging

* fix ci

* Fix: add deps

* logging fixes. use breadcrumbs

* fix android build

* update SeverityLevel

* [SELF-705] feat: add proof event logging (#1057)

* feat: add proof event logging

* refactor: unify sentry event logging

* fix types

* fix mock

* simplify

* code rabbit feedback

* fix tests

---------

Co-authored-by: seshanthS <[email protected]>

* skip on dev (#1063)

* don't get fancy just disable (#1064)

* saw it building so gonna try (#1065)

* chore: bump v2.6.5 rd2 (#1067)

* commit wip version bump

* remove from building

* chore: update tooling dependencies (#1069)

* chore: update tooling dependencies

* chore: align react typings and node types

* update lock

* chore: minor fixes across monorepo (#1068)

* small fixes

* fixes

* fix gesture handler error

* ci fixes

* fix yarn build; add workflow ci (#1075)

* add new workspace ci

* disable package version check for now

* build before checks

* format

* fix in future pr

* feat: add functions for disclosing aadhaar attributes (#1033)

* feat: add functions for disclosing aadhaar attributes

* format

* chore: update monorepo artifacts (#1079)

* remove unneeded artifacts, skip building circuits

* update md files

* chore: update hub contract address

* format

* fix: add aadhaar in AllIds

* chore: bump to v1.1.0-beta

---------

Co-authored-by: vishal <[email protected]>
Co-authored-by: Leszek Stachowski <[email protected]>
Co-authored-by: Aaron DeRuvo <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: seshanthS <[email protected]>
remicolin added a commit that referenced this pull request Sep 20, 2025
* chore: bump v2.6.5 rd2 (#1067)

* commit wip version bump

* remove from building

* chore: update tooling dependencies (#1069)

* chore: update tooling dependencies

* chore: align react typings and node types

* update lock

* chore: minor fixes across monorepo (#1068)

* small fixes

* fixes

* fix gesture handler error

* ci fixes

* fix yarn build; add workflow ci (#1075)

* add new workspace ci

* disable package version check for now

* build before checks

* format

* fix in future pr

* feat: add functions for disclosing aadhaar attributes (#1033)

* feat: add functions for disclosing aadhaar attributes

* format

* chore: update monorepo artifacts (#1079)

* remove unneeded artifacts, skip building circuits

* update md files

* cleans up unused parts of sdk interface, adds inline documentation, (#1078)

* cleans up unused parts of sdk interface, adds inline documentation,

* fix up build

* yolo

* Feat/aadhaar sdk (#1082)

* feat: add aadhaar support to the ts sdk

* feat: aadhaar support to go sdk

* chore: refactor

* move clearPassportData, markCurrentDocumentAsRegistered, reStorePassportDataWithRightCSCA to SDK (#1041)

* Move self app store to mobile sdk (#1040)

* chore(mobile-sdk-alpha): remove unused tslib dependency (#1053)

* remove tslib -- seems unused

* remove deps accidentally added to root

* build file

* remove unused imports (#1055)

* fix: sha256 signed attr tests (#1058)

* fix mock screen launch (#1059)

* Hotfix: Belgium ID cards (#1061)

* feat: parse belgium TD1 mrz android

* feat: Parse Belgium TD1 MRZ IOS

* fix: OFAC trees not found (#1060)

* fix: relax OFAC tree response validation

* test: cover OFAC tree edge cases

* fix stateless

* revert and fix types

* fix tests

* [SELF-723] feat: add structured NFC and Proof logging (#1048)

* feat: add structured NFC logging

* fix ci

* Fix: add deps

* logging fixes. use breadcrumbs

* fix android build

* update SeverityLevel

* [SELF-705] feat: add proof event logging (#1057)

* feat: add proof event logging

* refactor: unify sentry event logging

* fix types

* fix mock

* simplify

* code rabbit feedback

* fix tests

---------

Co-authored-by: seshanthS <[email protected]>

* skip on dev (#1063)

* don't get fancy just disable (#1064)

* saw it building so gonna try (#1065)

* chore: bump v2.6.5 rd2 (#1067)

* commit wip version bump

* remove from building

* chore: update tooling dependencies (#1069)

* chore: update tooling dependencies

* chore: align react typings and node types

* update lock

* chore: minor fixes across monorepo (#1068)

* small fixes

* fixes

* fix gesture handler error

* ci fixes

* fix yarn build; add workflow ci (#1075)

* add new workspace ci

* disable package version check for now

* build before checks

* format

* fix in future pr

* feat: add functions for disclosing aadhaar attributes (#1033)

* feat: add functions for disclosing aadhaar attributes

* format

* chore: update monorepo artifacts (#1079)

* remove unneeded artifacts, skip building circuits

* update md files

* chore: update hub contract address

* format

* fix: add aadhaar in AllIds

* chore: bump to v1.1.0-beta

---------

Co-authored-by: vishal <[email protected]>
Co-authored-by: Leszek Stachowski <[email protected]>
Co-authored-by: Aaron DeRuvo <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: seshanthS <[email protected]>

* feat: change to gcp attestation verification (#959)

* feat: change to gcp attestation verification

* lint

* fix e2e test

* chore: don't check PCR0 mapping if building the app locally

* fmt:fix

---------

Co-authored-by: Justin Hernandez <[email protected]>

* Mobile SDK: move provingMachine from the app (#1052)

* Mobile SDK: move provingMachine from the app

* lint, fixes

* fix web build?

* lint

* fix metro build, add deps

* update lock files

* move the status handlers and proving machine tests

* may it be

* fix up

* yolo

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Aaron DeRuvo <[email protected]>

* Revert "Mobile SDK: move provingMachine from the app (#1052)" (#1084)

This reverts commit 8983ac2.

* fix: sdk (#1085)

* bump sdk (#1086)

* chore update mobile app types (#1087)

* clean up types

* clean up additional types

* format

* fix types

* feat: add contract utils (#1088)

* Feat/contracts npm publish (#1089)

* chore: ci to publish contracts

* yarn fmt

* fix: use celo sepolia in common (#1091)

* chore: export selfappbuilder (#1092)

* [SELF-747] feat: clone android passport reader during setup (#1080)

* chore: remove android private modules doc

* private repo pull

* skip private modules

* remove unused circuits building

* save wip

* format

* restore tsconfig

* fix package install

* fix internal repo cloning

* unify logic and fix cloning

* git clone internal repos efficiently

* formatting

* run app yarn reinstall from root

* coderabbit feedback

* coderabbit suggestions

* remove skip private modules logic

* fix: ensure PAT is passed through yarn-install action and handle missing PAT gracefully

- Update yarn-install action to pass SELFXYZ_INTERNAL_REPO_PAT to yarn install
- Make setup-private-modules.cjs skip gracefully when PAT is unavailable in CI
- Fixes issue where setup script was throwing error instead of skipping for forks

* prettier

* fix clone ci

* clone ci fixes

* fix import export sorts

* fix instructions

* fix: remove SelfAppBuilder re-export to fix duplicate export error

- Remove SelfAppBuilder import/export from @selfxyz/qrcode
- Update README to import SelfAppBuilder directly from @selfxyz/common
- Fixes CI build failure with duplicate export error

* fix: unify eslint-plugin-sort-exports version across workspaces

- Update mobile-sdk-alpha from 0.8.0 to 0.9.1 to match other workspaces
- Removes yarn.lock version conflict causing CI/local behavior mismatch
- Fixes quality-checks workflow linting failure

* fix: bust qrcode SDK build cache to resolve stale SelfAppBuilder issue

- Increment GH_SDK_CACHE_VERSION from v1 to v2
- Forces CI to rebuild artifacts from scratch instead of using cached version
- Resolves quality-checks linter error showing removed SelfAppBuilder export

* skip job

* test yarn cache

* bump cache version to try and fix the issue

* revert cache version

* refactor: use direct re-exports for cleaner qrcode package structure

- Replace import-then-export pattern with direct re-exports
- Keep SelfAppBuilder export with proper alphabetical sorting (before SelfQRcode)
- Maintain API compatibility as documented in README
- Eliminates linter sorting issues while keeping clean code structure

* fix: separate type and value imports in README examples

- Import SelfApp as type since it's an interface
- Import SelfAppBuilder as value since it's a class
- Follows TypeScript best practices and improves tree shaking

* address version mismatches and package resolutions (#1081)

* fix package version mismatches and resolutions

* fixes

* update lock

* fix comma

* fixes

* fix packages

* update packages

* remove firebase analytics. not needed

* fix: aadhaar verifier abi (#1096)

* fix: aadhaar verifier abi

* bump: core

* fix: go-sdk (#1090)

* SELF-725: add iOS qrcode opener and aadhaar screen (#1038)

* add iOS qrcode opener and aadhaar screen

* format

* fix test

* add Image-picker android (#1077)

* add image-picker android

* fix validation

* feat: implement Aadhaar upload success and error screens, enhance AadhaarNavBar with dynamic progress indication

- Added AadhaarUploadedSuccessScreen and AadhaarUploadErrorScreen components for handling upload outcomes.
- Updated AadhaarNavBar to reflect current upload step with dynamic progress bar.
- Integrated new screens into navigation flow for Aadhaar upload process.
- Introduced blue check and warning SVG icons for visual feedback on success and error states.

* feat: generate mock aadhar (#1083)

* feat: generate mock aadhar

* add yarn.lock

* update yarn.lock

* update protocolStore, update types, start modifying provingMachine

* Register mock aadhar (#1093)

* Register mock aadhar

* fix ofac

* temp: generate name

* fix dob

* Add Aadhaar support to ID card component and screens

- Integrated Aadhaar icon and conditional rendering in IdCardLayout.
- Updated AadhaarUploadScreen to process QR codes and store Aadhaar data.
- Modified navigation and button text in AadhaarUploadedSuccessScreen.
- Added mock data generation for Aadhaar in the mobile SDK.
- Updated ManageDocumentsScreen to include Aadhaar document type.
- Enhanced error handling and validation for Aadhaar QR code processing.
- Added utility functions for Aadhaar data extraction and commitment processing.

* aadhaar disclose - wip (#1094)

* fix: timestamp cal of extractQRDataFields

* Feat/aadhar fixes (#1099)

* Fix - android aadhar qr scanner

* fixes

* update text

* yarn nice

* run prettier

* Add mock Aadhaar certificates for development

- Introduced hardcoded Aadhaar test certificates for development purposes.
- Moved Aadhaar mock private and public keys to a dedicated file for better organization.
- Updated the mock ID document generation utility to utilize the new Aadhaar mock certificates.

* prettier write

* add 'add-aadhaar' button (#1100)

* Update .gitleaks.toml to include path for mock certificates in the common/dist directory

* yarn nice

* Enhance Aadhaar error handling with specific error types

- Updated the AadhaarUploadErrorScreen to display different messages based on the error type (general or expired).
- Modified the AadhaarUploadScreen to pass the appropriate error type when navigating to the error screen.
- Set initial parameters for the home screen to include a default error type.

* Update passport handling in proving machine to support Aadhaar document category

- Modified the handling of country code in the useProvingStore to return 'IND' for Aadhaar documents.
- Ensured that the country code is only fetched from passport metadata for non-Aadhaar documents.

* tweak layout, text, change email to support, hide help button

* fix ci, remove aadhaar logging, add aadhaar events

* remove unused aadhaar tracking events

* update globs

* fix gitguardian config

* don't track id

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: vishal <[email protected]>

* fix aadhaar screen test (#1101)

* add iOS qrcode opener and aadhaar screen

* format

* fix test

* add Image-picker android (#1077)

* add image-picker android

* fix validation

* feat: implement Aadhaar upload success and error screens, enhance AadhaarNavBar with dynamic progress indication

- Added AadhaarUploadedSuccessScreen and AadhaarUploadErrorScreen components for handling upload outcomes.
- Updated AadhaarNavBar to reflect current upload step with dynamic progress bar.
- Integrated new screens into navigation flow for Aadhaar upload process.
- Introduced blue check and warning SVG icons for visual feedback on success and error states.

* feat: generate mock aadhar (#1083)

* feat: generate mock aadhar

* add yarn.lock

* update yarn.lock

* update protocolStore, update types, start modifying provingMachine

* Register mock aadhar (#1093)

* Register mock aadhar

* fix ofac

* temp: generate name

* fix dob

* Add Aadhaar support to ID card component and screens

- Integrated Aadhaar icon and conditional rendering in IdCardLayout.
- Updated AadhaarUploadScreen to process QR codes and store Aadhaar data.
- Modified navigation and button text in AadhaarUploadedSuccessScreen.
- Added mock data generation for Aadhaar in the mobile SDK.
- Updated ManageDocumentsScreen to include Aadhaar document type.
- Enhanced error handling and validation for Aadhaar QR code processing.
- Added utility functions for Aadhaar data extraction and commitment processing.

* aadhaar disclose - wip (#1094)

* fix: timestamp cal of extractQRDataFields

* Feat/aadhar fixes (#1099)

* Fix - android aadhar qr scanner

* fixes

* update text

* yarn nice

* run prettier

* Add mock Aadhaar certificates for development

- Introduced hardcoded Aadhaar test certificates for development purposes.
- Moved Aadhaar mock private and public keys to a dedicated file for better organization.
- Updated the mock ID document generation utility to utilize the new Aadhaar mock certificates.

* prettier write

* add 'add-aadhaar' button (#1100)

* Update .gitleaks.toml to include path for mock certificates in the common/dist directory

* yarn nice

* Enhance Aadhaar error handling with specific error types

- Updated the AadhaarUploadErrorScreen to display different messages based on the error type (general or expired).
- Modified the AadhaarUploadScreen to pass the appropriate error type when navigating to the error screen.
- Set initial parameters for the home screen to include a default error type.

* Update passport handling in proving machine to support Aadhaar document category

- Modified the handling of country code in the useProvingStore to return 'IND' for Aadhaar documents.
- Ensured that the country code is only fetched from passport metadata for non-Aadhaar documents.

* tweak layout, text, change email to support, hide help button

* fix ci, remove aadhaar logging, add aadhaar events

* remove unused aadhaar tracking events

* update globs

* fix gitguardian config

* don't track id

* fix test

---------

Co-authored-by: turnoffthiscomputer <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: vishal <[email protected]>

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Nesopie <[email protected]>
Co-authored-by: Aaron DeRuvo <[email protected]>
Co-authored-by: vishal <[email protected]>
Co-authored-by: Leszek Stachowski <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: seshanthS <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
remicolin added a commit that referenced this pull request Sep 22, 2025
* SDK Go version (#920)

* feat: helper functions and constant for go-sdk

* feat: formatRevealedDataPacked in go

* chore: refactor

* feat: define struct for selfBackendVerifier

* feat: verify function for selfBackendVerifier

* feat(wip): custom hasher

* feat: SelfVerifierBacked in go

* test(wip): scope and userContextHash is failing

* test: zk proof verified

* fix: MockConfigStore getactionId function

* chore: refactor

* chore: remove abi duplicate files

* chore: move configStore to utils

* chore: modified VcAndDiscloseProof struct

* chore: more review changes

* feat: impl DefaultConfig and InMemoryConfigStore

* chore: refactor and export functions

* fix: module import and README

* chore: remove example folder

* chore: remove pointers from VerificationConfig

* chore: coderabbit review fixes

* chore: more coderabbit review fix

* chore: add license

* fix: convert attestationIdd to int

* chore: remove duplicate code

---------

Co-authored-by: ayman <[email protected]>

* Moving proving Utils to common (#935)

* remove react dom

* moves proving utils to the common

* need to use rn components

* fix imports

* add proving-utils and dedeuplicate entry configs for esm and cjs.

* must wrap in text component

* fix metro bundling

* fix mock import

* fix builds and tests

* please save me

* solution?

* fix test

* Move proving inputs to the common package (#937)

* create ofactTree type to share

* move proving inputs from app to register inputs in common

* missed reexport

* ok

* add some validations as suggested by our ai overlords

* Fix mock passport flow (#942)

* fix dev screens

* add hint

* rename

* fix path

* fix mobile-ci path

* fix: extractMRZ (#938)

* fix: extractMRZ

* yarn nice && yarn types

* fix test: remove unused

* fix mobile ci

* add script

---------

Co-authored-by: Justin Hernandez <[email protected]>

* Move Proving attest and cose (#950)

* moved attest and cose utils to common

with cursor converted tests in common to use vitest and converted coseVerify.test to vitest after moving from app to common

what does cryptoLoader do?

* moved away

* get buff

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* SELF-253 feat: add user email feedback (#889)

* feat: add sentry feedback

* add sentry feedback to web

* feat: add custom feedback modal & fix freeze on IOS

* yarn nice

* update lock

* feat: show feedback widget on NFC scan issues (#948)

* feat: show feedback widget on NFC scan issues

* fix ref

* clean up

* fix report issue screen

* abstract send user feedback email logic

* fixes

* change text to Report Issue

* sanitize email and track event messge

* remove unnecessary sanitization

* add sanitize error message tests

* fix tests

* save wip. almost done

* fix screen test

* fix screen test

* remove non working test

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>

* chore: centralize license header checks (#952)

* chore: centralize license header scripts

* chore: run license header checks from root

* add header to other files

* add header to bundle

* add migration script and update check license headers

* convert license to mobile sdk

* migrate license headers

* remove headers from common; convert remaining

* fix headers

* add license header checks

* update unsupported passport screen (#953)

* update unsupported passport screen

* yarn nice

* Migrate Analytics  (#951)

* setup analytics adapter for self mobile sdk client and use in app

* wrap for context

* fix build

* yarn types is an alias for build when build just compiles ts

* ok unlock

* deeper

* ok this looks to work

* fix license check

* make sure it starts with this line

* someone didnt commit

* fix double analytics bug and builds

* lint

* Read document catalog from selfClient (#936)

* [SELF-676] feat: upgrade React Native from 0.75.4 to 0.76.9 (#943)

* chore: upgrade build tooling to Node 22 and AGP 8.6

* chore: upgrade react-native to 0.76.9

* update lock files and formatting

* fix path

* fix: handle hermes-engine cache mismatch in CI after React Native upgrade

- Add fallback logic to run 'pod update hermes-engine' when pod install fails
- This resolves CocoaPods cache issues that occur after React Native version upgrades
- Fixes CI pipeline failures on codex/update-core-tooling-for-react-native-upgrade branch

* fix: improve hermes-engine cache handling in CI

- Preemptively clear CocoaPods cache before pod install
- This prevents dependency analysis failures that occur when cached podspecs conflict
- Addresses the root cause: cache conflicts during 'Analyzing dependencies' phase
- Keeps fallback logic for additional safety

* fix: handle hermes-engine cache in mobile-bundle-analysis workflow

- Add pod-install-with-cache-fix.sh script to handle hermes-engine cache conflicts
- Update install-app:setup script to use the new cache fix approach
- This fixes the mobile-bundle-analysis.yml workflow failures after React Native upgrade
- Proactively clears CocoaPods cache and has fallback for hermes-engine updates

* formatting

* fix: robust hermes-engine cache handling in CI workflows

- Apply comprehensive cache clearing to mobile-ci.yml and mobile-e2e.yml
- Pre-emptively run 'pod update hermes-engine' before pod install
- Clear multiple cache locations to handle CI environment differences
- This prevents 'hermes-engine differs from Pods/Local Podspecs' errors
- Fixes all workflows affected by React Native 0.76.9 upgrade cache issues

* fixes

* clean up

* update lock files

* fix tests

* sort

* fixes

* fix ci

* fix deployment target

* android fixes

* upgrade fix

* fixes

* fix: streamline mobile CI build and caching (#946)

* fix: streamline mobile CI build and caching

* Enable mobile E2E tests on codex/fix-mobile-ci-workflow-errors branch

* test

* simplify and fix path

* workflow fixes

* fix loading on 0.76.9

* clean up unnecessary comments

* fix readme

* finalize upgrade to 0.76.9

* fix android build and upgrade

* fix bundler caching

* download cli to fix "yarn start" issues

* fix cli build erorr

* fix script path

* better path

* abstract build step to prevent race condition

* fixes

* better cache

* fix corepack build error

* update lock

* update lock

* add yarn cache to workflows

* fix test building

* ci caching improvements

* fix common type check

* fix common ci

* better mobile sdk alpha building logic

* chore: speed up mobile e2e workflow (#962)

* chore: speed up mobile e2e workflow

* chore: disable android e2e job

* chore: speed up ios build

* fix: bundle js for ios debug build

* fix e2e

* fix mobile ci (#964)

* feat: improve mixpanel flush strategy (#960)

* feat: improve mixpanel flush strategy

* fixes

* fix build

* update lock

* refactor methods

* conslidate calls

* update package and lock

* refactor: remove namespace imports (#969)

* refactor: remove namespace imports

* refactor: use named fs imports

* refactor(app): replace path and fs namespace imports

* format

* format

* Mixpanel tweaks (#971)

* udpates

* fox

* update license

* Add DSC parsing check (#836)

* Handle missing dsc parsed

* nice

* fix test

* throw

* fix

* chore(app): upgrade dependencies (#968)

* chore(app): upgrade dependencies

* update package

* update lock files

* fixes

* lock

* fix

* Auth Adapter +  (#958)

* basic auth adapater

* remove SelfMobileSDk, this was another architecture which the adapter patern replaced

* rename to avoid confusion with client.test.ts

* basic auth adapater

* remove SelfMobileSDk, this was another architecture which the adapter patern replaced

* rename to avoid confusion with client.test.ts

* self

* fix

* remove prototypes

* make sure its mounted

* fix tests

* fmt

* require required adapters

* fix types

* not a partial

* adds missing exports

* fix missing data

* Fix nfc configuration scanning issue (#978)

* fix nfc scanning on ios and android

* save test

* fix tests

* fix lint

* Chore fix ios nfc scanning and compiling (#979)

* fixes

* silence error

* fix debugge

* fix nfc scanning

* lint and pipeline fixes

* large runner (#980)

* chore: update to macos latest large runner (#981)

* bump up to macos-latest-large

* fix ci

* Move loadSelectedDocument to SDK (#967)



Co-authored-by: Aaron DeRuvo <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* docs: update mobile SDK migration progress (#982)

* docs: record app integration progress

* docs: consolidate mobile SDK migration tracking

* docs: humanize migration tracking and merge prompts

* docs: add common consolidation tasks

* docs: reprioritize migration tasks

* docs: soften migration plan tone

* docs: detail agent prompts with file paths

* docs: catalog Linear tasks for SDK

* updates

* remove artifact management

* moves validateDocument functions into the common package. (#977)

* moves validateDocument functions into the common package.

* fix build issues and lint

* handle bad connections better in nullifiier

* add an abort controler to nullifer fetcher,  ignore fals positives

* import types separately

* take it as an arg

* chore: update yarn.lock

* chore(app): resolve lint warnings (#990)

* chore(app): resolve lint warnings

* update lock

* clean up any types

* fix types

* feedback from cr

* [SELF-703] feat: Migrate mock generator to mobile sdk (#992)

* feat: expose mock generator

* formatting

* fix tests and lint

* rename passport to document

* fix types

* [SELF-698] scaffold mobile sdk demo app (#993)

* chore: scaffold mobile sdk demo app

* test: cover demo app menu

* prettier and types

* sort

* add android app foundation

* fix android loading

* get ios app running

* update script

* cr feedback

* disable fabric

* fixes

* fixes

* fix

* SELF-702: Refactor navigation structure and dev utilities (#994)

* Refactor navigation and dev screens

* refactor: rename passport screens to document

* fixes

* add missing header

* fixes

* type files

* feat: clarify proof verification analytics (#996)

* feat: increase sha256 byte size and add new rsa circuits (#986)

* feat: increase sha256 byte size and add new rsa circuits

* feat: modularise the rsa fp pow mod

* chore: comment signature verifier for testing

* fix: sha256_sha256_sha224_ecdsa_secp224r1

* lint

* chore: implement google play suggestions (#997)

* google play suggestions

* update gitguardian ignore

* remove unused

* chore: address yarn lock issues (#1004)

* address yarn lock issues

* fix postinstall

* skip postinstall for ci (#1005)

* [SELF-654] feat: add native modules (#919)

* feat: add ios native modules

* fix: extractMRZ

* Add android OCR native module

* wire native mrz module with adapter

* wire Native modules and fix tests

* fixes

* fix license header logic

* fix tests

* fix types

* fix: ci test

* fix: android build ci

* fix: ios build CI

* add podfile.lock

* add yarn.lock

* update lock files

* add yarn.lock

* add license

* order methods

* update lock

* pipeline fixes

* prettier

* update lock file

* fix native modules on external apps

* bundle @selfxyz/common into mobile-sdk-alpha

* chore: address yarn lock issues (#1004)

* address yarn lock issues

* fix postinstall

* update lock

* fix build issues

* fix pipeline issue

* fix ci

* fix bad merge

* fix android ci

* fix ci errors

* fix mobile sdk ci. stop gap fix for now until we create a package

* tweaks

* retry aapt2 approach

* use ^0.8.4 instead of ^0.8.0 due to the use of custom errors

* workflow fixes

* fix file

* update

* fix ci

* test ci fix

* fix test

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>

* chore: update dev with staging 09/06/25 (#1007)

* update CI

* bump iOS version

* update readme

* update mobile-deploy ci

* bump version iOS

* update workflow to use workload identity federation (#933)

* update workflow to use workload identity federation

* add token permissions

* correct provider name

* chore: incrementing android build version for version 2.6.4 [github action]

---------

Co-authored-by: Self GitHub Actions <[email protected]>

* update ci

* update ci

* update ci

* update ci

* update ci

* fix ci

* fix ci

* fix ci

* remove fastlane use for android

* bump iOS build version

* update CI python script

* iterate on CI

* iterate on CI

* iterate on CI

* Dev (#941)

* SDK Go version (#920)

* feat: helper functions and constant for go-sdk

* feat: formatRevealedDataPacked in go

* chore: refactor

* feat: define struct for selfBackendVerifier

* feat: verify function for selfBackendVerifier

* feat(wip): custom hasher

* feat: SelfVerifierBacked in go

* test(wip): scope and userContextHash is failing

* test: zk proof verified

* fix: MockConfigStore getactionId function

* chore: refactor

* chore: remove abi duplicate files

* chore: move configStore to utils

* chore: modified VcAndDiscloseProof struct

* chore: more review changes

* feat: impl DefaultConfig and InMemoryConfigStore

* chore: refactor and export functions

* fix: module import and README

* chore: remove example folder

* chore: remove pointers from VerificationConfig

* chore: coderabbit review fixes

* chore: more coderabbit review fix

* chore: add license

* fix: convert attestationIdd to int

* chore: remove duplicate code

---------

Co-authored-by: ayman <[email protected]>

* Moving proving Utils to common (#935)

* remove react dom

* moves proving utils to the common

* need to use rn components

* fix imports

* add proving-utils and dedeuplicate entry configs for esm and cjs.

* must wrap in text component

* fix metro bundling

* fix mock import

* fix builds and tests

* please save me

* solution?

* fix test

* Move proving inputs to the common package (#937)

* create ofactTree type to share

* move proving inputs from app to register inputs in common

* missed reexport

* ok

* add some validations as suggested by our ai overlords

* Fix mock passport flow (#942)

* fix dev screens

* add hint

* rename

* fix path

* fix mobile-ci path

* fix: extractMRZ (#938)

* fix: extractMRZ

* yarn nice && yarn types

* fix test: remove unused

* fix mobile ci

* add script

---------

Co-authored-by: Justin Hernandez <[email protected]>

* Move Proving attest and cose (#950)

* moved attest and cose utils to common

with cursor converted tests in common to use vitest and converted coseVerify.test to vitest after moving from app to common

what does cryptoLoader do?

* moved away

* get buff

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* SELF-253 feat: add user email feedback (#889)

* feat: add sentry feedback

* add sentry feedback to web

* feat: add custom feedback modal & fix freeze on IOS

* yarn nice

* update lock

* feat: show feedback widget on NFC scan issues (#948)

* feat: show feedback widget on NFC scan issues

* fix ref

* clean up

* fix report issue screen

* abstract send user feedback email logic

* fixes

* change text to Report Issue

* sanitize email and track event messge

* remove unnecessary sanitization

* add sanitize error message tests

* fix tests

* save wip. almost done

* fix screen test

* fix screen test

* remove non working test

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>

* chore: centralize license header checks (#952)

* chore: centralize license header scripts

* chore: run license header checks from root

* add header to other files

* add header to bundle

* add migration script and update check license headers

* convert license to mobile sdk

* migrate license headers

* remove headers from common; convert remaining

* fix headers

* add license header checks

* update unsupported passport screen (#953)

* update unsupported passport screen

* yarn nice

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: ayman <[email protected]>
Co-authored-by: Aaron DeRuvo <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* bump version

* bump yarn.lock

* update ci (#966)

* chore: Manually bump and release v2.6.4 (#961)

* update lock files

* bump and build android

* update build artifacts

* show generate mock document button

* update lock

* fix formatting and update failing e2e test

* revert podfile

* fixes

* fix cold start of the app with deeplink

* update ci

* update ci

* Sync MARKETING_VERSION to iOS project files after version bump

* chore: incrementing android build version for version 2.6.4 [github action] (#976)

Co-authored-by: remicolin <[email protected]>

* chore: add build dependencies step for iOS and Android in mobile deploy workflow

* chore: enhance mobile deploy workflow by adding CMake installation step

* bump android build version

* chore: incrementing android build version for version 2.6.4 [github action] (#985)

Co-authored-by: remicolin <[email protected]>

* chore: configure Metro bundler for production compatibility in mobile deploy workflow

* chore: incrementing android build version for version 2.6.4 [github action] (#987)

Co-authored-by: remicolin <[email protected]>

* Revert "chore: configure Metro bundler for production compatibility in mobile deploy workflow"

This reverts commit 60fc1f2580c2f6ad3105d8b904d969412a18bd2e.

* reduce max old space size in mobile-deploy ci

* fix android french id card (#957)

* fix android french id card

* fix common ci cache

* feat: log apdu (#988)

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>

* unblock ci

* fix merge

* merge fixes

* fix tests

* make ci happy

---------

Co-authored-by: turnoffthiscomputer <[email protected]>
Co-authored-by: pputman-clabs <[email protected]>
Co-authored-by: Self GitHub Actions <[email protected]>
Co-authored-by: turnoffthiscomputer <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: ayman <[email protected]>
Co-authored-by: Aaron DeRuvo <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* chore: fix yarn format (#1009)

* fix yarn format

* yarn format

* fix lint

* undo temporary disabling

* pipeline fixes

* revert nvmrc change

* add new home screen (#1019)

* add new home screen

* fix typing issue

* yarn nice

* chore: update the cpp build script (#1021)

* chore: install node (#1022)

* chore: use node v22 (#1023)

* chore: install yarn (#1024)

* chore: yarn cache (#1025)

* chore: sanitise node version (#1026)

* remove lazy loading (#1018)

* remove lazy loading

* fix tests

* formatting

* fix imports and web ci

* fix tests

* fix building

* fix

* debug ci

* fix web ci issue

* fix

* fix

* fix ci

* remove web render test

* coderabbit feedback

* fix ci

* use import

* fix lint

* fix compiling

* update lock

* update lock

* fix: update yarn.lock hash for @selfxyz/mobile-sdk-alpha

Resolves CI error where yarn install --immutable failed due to
outdated package hash. The hash changed from b2afc4 to f9ebb9.

* fix: update yarn.lock hash after mobile-sdk-alpha changes

- Hash changed from c0e6b9 to 0d0f72 due to package modifications
- Cleaned caches and regenerated lockfile to ensure consistency
- This resolves CI cache mismatch where old artifacts had stale hash

* fix: update yarn.lock hash after building mobile-sdk-alpha

- Final hash: 89f5a6 (includes built dist artifacts)
- Built mobile-sdk-alpha to ensure package is in stable state
- This should resolve CI immutable install errors

* fix yarn lock and build

* chore(ci): improve mobile e2e caching (#1010)

* chore(ci): improve mobile e2e caching

* chore(ci): restore deriveddata cache

* chore(ci): remove ios deriveddata cache

* chore(ci): cache ios derived data

* chore(ci): optimize mobile deploy caching

* chore(ci): enable ccache for ios e2e builds

* fix(ci): add ccache path for ios e2e

* moves ofac and protocol store (#1012)

* move ofact tree fetch to common

* move protocol store to the msdk, fix some dependencies on msdk

* chore: remove register id from register circuits (#1028)

* chore: remove register id from register circuits

* chore: only use 128ram instance

* Feat/build cpp (#1029)

* chore: remove register id from register circuits

* chore: only use 128ram instance

* chore: build 2 circuits at a time

* Remove navigationRef from provingMachine (#1011)

* SDK: minimize amount of data sent through PROVING_PASSPORT_NOT_SUPPORTED event (#1030)

* Fix mock passport generation (#1031)

* fix mock passport generation

* fix mobile ci tests

* Feat/aadhaar (#949)

* make contract sdk simpler (#514)

* make contract sdk simpler

* reduce root inputs

* delete convert function

* summarize our library

* update npm package

* update package version

* update attestation id

* add util function to get revealed data

* Revert "make contract sdk simpler (#514)" (#518)

This reverts commit 847b88d5ecc0d449b976a552f68af38eec8e561b.

* merge dev into main (#576)

* Feat: Show error code in SDK (#500)

* feat: emit `error_code` and `reason` in app

* feat: add `onError` in sdk

* feat: Display reason in app

* lint & fmt

* feat: add scrollview in ProofRequestStatusScreen for long reasons

* Fix input generation for 521bit curves (#481)

* fix EC point padding for 521 bit curves

* rename modulus to point in findStartIndexEC as it is a point

* simplify matching logic

* simplify padding logic

* remove comment

* remove log

removing .only so the CI/CD runs circuit tests

fix disclosure test

fix scope in test

fix scope error in circuit tests

remove .only

fix test

* run ci/cd

* Feat/simpler contract sdk (#519)

* make contract sdk simpler

* reduce root inputs

* delete convert function

* summarize our library

* update npm package

* update package version

* update attestation id

* add util function to get revealed data

---------

Co-authored-by: motemotech <[email protected]>

* forgot to include package update (#521)

* Bump version to 2.5.1 (#522)

* bump version

* update fastlane

* fix bump version

* bump build and add todo

* disable commit for now

* [SEL-154] Step 1: Scan your passport (#511)

* simplify navigation logic

* use aesop design hook

* save wip

* add new aesop redesign screens

* save wip design

* refactor nav bar logic

* fix paths

* save wip

* stub progress navbar and save wip

* save wip progress bar animation

* save wip progress bar, almost done with design

* fix progress bar design

* fix bottom padding

* disable git commit for now

* fix flaky android downloads that causes pipeline to crash

* update lock for ci

* [SEL-46] FE: Add minimum bottom padding (#510)

* fix bottom padding for smaller screens

* fix podfile post install hook permissions check

* update pod lock and disable git commit action step for now

* update lock

* fix flaky android downloads that causes pipeline to crash

* fix: improve error handling for forbidden countries list mismatch (#494)

* Update SelfBackendVerifier.ts

* Update constants.ts

* Update formatInputs.ts

* Update formatCallData.ts

* DX: Auto format on save (#526)

* save wip

* use elint instead of prettier to sort imports

* set imports to warn

* sync prettier settigns

* update prettier settings

* save working version

* fix export and disable mobile pipeline for now

* limit auto formatting to the app folder

* remove artefacts

* SEL-187: Make bottom layout scrollable on smaller screens (#525)

* fix design check

* add an option to disable local sending of sentry events

* better sentry enable / disable

* fix scan passport height

* make bottom layout scrollable so it doesn't squish top screen

* simpler logic check. don't create new env var

* fix internet connection issues

* readd comment

* use isConnected instead of internet reachable

* use a dynamic bottom panel height

* add missing recovery screens

* move aesop below

* remove dupe export

* fix rebase

* fix android package download issue

* Feat/extend id support (#517)

* refactor proving impleting xstate, speedup proving

* add disclosure proof support

* keep refactoring provingMachine, clean old implementation

* call init method when switching from dsc to register

* rebase with dev to display why the proof verification failed

* refactor ws connexion between front-end and mobile to retrieve self-app

* update the webclient at proofVerification and use selfAppStore in provingMachine

* fix provintStore.init in ProveScreen

* yarn nice

* fetch data correctly in splash screen

* Bump build versions for 2.5.1 (#531)

* release new builds

* fix app and build versions

* fix env check

* display error animation on failure on loading screen (#532)

* display error animation on failure on loading screen

* remove log

---------

Co-authored-by: Justin Hernandez <[email protected]>

* ci: bump actions/checkout to v4 (#529)

* make contract sdk simpler (#514)

* make contract sdk simpler

* reduce root inputs

* delete convert function

* summarize our library

* update npm package

* update package version

* update attestation id

* add util function to get revealed data

* Revert "make contract sdk simpler (#514)" (#518)

This reverts commit 847b88d5ecc0d449b976a552f68af38eec8e561b.

* ci: bump actions/checkout to v4

---------

Co-authored-by: nicoshark <[email protected]>
Co-authored-by: turnoffthiscomputer <[email protected]>

* fix italy (#530)

* Fix/proving machine endpoint type (#538)

* store endpoint type in proving machine

* yarn nice

* fix splash screen error (#539)

* New bug fix build for v2.5.1 (#540)

* bump new build for dev fixes

* update lock

* reinstall before running local deploy

* SEL-178: Improve haptic feedback library (#535)

* fix dev settings typing

* add dev screens file

* save haptic feedback progress

* change ordedr

* fix initial route and add haptic feedback screen to dev settings options

* add delete scripts (#542)

* update staging registry address (#545)

* feat: Add Disclose history (#533)

* feat: Add Disclose history

* fix: Duplicate history in list

* fix: Outdated disclosures

* Delete app/ios/Self copy-Info.plist

* allow a scale of up to 1.3 (#546)

* allow a scale of up to 1.3

* update lock files

* clean up unused imports

* fix settings

* add common sdk (#537)

* add common sdk

* remove sdk backend api

* remove registry

* regenerate sha256 rsa dsc each time

* download ski-pem dynamically on staging, refactor initpassportDataParsing

* add state machine for button on prove screen, improve ux on splash screen

* fetch ski-pem in production

* fix linter issues

* fix prove screen button bugs

* update podfile.lock and yarn.lock

* run linter in circuits repo

* bump build

* bump version for sentry debugging

* bump ios to version 118

---------

Co-authored-by: Justin Hernandez <[email protected]>

* better connection check (#548)

* Clean up navigation and setup Jest (#549)

* remove dupe account screens and prefer the term home

* organize screen loading better

* sort keys

* rename screen files wip

* fix deleted directory issues

* rename folders

* fix paths and naming

* save working jest import test

* save base working jest navigation test

* finalize navigation refactor and jest test

* update test name and podfile lock

* remove unused packages

* use the correct version of react test renderer

* bump build (#552)

* Eth dublin (#554)

* add mock id card generator

* add genMockIdDoc in common/sdk exports

* onboard developer id using deeplink, allow custom birthdate on mockpassport

* log more dsc info (#558)

* Push notification (#536)

* add push notification feature

* merge new app impl

* change dsc key

* import

* reverse mock dsc

* worked in the ios

* checked in android

* update url and delete console

* delete small changes

* lint

* add yarn.lock

* fix warning message

* add mock notification service for test code

* fix path for the mock implementation

* add mock deeplink to the test code

* nice notificationServiceMock.js

* delete unused firebase related implementation

* fix wording and UI related to notification service

* hotfix on mockdatascreen

---------

Co-authored-by: turnoffthiscomputer <[email protected]>

* Fix deeplink 2 (#560)

* fix deeplink

* fix deeplink

* yarn nice

* feat: Use vision for MRZ scanning (SEL-47) (#557)

* feat: Use vision for MRZ scanning

* modify label to position the smartphone during the OCR scan

---------

Co-authored-by: turnoffthiscomputer <[email protected]>

* SEL-255: improved loading screen with estimated wait times (#550)

* create new loading screen and rename static to misc

* fix route

* save wip loading screen

* save wip animation

* save static wip design

* continue

* splash

* add a loading screen text helper

* add test for loading screen text

* save wip. almost there

* update haptic logic

* better feedback and add dev scren

* save current work

* update text logic and tests

* load passport metadata in loading screen

* simplify and fix tests

* test for additional exponents

* add new animation

* rename file

* consolidate ui useEffect and fix loading screen layout

* fix current state

* remove mockPassportFlow param

* merge new loading screen and new notification logic

* simplify

* update lock

* use passportMetadata instead of metadata

* save simplification

* update loading text based on pr feedback and tests

* Bump v2.5.1: ios 122; android 60 (#561)

* increment build to 120

* bump builds for 2.5.1. ios 121; android 60

* clean up logic

* upgrade react native firebase for privacy manifests

* update react native keychain to fix could not recover issue (#564)

* fix: update ocr corrections (#563)

* Chore: Polish proof history to prep for release (#566)

* clean up nav and home boundaries, passport data screen insets

* migrate proof history screen out of settings

* minor clean up

* save wip

* add new ibm plex mono font and clean up proof detail screen

* remove test data

* remove extra loading screen text

* remove unnecessary ceil

* Bump v2.5.1; ios 123; android 62 (#565)

* bump to build 61

* bump ios version

* update version

* Feature/add prettier formatter (#568)

* Add Prettier configuration and ignore files for code formatting

- Created .prettierignore to exclude specific directories and files from formatting.
- Added .prettierrc.yml with custom settings for print width and trailing commas.
- Updated package.json to include Prettier and its Solidity plugin as dependencies, along with scripts for formatting and checking code.

* Run prettier formatting

* fix nationality using mock passports

* SEL-181 & SEL-252: Update mobile app events (#570)

* improve analytics handling

* add error boundary that flushes segment events before error occurs

* upgrade segment analytics package

* flush analytics when user encounters error screen

* track all click events

* add tracking to loading screen

* better init and click event names

* track cloud backup and modal actions

* use __DEV__ for debugging

* add tracking to account recovery, auth, mock data

* return false instead of throwing

* add more tracking events

* save wip event updating

* abstract analytic event names

* update click events

* clean up

* move reasons comment

* add unsupported passport event

* Feature/enhance self verification root (#569)

* Add SelfVerificationConsumer contract for self-verification logic

- Introduced an abstract contract, SelfVerificationConsumer, that extends SelfVerificationRoot.
- Implemented nullifier tracking, verification success events, and customizable validation and update methods for nullifiers.
- Added error handling for nullifier check failures and hooks for derived contracts to implement custom logic after successful verification.

* Add SelfHappyBirthday contract example using SelfVerificationConsumer

- Introduced SelfHappyBirthday contract that allows users to claim USDC on their birthday.
- Integrated SelfVerificationConsumer for handling verification and nullifier tracking.
- Added functions to set claimable amount and window, along with event emissions for state changes.
- Implemented logic to check if the claim is within the user's birthday window and transfer USDC accordingly.

* Refactor imports in HappyBirthday contract for better organization

- Updated import statements in HappyBirthday.sol to use relative paths for ISelfVerificationRoot, SelfCircuitLibrary, and SelfVerificationConsumer.
- Improved code readability and maintainability by organizing imports more logically.

* Refactor Airdrop contract to use SelfVerificationConsumer for registration logic

- Updated Airdrop contract to inherit from SelfVerificationConsumer instead of SelfVerificationRoot.
- Refactored mappings for user identifiers and nullifiers for improved clarity and functionality.
- Enhanced error handling and updated function parameters for consistency.
- Implemented new validation and update methods for nullifiers, streamlining the registration process.
- Removed deprecated verifySelfProof function and integrated logic into new methods.

* Add events and refactor SelfVerificationRoot and related contracts

- Introduced new events in SelfVerificationRoot for verification configuration updates, scope changes, and attestation ID management.
- Updated Airdrop contract to remove deprecated events and added a new event for Merkle root updates.
- Refactored SelfPassportERC721 to inherit from SelfVerificationConsumer, enhancing verification logic and event handling.
- Improved function parameters for consistency and clarity across contracts.

* Refactor contracts to use SelfVerificationRoot and enhance verification logic

- Removed SelfVerificationConsumer contract and updated related contracts to inherit from SelfVerificationRoot.
- Refactored mappings and event emissions in Airdrop, HappyBirthday, and SelfPassportERC721 for improved clarity and functionality.
- Enhanced verification success hooks to include user identifiers and nullifiers for better tracking.
- Updated constructor parameters for consistency across contracts and improved error handling for user registration and claims.

* Refactor constructor in SelfPassportERC721 for improved readability

* Refactor function parameters in SelfVerificationRoot and related contracts

* Refactor constructor parameter names in IdentityVerificationHub, Airdrop, IdentityRegistry, and ProxyRoot contracts for improved clarity and consistency

* fix getCircuitName function (#575)

* fix getCircuitName function

* fix getCircuitName function

* feat: Read ID cards (#571)

* Update GitHub checkout action from v3 to v4 (#544)

* Bump build version 2.5.2 to test react native keychain (#572)

* bump build and version

* bump version 2.5.2

* don't downgrade react native keychain

* update app/README.md toolchain instructions (#140)

* bump build (#580)

---------

Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: turboblitz <[email protected]>
Co-authored-by: motemotech <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: crStiv <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: James Niken <[email protected]>
Co-authored-by: Kevin Lin <[email protected]>
Co-authored-by: leopardracer <[email protected]>
Co-authored-by: Olof Andersson <[email protected]>

* feat(wip): register circuit for aadhaar

* chore: add anon aadhar circuits

* chore: remove sc and disclose selfrica test

* feat: extract aadhaar qr data

* test: aadhaar qr data extract circuit

* test: aadhaar register  circuit

* feat: extract pincode and ph no last 4 digit

* fix: register aadhaar nullifier and commitment

* test: Verify commitment circuit of aadhaar

* feat: add photoHash inside commitment

* feat: build Aadhaar OFAC SMT

* feat: ofac check and reveal data (test done)

* test: qr extractor for custom data input

* feat: add state as reveal data inside VC and disclose

* chore: add comments

* fix: num2Ceil component

* chore: review changes

* chore: use passport SignatureVerifier

* fix: signatureVerifier inputs

* feat: extract ascii values of fields

* feat: provide users the flexibility to reveal specific characters of a field

* chore: refactor

* test: register aadhaar for tampered data

* test(wip): should return 0 if in ofac list

* test: ofac check

* test: register aadhaar circuit for different qr data

* merge dev into main (#683)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

* implement self uups upgradeable (#592)

* implement self uups upgradeable

* small changes in identityVerificationHubImplV2

* delete aderyn.toml

* chore: add custom verifier

* chnage return output

* feat: use self structs and a Generic output struct

* feat: add userIdentifier, nullifier, forbiddencountries to returned output

* add root view functions from registry

* fix: build and compilation errors

* add userDefined data into selfVerificationRoot

* "resolve conflicts"

* fix compilation problem

* fix how to register verification config

* test: CustomVerifier

* fix verification root and hub integration

* add scope check in hub impl

* replace poseidon hash to ripemd+sha256

* add todo list

* feat: refactor and add test cases for generic formatter

* add performUserIdentifierCheck in basicVerification

* change how to handle additionalData and fix stack too deep

* start adding test codes

* fix dependency problems in monorepo

* fix: forbidden countries (#612)

LGTM!

* able to run test code

* pass happy path

* delete unused codes

* change error code name, add caller address validation and add scripts to run test and build in monorepo

* add all test cases in vcAndDisclose flow

* remove comment out

* chore: use actual user identifier outputs

* success in registration tests

* cover all cases

* pass contractVersion instead of circuitVersion

* fix disclose test

* chore: add natspecs for ImplHubV2, CustomVerifier and GenericFormatter

* change val name and remove unused lines

* add val name change

* remove userIdentifier from return data

* feat: use GenericDiscloseOutput struct in verfication hook  fix test cases for user identifier

* chore: change the function order for Hub Impl V2 (#625)

* fix nat specs

* add nat spec in SelfStructs

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* prettier (#629)

* CAN auth - android (#613)

* add missed files

* add NFCMethodSelectionScreen

* bump android build

---------

Co-authored-by: Justin Hernandez <[email protected]>

* feat: add MRZ correction method to NFCMethodSelectionScreen (#627)

* add npm auth token env (#632)

* bump sdk version (#633)

* publish npm package when merging on dev

* bump common sdk version

* replace yarn publish by npm publish

* update common package version

* Simplify dev mode gesture (#635)

* Simplify developer mode gesture

* Enable dev mode on MockData screen with five taps

* add build smt function to common sdk

* update vc_and_disclose_id test (dev branch) (#641)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* Show modal on NFC scan error (#642)

* Add help button and error modal actions

* fix the screen management

* yarn nice

* Bump build v2.5.4: ios 132; android 71 (#631)

* bump version and build numbers

* remove tamagui/toast

* fix marketing version

* fix: update TD1 and TD3 checks (#643)

* bum yarn.lock

* Bump build: ios 133; android 72 and build fixes (#654)

* update gesture version and bump android build

* bump and fix ios build

* update lock files

* fixes

* fix fotoapparat library source

* Update example contracts to include EUID usage (#656)

* refactor: update HappyBirthday contract to V2 with support for E-Passport and EUID cards, introduce bonus multipliers, and enhance verification logic

* refactor: update Airdrop contract to V2 with support for E-Passport and EU ID Card attestations

* refactor: remove BASIS_POINTS constant from Airdrop contract

* feat: introduce SelfIdentityERC721 contract for issuing NFTs based on verified identity credentials, replacing SelfPassportERC721

* fix: update verification functions in Airdrop, HappyBirthday, and SelfIdentityERC721 contracts to use customVerificationHook

* cherry pick commit from add-test-self-verification...

* block non-dev pr to main branch

* audit fixes (#645)

* merge dev branch into main (#624)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>

* update contracts (#628)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

* implement self uups upgradeable (#592)

* implement self uups upgradeable

* small changes in identityVerificationHubImplV2

* delete aderyn.toml

* chore: add custom verifier

* chnage return output

* feat: use self structs and a Generic output struct

* feat: add userIdentifier, nullifier, forbiddencountries to returned output

* add root view functions from registry

* fix: build and compilation errors

* add userDefined data into selfVerificationRoot

* "resolve conflicts"

* fix compilation problem

* fix how to register verification config

* test: CustomVerifier

* fix verification root and hub integration

* add scope check in hub impl

* replace poseidon hash to ripemd+sha256

* add todo list

* feat: refactor and add test cases for generic formatter

* add performUserIdentifierCheck in basicVerification

* change how to handle additionalData and fix stack too deep

* start adding test codes

* fix dependency problems in monorepo

* fix: forbidden countries (#612)

LGTM!

* able to run test code

* pass happy path

* delete unused codes

* change error code name, add caller address validation and add scripts to run test and build in monorepo

* add all test cases in vcAndDisclose flow

* remove comment out

* chore: use actual user identifier outputs

* success in registration tests

* cover all cases

* pass contractVersion instead of circuitVersion

* fix disclose test

* chore: add natspecs for ImplHubV2, CustomVerifier and GenericFormatter

* change val name and remove unused lines

* add val name change

* remove userIdentifier from return data

* feat: use GenericDiscloseOutput struct in verfication hook  fix test cases for user identifier

* chore: change the function order for Hub Impl V2 (#625)

* fix nat specs

* add nat spec in SelfStructs

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* prettier (#629)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* fix: vc_and_disclose_id test (#640)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* fix: check if a config id exists

* chore: change the function where the config not set verification is happening

* fix: add await

* feat: add getConfigId function in SelfVerificationRoot (#650)

* feat: add getConfigId function in SelfVerificationRoot

* update comment

---------

Co-authored-by: motemotech <[email protected]>

* chore: fix ofac end index in eu id cards

* chore: fix tests

* fix: example contracts and tests

---------

Co-authored-by: turnoffthiscomputer <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>

* Update deployment module for Identity Verification Hub V2 with detailed documentation and library linkage for CustomVerifier. Update initialization process to reflect changes in V2 implementation, ensuring proper setup for proxy deployment. (#658)

* publish npm-package (#651)

* App/eu id updates (#638)

* fix build issues

* generate disclosure proof with euids

* generate disclosure proof with euids

* Eu id updates 2 (#648)

* update vc_and_disclose_id test (dev branch) (#641)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* Show modal on NFC scan error (#642)

* Add help button and error modal actions

* fix the screen management

* yarn nice

* Bump build v2.5.4: ios 132; android 71 (#631)

* bump version and build numbers

* remove tamagui/toast

* fix marketing version

* fix: update TD1 and TD3 checks (#643)

* bum yarn.lock

* add version and user defined data

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>

* remove the mock user define data

* get the useridentifier as a hash from the user defined data

* chore: add version and userDefinedData

* feat: use the version in register / dsc proofs as well

* update calculateUserIdentifierHash

* yarn nice

* refactor: consolidate user context data handling and update payload structure

* fix typing issues on sha1

* remove console.log(sha1)

* fix sha1 import

* refactor: streamline userDefinedData handling and adjust payload type for circuit

* refactor: update sha1 usage and enhance logging in calculateUserIdentifierHash

* yarn nice

* yarn lint common

* use ts-ignore for sha1 import

* fix app ci tests

* fix typing issue

* remove unused ts-ignore

* cast uuid before calling generateinputs

* bump qrcode version

* add tsup on the qrcode sdk

* fix: exports on selfxyz/qrcode

* update how we define config.version

* fix yarn imports

* yarn format

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: Ayman <[email protected]>

* Hotfix contract compile error (#660)

* Fix previous rebase error

* Refactor deployment module for Identity Verification Hub V2.

* Fix/sdk (#652)

* fix: sdk build configs

* chore: SelfBackendVerifier (WIP)

* feat: add custom verification

* feat: consider destination chain in user defined data

* chore: export attestation id

* chore: export attestation id

* chore: export config storage

* chore: don't throw an error if the proof is not valid

* chore: trim abi and rm typechain types

* refactor

* chore: rm unnecessary exports

* 📝 Add docstrings to `fix/sdk` (#653)

Docstrings generation was requested by @remicolin.

* https://github.com/selfxyz/self/pull/652#issuecomment-2992046545

The following files were modified:

* `sdk/core/src/utils/hash.ts`
* `sdk/core/src/utils/proof.ts`
* `sdk/core/src/utils/utils.ts`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* review fixes

* chore: fix package.json cjs types

* chore: add minor changes to checks

* feat: add InMemoryConfigStore, allIds constant and verificationResult type

* chore: export Verification config

* feat: change the verification config types

* fix: throw issues early if verification config is null

* fix: update yarn.lock file

* chore: lint

* fix: rm ts expect error directive

* fix: contract tests

* use excluded countries instead forbidden countries list

* chore: change types in constnats

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update npm-publish workflow and bump core package version to 1.0.0 (#661)

* update import

* Update get verification config visibility (#664)

* Update deployment module for Identity Verification Hub V2 to correct file paths and module name for deployment commands.

* Add troubleshooting documentation for verification issues in deployHubV2.ts. Include manual verification steps and common failure reasons to assist users during deployment.

* Change visibility of getVerificationConfigV2 function from internal to public in IdentityVerificationHubImplV2 contract to allow external access.

* Apply BUSL v1.1 license headers to app (#665)

* Add BSL license headers to app sources

* prettier

* fix license reference - https://spdx.org/licenses/BUSL-1.1.html

* bump build: android 73 (#659)

* Contracts/deploy staging (#668)

* update scripts

* deploy vc and disclose id

* fix the deployment scripts on staging

* update yarn.lock

* bump ios build and version (#669)

* configure coderabbitai (#670)

* tweak coderabbit

* bump

* more thorough test spec

* Apply BSL to app codebase (#639)

* Clean up root license wording

* Simplify SPDX header

* simplify license and rename BSL to BUSL

* fix merge issues

* fix missing method

---------

Co-authored-by: Justin Hernandez <[email protected]>

* SEL-423 apply xcode build suggestions (#671)

* apply recommended app settings from xcode

* stick to portrait orientation and update target settings

* remove app clip references

* Circuit audit fixes  (#644)

* feat: add range checks before use of LessEqThan and SelectSubArray

* fix: Num2Bits_strict to constrain virtualKey

* bump core version

* bump core version and fix ci

* chore: use npm_auth_token in yarnrc

* chroe: rm yarnrc changes

* chore: update npm publish

* chore: run npm publish manually

* chore: change hub contract address (#675)

* Update npm-publish.yml

* chore: use proper secret when publishing

* feat: enable publishing if workflow was triggered manually

* Contracts/update verifier (#673)

* update hardhat config

* update vc and disclose verifier

* update vc and disclose verifier script and run it

* update test self verification root

* update verifier

* bump sdk version and use new hub address

* chore: update zk-kit binary merkle root dep (#674)

* refactor deployment scripts (#678)

* feat: add register eu id instances (#682)

* feat: add register eu id instances

* feat: add new instances

* chore: update scripts

* chore: fix sig alg

* chore: rm circuits

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>
Co-authored-by: Nesopie <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Kevin Lin <[email protected]>
Co-authored-by: kevinsslin <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Eric Nakagawa <[email protected]>

* fix: commitment hash

* fix: register aadhaar test

* chore: refactor

* feat: reveal data in packed bytes

* feat: add constrain on delimiterIndices

* feat: reveal timestamp

* merge main to feat/aadhaar

* fix: tests

* feat: hash pubKey

* feat: add registry contract

* feat: Update HubImplV2 (WIP)

* add functions to generate aadhaar data (WIP)

* modularize aadhaar data generation (WIP)

* fix(wip): register test

* fix: test qr extractor

* fix

* chore: refactor functions

* feat: add age extractor and tested

* feat: add isMiniumAge check

* fix: prepareAadhaarTestData func

* registry contract tests

* feat: registry contract tests

* feat: extract fields from qr data bytes

* chore: refactor mockData

* feat: move minimum age to revealPackedData

* feat: create a constant.ts to retrive fields from unpacked bytes

* chore: refactor

* fix: exports

* rebase

* rebase

* feat: add public signal ,indices mapping

* chore: add public output to indices mapping

* fix:AADHAAR_PUBLIC_SIGNAL_INDICES

* feat: make nullifier public

* fix: nullifier cal for disclose circuits

* feat: merge isMiniumAgeValid and miniumAge signal

* fix: disclsoe test

* feat: support for user identifier and secret

* chore :refactor

* feat: ofac test last name , firstname

* feat: add forbidden_countries_list check

* feat: add tests for aadhaar (WIP)

* failing ofac tests

* feat: finish contract tests

* fix: merge conflicts

* update the common package to be usable in circuits and contracts

* lint everything

* coderabbit fixes

* chore: update name dob,yob aadhaar ofac tree

* feat: merge ofac and reverse ofac check into one

* test: merged ofac constrain

* SELF-253 feat: add user email feedback (#889)

* feat: add sentry feedback

* add sentry feedback to web

* feat: add custom feedback modal & fix freeze on IOS

* yarn nice

* update lock

* feat: show feedback widget on NFC scan issues (#948)

* feat: show feedback widget on NFC scan issues

* fix ref

* clean up

* fix report issue screen

* abstract send user feedback email logic

* fixes

* change text to Report Issue

* sanitize email and track event messge

* remove unnecessary sanitization

* add sanitize error message tests

* fix tests

* save wip. almost done

* fix screen test

* fix screen test

* remove non working test

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>

* chore: centralize license header checks (#952)

* chore: centralize license header scripts

* chore: run license header checks from root

* add header to other files

* add header to bundle

* add migration script and update check license headers

* convert license to mobile sdk

* migrate license headers

* remove headers from common; convert remaining

* fix headers

* add license header checks

* update unsupported passport screen (#953)

* update unsupported passport screen

* yarn nice

* feat: support new ofac trees

* fix: qr extractor tests

* chore: remove unassigned age signal

* chore: modify timestamp func comment

* fix: add constrain on photo bytes delimiter

* fix: add range check on minimumAge within 2^7

* fix: range check for country not in list

* chore: remove dummy constrain

* fix: assert lessthan

* fix: check is photoEOI valid

* fix: replace maxDataLength with qrPaddedLength for valid del indices

* feat: update forbidden countries in disclose and disclose id

* feat: convert name to uppercase

* fix: add constrain between delimiter and photoEOI

* feat: support for phno len 4 and 10

* chore: hard-code attestaion_ID to 3

* feat: calculate nullifier using uppercase name

* feat: add real id support

* fix: rebase error

* chore: refactor

* add new nullifier and commitment calc

* fix: reuse uppercase name from verify commitment

* feat: add a function that will iterate though all pubkeys

* chore: skip real id test

* chore: yarn format

* chore: update yarn.lock

* chore: rm trailing / from import

* chore: add support for issuing state

* chore: linting and types

* chore: rm types script from circuits

* chore: add license header

---------

Co-authored-by: nicoshark <[email protected]>
Co-authored-by: turnoffthiscomputer <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: turboblitz <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: crStiv <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: James Niken <[email protected]>
Co-authored-by: Kevin Lin <[email protected]>
Co-authored-by: leopardracer <[email protected]>
Co-authored-by: Olof Andersson <[email protected]>
Co-authored-by: vishal <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: kevinsslin <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Eric Nakagawa <[email protected]>

* fix: CLA not supported (#1027)

* fix: CLA not supported

* fix "yarn android" building

* remove unnecessary commands

---------

Co-authored-by: Justin Hernandez <[email protected]>

* chore: bump app version v2.6.5 (#1034)

* update gem lock

* bump build and version

* fix app versions

* chore: fix nfc passport reader private repo access (#1042)

* add internal repo pat

* update nfc passport reader location

* update workflows to use PAT to access NFC Passport Reader

* fix ci

* update logic to access private repo

* build(android): support 16KB page size (#1043)

* build(android): support 16KB page size

* fix 16kb

* update lock

* chore: bump v2.6.5 for release (#1036)

* bump build

* update to ssh clone to fix local build

* update podfile lock

* fix version

* Feat/build aadhaar (#1044)

* feat: build aadhaar circuits as well in the ci

* feat: add register aadhaar case handling

* fix aadhaar register output after building the cpp circuit (#1045)

* fix: metro js crypto module build issues (#1047)

* fix sdk build issues

* fix build error

* sort and fix dependencies

* add constants-browserify

* feat: add new verifiers (#1049)

* feat: add new verifiers

* format: contracts

* fix: ofac check to aadhaar (#1050)

* fix: hub-v2 (#1051)

* Add DisclosureVerified event for comprehensive verification tracking (#945)

* Add VerificationPerformed event to track verification calls

- Added VerificationPerformed event with comprehensive tracking fields
- Captures requestor contract, version, attestation ID, chain ID, config ID, user identifier, output, and user data
- Enhanced _executeVerificationFlow to return additional tracking data
- Event emission placed after verification completion for accurate tracking

* chore: run formatter

* chore: rename verify event name to DisclosureVerified

* move clearPassportData, markCurrentDocumentAsRegistered, reStorePassportDataWithRightCSCA to SDK (#1041)

* Move self app store to mobile sdk (#1040)

* chore(mobile-sdk-alpha): remove unused tslib dependency (#1053)

* remove tslib -- seems unused

* remove deps accidentally added to root

* build file

* remove unused imports (#1055)

* fix: sha256 signed attr tests (#1058)

* fix mock screen launch (#1059)

* Hotfix: Belgium ID cards (#1061)

* feat: parse belgium TD1 mrz android

* feat: Parse Belgium TD1 MRZ IOS

* fix: OFAC trees not found (#1060)

* fix: relax OFAC tree response validation

* test: cover OFAC tree edge cases

* fix stateless

* revert and fix types

* fix tests

* [SELF-723] feat: add structured NFC and Proof logging (#1048)

* feat: add structured NFC logging

* fix ci

* Fix: add deps

* logging fixes. use breadcrumbs

* fix android build

* update SeverityLevel

* [SELF-705] feat: add proof event logging (#1057)

* feat: add proof event logging

* refactor: unify sentry event logging

* fix types

* fix mock

* simplify

* code rabbit feedback

* fix tests

---------

Co-authored-by: seshanthS <[email protected]>

* skip on dev (#1063)

* don't get fancy just disable (#1064)

* saw it building so gonna try (#1065)

* Dev (#1074)

* chore: bump v2.6.5 rd2 (#1067)

* commit wip version bump

* remove from building

* chore: update tooling dependencies (#1069)

* chore: update tooling dependencies

* chore: align react typings and node types

* update lock

* chore: minor fixes across monorepo (#1068)

* small fixes

* fixes

* fix gesture handler error

* ci fixes

* fix yarn build; add workflow ci (#1075)

* add new workspace ci

* disable package version check for now

* build before checks

* format

* fix in future pr

* feat: add functions for disclosing aadhaar attributes (#1033)

* feat: add functions for disclosing aadhaar attributes

* format

* chore: update monorepo artifacts (#1079)

* remove unneeded artifacts, skip building circuits

* update md files

* cleans up unused parts of sdk interface, adds inline documentation, (#1078)

* cleans up unused parts of sdk interface, adds inline documentation,

* fix up build

* yolo

* Feat/aadhaar sdk (#1082)

* feat: add aadhaar support to the ts sdk

* feat: aadhaar support to go sdk

* chore: refactor

* move clearPassportData, markCurrentDocumentAsRegistered, reStorePassportDataWithRightCSCA to SDK (#1041)

* Move self app store to mobile sdk (#1040)

* chore(mobile-sdk-alpha): remove unused tslib dependency (#1053)

* remove tslib -- seems unused

* remove deps accidentally added to root

* build file

* remove unused imports (#1055)

* fix: sha256 signed attr tests (#1058)

* fix mock screen launch (#1059)

* Hotfix: Belgium ID cards (#1061)

* feat: parse belgium TD1 mrz android

* feat: Parse Belgium TD1 MRZ IOS

* fix: OFAC trees not found (#1060)

* fix: relax OFAC tree response validation

* test: cover OFAC tree edge cases

* fix stateless

* revert and fix types

* fix tests

* [SELF-723] feat: add structured NFC and Proof logging (#1048)

* feat: add structured NFC logging

* fix ci

* Fix: add deps

* logging fixes. use breadcrumbs

* fix android build

* update SeverityLevel

* [SELF-705] feat: add proof event logging (#1057)

* feat: add proof event logging

* refactor: unify sentry event logging

* fix types

* fix mock

* simplify

* code rabbit feedback

* fix tests

---------

Co-authored-by: seshanthS <[email protected]>

* skip on dev (#1063)

* don't get fancy just disable (#1064)

* saw it building so gonna try (#1065)

* chore: bump v2.6.5 rd2 (#1067)

* commit wip version bump

* remove from building

* chore: update tooling dependencies (#1069)

* chore: update tooling dependencies

* chore: align react typings and node types

* update lock

* chore: minor fixes across monorepo (#1068)

* small fixes

* fixes

* fix gesture handler error

* ci fixes

* fix yarn build; add workflow ci (#1075)

* add new workspace ci

* disable package version check for now

* build before checks

* format

* fix in future pr

* feat: add functions for disclosing aadhaar attributes (#1033)

* feat: add functions for disclosing aadhaar attributes

* format

* chore: update monorepo artifacts (#1079)

* remove unneeded artifacts, skip building circuits

* update md files

* chore: update hub contract address

* format

* fix: add aadhaar in AllIds

* chore: bump to v1.1.0-beta

---------

Co-authored-by: vishal <[email protected]>
Co-authored-by: Leszek Stachowski <[email protected]>
Co-authored-by: Aaron DeRuvo <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: seshanthS <[email protected]>

* feat: change to gcp attestation verification (#959)

* feat: change to gcp attestation verification

* lint

* fix e2e test

* chore: don't check PCR0 mapping if building the app locally

* fmt:fix

---------

Co-authored-by: Justin Hernandez <[email protected]>

* Mobile SDK: move provingMachine from the app (#1052)

* Mobile SDK: move provingMachine from the app

* lint, fixes

* fix web build?

* lint

* fix metro build, add deps

* update lock files

* move the status handlers and proving machine tests

* may it be

* fix up

* yolo

---------

Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Aaron DeRuvo <[email protected]>

* Revert "Mobile SDK: move provingMachine from the app (#1052)" (#1084)

This reverts commit 8983ac22688f731bca8890cbf9be9c85b4ac2bf…
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