Skip to content

feat: insert pin before to connect to specific badge#1783

Open
ctrlVnt wants to merge 12 commits into
fossasia:developmentfrom
ctrlVnt:security-pin
Open

feat: insert pin before to connect to specific badge#1783
ctrlVnt wants to merge 12 commits into
fossasia:developmentfrom
ctrlVnt:security-pin

Conversation

@ctrlVnt

@ctrlVnt ctrlVnt commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Fixes #1780

Changes

  • Added popup that ask the 4 numbers pin before to connect
  • Option is not activated by default, so added switch option in the settings

Important

To test you need this version of firmware: https://github.com/fossasia/badgemagic-firmware/actions/runs/28226361094?pr=163

Note

You can see that toasts are annoying, the #1732 solve this problem

Screenshots / Recordings

screen-20260629-154447-1782740609257.mov

This is the new information dialog:

Screenshot 2026-06-30 at 12 34 53

Checklist:

  • No hard coding: I have used resources from constants.dart without hard coding any value.
  • No end of file edits: No modifications done at end of resource files.
  • Code reformatting: I have reformatted code and fixed indentation in every file included in this pull request.
  • Code analyzation: My code passes analyzations run in flutter analyze and tests run in flutter test.

Summary by Sourcery

Add a PIN entry step before initiating badge data transfer to support badge authentication.

New Features:

  • Prompt users with a 4-digit PIN dialog before transferring data to a badge.
  • Send the entered PIN to the badge as a preliminary authenticated transfer message.

@sourcery-ai

sourcery-ai Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Adds a mandatory 4-digit PIN authentication dialog before badge data transfer and sends the entered PIN as a separate fixed message to the badge, plus introduces a reusable widget for the PIN dialog UI.

Sequence diagram for new PIN-gated badge transfer flow

sequenceDiagram
    actor User
    participant BadgeMessageProvider
    participant AuthPinDialog
    participant ToastUtils
    participant Badge

    User->>BadgeMessageProvider: initiateTransfer(context)
    loop until isAuthenticated
        BadgeMessageProvider->>AuthPinDialog: showPinAuthDialog(context)
        AuthPinDialog-->>BadgeMessageProvider: enteredPin or null
        alt User cancels
            BadgeMessageProvider->>ToastUtils: showToast("Transfer canceled by user")
            BadgeMessageProvider-->>User: transferAborted
            Note over BadgeMessageProvider,User: loop breaks
        else PIN entered
            BadgeMessageProvider->>Badge: transferData(DataTransferManager(pinData), context)
            BadgeMessageProvider->>ToastUtils: showToast("Code verified! Transferring data...")
            BadgeMessageProvider-->>User: transferContinues
            Note over BadgeMessageProvider,User: loop breaks
        end
    end
    Note over BadgeMessageProvider,Badge: After PIN message, normal data transfer logic runs as before
Loading

File-Level Changes

Change Details Files
Require a 4-digit PIN entry before starting a badge data transfer and send the PIN to the badge as a fixed message.
  • Import the new PIN authentication dialog helper into the badge message provider.
  • Before constructing the main Data for transfer, loop until authentication succeeds by showing a PIN dialog and handling cancelation.
  • On cancel, abort the transfer and show a cancellation toast.
  • On successful PIN entry, encode the PIN digits as hex, wrap them into a Data/Message with fixed mode and default attributes, and transfer that data to the badge before the main payload.
  • Show a toast indicating that the code was verified and data transfer is proceeding.
lib/providers/badge_message_provider.dart
Introduce a reusable PIN authentication dialog widget to collect and validate a 4-digit numeric code from the user.
  • Create a dialog function that shows a modal AlertDialog with lock icon and explanatory text.
  • Implement a 4-digit numeric TextFormField with center alignment, visual emphasis, and digit-only input filtering.
  • Validate that the PIN is exactly 4 digits before allowing submission.
  • Provide Cancel and Verify & Send actions, returning the entered PIN string or null via Navigator.pop.
lib/view/widgets/auth_pin_dialog.dart

Assessment against linked issues

Issue Objective Addressed Explanation
#1780 Before sending the first bitmap ("wang") transfer over BLE, show a prompt asking the user to enter the 4-digit code displayed on the badge.
#1780 Send a single BLE Write Request to characteristic 0xFEE1 (service 0xFEE0) containing exactly 16 bytes (first 4 bytes = ASCII digits of the entered code, bytes 4–15 = zero padding), and on write success proceed with normal transfer; on write failure show an error message. The PR turns the entered PIN into a list of hex string values and wraps it in a Data/Message object, then calls transferData, which is the normal bitmap transfer path. It does not perform a direct BLE write to characteristic 0xFEE1 with a 16-byte buffer, does not zero-pad bytes 4–15, and does not handle success/failure of that specific write to gate the subsequent transfer.
#1780 Ensure authentication is requested only once per BLE connection session, resetting on disconnect as per firmware behavior. The PR shows the PIN dialog immediately before starting a transfer but has no logic tied to the BLE connection lifecycle. There is no tracking of whether the current connection has already been authenticated, nor any reset-on-disconnect behavior, so the once-per-session requirement is not implemented.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions

github-actions Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Build Status

Build successful. APKs to test: https://github.com/fossasia/badgemagic-app/actions/runs/28375755034/artifacts/7953566808.

Screenshots

Android Screenshots
iPhone Screenshots
iPad Screenshots

@ctrlVnt ctrlVnt changed the title fix: insert pin before to connect to specific badge feat: insert pin before to connect to specific badge Jun 25, 2026
@ctrlVnt

ctrlVnt commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1780 - Fully compliant

Compliant requirements:

  • Show a prompt: "Enter the 4-digit code shown on the badge"
  • User reads the code off the badge display and types it in
  • App sends one Write Request to characteristic 0xFEE1 (service 0xFEE0) where Bytes 0–3: ASCII digits of the code e.g. "4364" → 0x34 0x33 0x36 0x34 and Bytes 4–15: zero-padded to exactly 16 bytes
  • If write succeeds → proceed with normal "wang" transfer, the current working
  • If write fails → show error message

1732 - Not compliant

Non-compliant requirements:

  • Add custom popup
  • Non dismissible if we click out of the border
  • Cancel method to stop scan and abort transfer
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Possible Issue

The RawDataTransferManager class does not handle the case where the PIN is not 4 digits long.

  List<List<int>> textChunks = await converter.convert(textData);

  List<String> pinHex = pin.codeUnits
      .map((char) => char.toRadixString(16).padLeft(2, '0'))
      .toList();

  while (pinHex.length < 16) {
    pinHex.add("00");
  }
  List<int> parsedPinBytes =
      pinHex.map((h) => int.parse(h, radix: 16)).toList();
  return [parsedPinBytes, ...textChunks];
}
Possible Issue

The transferData function does not handle the case where the context is null.

Future<bool> transferData(
  DataTransferManager manager, {
  BuildContext? context,
}) async {
  final scanProvider = context != null
      ? Provider.of<BadgeScanProvider>(context, listen: false)
      : null;

  final BleState initialState = ScanState(
    manager: manager,
    mode: scanProvider?.mode ?? BadgeScanMode.any,
    allowedNames: scanProvider?.getSelectedBadgeNames() ?? <String>[],
  );

  BleState? state = initialState;
  DateTime now = DateTime.now();
  dynamic lastState;

  while (state != null) {
    lastState = state;
    state = await state.process();
  }

  logger.d("Time to transfer data: ${DateTime.now().difference(now)}");
  logger.d(".......Data transfer completed.......");

  if (lastState != null) {
    try {
      if (lastState.isSuccess == false) {
        return false;
      }
    } catch (_) {}
  }

  return true;
}

@ctrlVnt ctrlVnt marked this pull request as ready for review June 30, 2026 11:01

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sorry @ctrlVnt, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: send 4-digit auth code before BLE bitmap transfer (security-feature)

1 participant