Skip to content

Windows: card-inserted/card-removed events fire inconsistently #111

@siriwatknp

Description

@siriwatknp

Environment

  • OS: Windows 11
  • Node.js: 22.x (via Electron 35)
  • smartcard version: 3.7.0

Problem

On Windows, card-inserted and card-removed events fire inconsistently. The same code works reliably on macOS.

Observed behavior:

  • reader-attached fires reliably
  • card-inserted fires sometimes but not always when inserting a card
  • card-removed rarely fires when removing a card
  • If card is already in reader when reader-attached fires, hasCard: true is detected and card-inserted fires (this works)

Reproduction

const { Devices } = require('smartcard');

const devices = new Devices();

devices.on('reader-attached', (reader) => {
  console.log('reader-attached', reader.name, 'hasCard:', (reader.state & 0x20) !== 0);
});

devices.on('card-inserted', ({ reader }) => {
  console.log('card-inserted', reader.name);
});

devices.on('card-removed', ({ reader }) => {
  console.log('card-removed', reader.name);
});

devices.start();

Steps:

  1. Run script on Windows 11
  2. Plug in USB card reader → reader-attached fires ✓
  3. Insert card → card-inserted sometimes fires, sometimes doesn't
  4. Remove card → card-removed rarely fires

Suspected cause

Looking at reader_monitor.cpp, the issue appears to be in how SCardGetStatusChange() state tracking works on Windows:

// State stored without SCARD_STATE_CHANGED flag
readers_[i].lastState = newState & ~SCARD_STATE_CHANGED;

// Next iteration uses this as dwCurrentState
state.dwCurrentState = reader.lastState;

If lastState gets out of sync with actual reader state (timing issue specific to Windows PC/SC), subsequent state changes aren't detected.

Workaround

Periodically stopping and restarting the monitor resets state tracking and improves reliability:

setInterval(() => {
  devices.stop();
  devices = new Devices();
  // re-attach event listeners...
  devices.start();
}, 5000);

This suggests the native state tracking diverges from actual hardware state over time on Windows.

Additional context

  • Windows Smart Card service is running
  • Tested with ACR38U reader
  • Thai National ID card (contact-based, T=0 protocol)

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions