smartcard 3.7.2 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,25 @@
1
1
  #include "reader_monitor.h"
2
2
  #include "pcsc_errors.h"
3
+ #include "pcsc_napi_error.h"
4
+ #include <cstdio>
3
5
  #include <cstring>
4
6
  #include <unordered_map>
5
7
  #include <memory>
8
+ #include "reader_state_utils.h"
9
+
10
+ using smartcard::CardEvent;
11
+ using smartcard::DetectCardStateChange;
6
12
 
7
13
  Napi::FunctionReference ReaderMonitor::constructor;
8
14
 
15
+ // Format a PC/SC error as "message (0xXXXXXXXX)" so the numeric code
16
+ // survives to JS even when only the message string is consumed.
17
+ static std::string FormatPCSCError(LONG code) {
18
+ char hex[16];
19
+ std::snprintf(hex, sizeof(hex), " (0x%08X)", static_cast<unsigned int>(static_cast<DWORD>(code)));
20
+ return std::string(GetPCSCErrorString(code)) + hex;
21
+ }
22
+
9
23
  // Number of iterations between forced full state refreshes (Windows reliability fix)
10
24
  static const int STATE_REFRESH_INTERVAL = 10;
11
25
 
@@ -15,6 +29,7 @@ struct EventData {
15
29
  std::string readerName;
16
30
  DWORD state;
17
31
  std::vector<uint8_t> atr;
32
+ DWORD code;
18
33
  };
19
34
 
20
35
  Napi::Object ReaderMonitor::Init(Napi::Env env, Napi::Object exports) {
@@ -35,21 +50,33 @@ ReaderMonitor::ReaderMonitor(const Napi::CallbackInfo& info)
35
50
  : Napi::ObjectWrap<ReaderMonitor>(info),
36
51
  context_(0),
37
52
  contextValid_(false),
38
- running_(false) {
53
+ running_(false),
54
+ tsfnActive_(false) {
39
55
  }
40
56
 
41
57
  ReaderMonitor::~ReaderMonitor() {
42
58
  // Ensure monitoring is stopped
43
59
  if (running_) {
44
60
  running_ = false;
45
- if (contextValid_) {
46
- SCardCancel(context_);
61
+ {
62
+ std::lock_guard<std::mutex> lock(mutex_);
63
+ if (contextValid_) {
64
+ SCardCancel(context_);
65
+ }
47
66
  }
48
67
  if (monitorThread_.joinable()) {
49
68
  monitorThread_.join();
50
69
  }
51
70
  }
52
71
 
72
+ // A monitor destroyed without stop() would otherwise leak the tsfn,
73
+ // keeping the event loop referenced and letting its finalizer run
74
+ // after this object is gone
75
+ if (tsfnActive_) {
76
+ tsfn_.Release();
77
+ tsfnActive_ = false;
78
+ }
79
+
53
80
  if (contextValid_) {
54
81
  SCardReleaseContext(context_);
55
82
  }
@@ -74,11 +101,18 @@ Napi::Value ReaderMonitor::Start(const Napi::CallbackInfo& info) {
74
101
  // Establish PC/SC context
75
102
  LONG result = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context_);
76
103
  if (result != SCARD_S_SUCCESS) {
77
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
104
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
78
105
  return env.Undefined();
79
106
  }
80
107
  contextValid_ = true;
81
108
 
109
+ // Per-session liveness flag. The tsfn finalizer runs asynchronously on a
110
+ // later event-loop tick, so after a same-tick stop()/start() a stale
111
+ // finalizer from the previous session must only be able to kill its own
112
+ // session - clearing running_ directly here would silently stop the new
113
+ // monitor thread and leave its std::thread joinable but never joined.
114
+ auto sessionActive = std::make_shared<std::atomic<bool>>(true);
115
+
82
116
  // Create thread-safe function
83
117
  tsfn_ = Napi::ThreadSafeFunction::New(
84
118
  env,
@@ -86,15 +120,16 @@ Napi::Value ReaderMonitor::Start(const Napi::CallbackInfo& info) {
86
120
  "ReaderMonitor",
87
121
  0, // Unlimited queue size
88
122
  1, // 1 initial thread
89
- [this](Napi::Env) {
90
- // Invoke destructor callback - called when tsfn is released
91
- running_ = false;
123
+ [sessionActive](Napi::Env) {
124
+ // Called when the tsfn is released (stop() or env teardown)
125
+ sessionActive->store(false);
92
126
  }
93
127
  );
128
+ tsfnActive_ = true;
94
129
 
95
130
  // Start monitoring
96
131
  running_ = true;
97
- monitorThread_ = std::thread(&ReaderMonitor::MonitorLoop, this);
132
+ monitorThread_ = std::thread(&ReaderMonitor::MonitorLoop, this, sessionActive);
98
133
 
99
134
  return env.Undefined();
100
135
  }
@@ -108,9 +143,14 @@ Napi::Value ReaderMonitor::Stop(const Napi::CallbackInfo& info) {
108
143
 
109
144
  running_ = false;
110
145
 
111
- // Cancel any blocking SCardGetStatusChange call
112
- if (contextValid_) {
113
- SCardCancel(context_);
146
+ // Cancel any blocking SCardGetStatusChange call. mutex_ guards
147
+ // context_/contextValid_ against the recovery path swapping them
148
+ // on the monitor thread.
149
+ {
150
+ std::lock_guard<std::mutex> lock(mutex_);
151
+ if (contextValid_) {
152
+ SCardCancel(context_);
153
+ }
114
154
  }
115
155
 
116
156
  // Wait for thread to finish
@@ -120,6 +160,7 @@ Napi::Value ReaderMonitor::Stop(const Napi::CallbackInfo& info) {
120
160
 
121
161
  // Release thread-safe function
122
162
  tsfn_.Release();
163
+ tsfnActive_ = false;
123
164
 
124
165
  // Release context
125
166
  if (contextValid_) {
@@ -137,7 +178,40 @@ Napi::Value ReaderMonitor::GetIsRunning(const Napi::CallbackInfo& info) {
137
178
  return Napi::Boolean::New(info.Env(), running_.load());
138
179
  }
139
180
 
140
- void ReaderMonitor::MonitorLoop() {
181
+ // Single commit point for card state transitions: all three detection paths
182
+ // (main wait, timeout re-query, periodic refresh) must apply identical
183
+ // masking, ATR, and event rules or their stored states drift apart.
184
+ void ReaderMonitor::ApplyCardStateChange(ReaderInfo& info, const std::string& readerName,
185
+ const SCARD_READERSTATE& readerState) {
186
+ DWORD newState = readerState.dwEventState & ~SCARD_STATE_CHANGED;
187
+ CardEvent event = DetectCardStateChange(info.lastState, newState, SCARD_STATE_PRESENT);
188
+
189
+ // Commit so a stale lastState can't make the next SCardGetStatusChange
190
+ // re-report the same change - but never store SCARD_STATE_IGNORE (fed
191
+ // back as dwCurrentState it excludes the reader from future waits), and
192
+ // don't absorb an unknown/empty no-event result: the PnP path handles
193
+ // vanished readers.
194
+ bool unusable = readerState.dwEventState == 0 ||
195
+ (newState & SCARD_STATE_UNKNOWN) != 0;
196
+ if (event != CardEvent::None || !unusable) {
197
+ info.lastState = newState & ~SCARD_STATE_IGNORE;
198
+ }
199
+
200
+ if (event == CardEvent::Inserted) {
201
+ // cbAtr comes from the PC/SC service; clamp to the actual buffer size
202
+ DWORD atrLen = readerState.cbAtr;
203
+ if (atrLen > sizeof(readerState.rgbAtr)) {
204
+ atrLen = sizeof(readerState.rgbAtr);
205
+ }
206
+ info.atr.assign(readerState.rgbAtr, readerState.rgbAtr + atrLen);
207
+ EmitEvent("card-inserted", readerName, newState, info.atr);
208
+ } else if (event == CardEvent::Removed) {
209
+ info.atr.clear();
210
+ EmitEvent("card-removed", readerName, newState, {});
211
+ }
212
+ }
213
+
214
+ void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive) {
141
215
  // Get initial reader list
142
216
  UpdateReaderList();
143
217
 
@@ -154,60 +228,13 @@ void ReaderMonitor::MonitorLoop() {
154
228
  std::vector<std::string> readerNames;
155
229
  int iterationCount = 0;
156
230
 
157
- while (running_) {
231
+ while (running_ && sessionActive->load()) {
158
232
  // Periodic full state refresh to handle Windows PC/SC state drift (Issue #111)
159
233
  // This ensures we don't miss events if the state tracking gets out of sync
160
234
  if (++iterationCount >= STATE_REFRESH_INTERVAL) {
161
235
  iterationCount = 0;
162
236
  std::lock_guard<std::mutex> lock(mutex_);
163
-
164
- // Get fresh state for all readers
165
- std::vector<SCARD_READERSTATE> refreshStates;
166
- std::vector<std::string> refreshNames;
167
-
168
- for (const auto& pair : readerStates_) {
169
- refreshNames.push_back(pair.first);
170
- SCARD_READERSTATE state = {};
171
- state.szReader = refreshNames.back().c_str();
172
- state.dwCurrentState = SCARD_STATE_UNAWARE; // Force fresh state
173
- refreshStates.push_back(state);
174
- }
175
-
176
- if (!refreshStates.empty()) {
177
- LONG refreshResult = SCardGetStatusChange(context_, 0, refreshStates.data(), refreshStates.size());
178
- if (refreshResult == SCARD_S_SUCCESS) {
179
- // Check for state divergence and emit missed events
180
- for (size_t i = 0; i < refreshStates.size(); i++) {
181
- const std::string& name = refreshNames[i];
182
- auto it = readerStates_.find(name);
183
- if (it != readerStates_.end()) {
184
- DWORD oldState = it->second.lastState;
185
- DWORD newState = refreshStates[i].dwEventState & ~SCARD_STATE_CHANGED;
186
-
187
- bool wasPresent = (oldState & SCARD_STATE_PRESENT) != 0;
188
- bool isPresent = (newState & SCARD_STATE_PRESENT) != 0;
189
-
190
- if (wasPresent != isPresent) {
191
- // State diverged - emit missed event
192
- std::vector<uint8_t> atr;
193
- if (refreshStates[i].cbAtr > 0) {
194
- atr.assign(refreshStates[i].rgbAtr,
195
- refreshStates[i].rgbAtr + refreshStates[i].cbAtr);
196
- }
197
-
198
- it->second.lastState = newState;
199
- it->second.atr = atr;
200
-
201
- if (isPresent) {
202
- EmitEvent("card-inserted", name, newState, atr);
203
- } else {
204
- EmitEvent("card-removed", name, newState, {});
205
- }
206
- }
207
- }
208
- }
209
- }
210
- }
237
+ RefreshAllReaderStates();
211
238
  }
212
239
 
213
240
  // Build states array using reader names from our map
@@ -216,6 +243,13 @@ void ReaderMonitor::MonitorLoop() {
216
243
  states.clear();
217
244
  readerNames.clear();
218
245
 
246
+ // Reserve for all tracked readers + the PnP entry so no
247
+ // push_back reallocates after szReader pointers are taken
248
+ // (SSO strings move with the vector - see the refresh block
249
+ // above). With a single reader the PnP push_back below is
250
+ // otherwise guaranteed to reallocate on the first iteration.
251
+ readerNames.reserve(readerStates_.size() + 1);
252
+
219
253
  // Add known readers - use the map for name-based lookup
220
254
  for (const auto& pair : readerStates_) {
221
255
  SCARD_READERSTATE state = {};
@@ -236,129 +270,86 @@ void ReaderMonitor::MonitorLoop() {
236
270
  // Wait for changes (with 1 second timeout for periodic refresh)
237
271
  LONG result = SCardGetStatusChange(context_, 1000, states.data(), states.size());
238
272
 
239
- if (!running_) {
273
+ if (!running_ || !sessionActive->load()) {
240
274
  break;
241
275
  }
242
276
 
243
- if (result == SCARD_E_CANCELLED) {
277
+ if (result == static_cast<LONG>(SCARD_E_CANCELLED)) {
244
278
  break;
245
279
  }
246
280
 
247
- if (result == SCARD_E_TIMEOUT) {
281
+ if (result == static_cast<LONG>(SCARD_E_TIMEOUT)) {
248
282
  // Timeout - query fresh state to detect missed events (Issue #111)
249
283
  // On Windows, dwEventState after timeout may just mirror dwCurrentState
250
284
  // rather than reflecting actual hardware state. We must explicitly
251
285
  // query with SCARD_STATE_UNAWARE to get the real current state.
252
286
  std::lock_guard<std::mutex> lock(mutex_);
253
-
254
- if (readerStates_.empty()) {
255
- continue;
256
- }
257
-
258
- // Build fresh state query for all readers
259
- std::vector<SCARD_READERSTATE> freshStates;
260
- std::vector<std::string> freshNames;
261
-
262
- for (const auto& pair : readerStates_) {
263
- freshNames.push_back(pair.first);
264
- SCARD_READERSTATE state = {};
265
- state.szReader = freshNames.back().c_str();
266
- state.dwCurrentState = SCARD_STATE_UNAWARE;
267
- freshStates.push_back(state);
268
- }
269
-
270
- LONG freshResult = SCardGetStatusChange(context_, 0, freshStates.data(), freshStates.size());
271
- if (freshResult != SCARD_S_SUCCESS) {
272
- continue;
273
- }
274
-
275
- for (size_t i = 0; i < freshStates.size(); i++) {
276
- const std::string& name = freshNames[i];
277
- auto it = readerStates_.find(name);
278
- if (it != readerStates_.end()) {
279
- DWORD freshState = freshStates[i].dwEventState & ~SCARD_STATE_CHANGED;
280
- DWORD storedState = it->second.lastState;
281
-
282
- bool wasPresent = (storedState & SCARD_STATE_PRESENT) != 0;
283
- bool isPresent = (freshState & SCARD_STATE_PRESENT) != 0;
284
-
285
- if (wasPresent != isPresent) {
286
- std::vector<uint8_t> atr;
287
- if (freshStates[i].cbAtr > 0) {
288
- atr.assign(freshStates[i].rgbAtr,
289
- freshStates[i].rgbAtr + freshStates[i].cbAtr);
290
- }
291
-
292
- it->second.lastState = freshState;
293
- it->second.atr = atr;
294
-
295
- if (isPresent) {
296
- EmitEvent("card-inserted", name, freshState, atr);
297
- } else {
298
- EmitEvent("card-removed", name, freshState, {});
299
- }
300
- }
301
- }
302
- }
287
+ RefreshAllReaderStates();
303
288
  continue;
304
289
  }
305
290
 
306
291
  if (result != SCARD_S_SUCCESS) {
307
- // Error - emit and continue
308
- EmitEvent("error", GetPCSCErrorString(result), 0, {});
292
+ // Error - emit and continue. The numeric code rides in the
293
+ // event's code field (and the message, for message-only
294
+ // consumers); state stays 0 so it keeps its bitmask meaning.
295
+ EmitEvent("error", FormatPCSCError(result), 0, {}, static_cast<DWORD>(result));
296
+
297
+ // Context-fatal errors (Smart Card service restart, dead handle):
298
+ // the existing context will never recover, so retrying it forever
299
+ // is pointless (Issue #119). Release it and re-establish before
300
+ // the next iteration. If re-establish fails, the next
301
+ // SCardGetStatusChange on the zeroed handle fails fast and we
302
+ // land back here - still one attempt per second.
303
+ // SCARD_E_INVALID_PARAMETER is deliberately not in this list: it
304
+ // is a per-call argument error, and recycling a healthy context
305
+ // would re-seed lastState and latch away pending transitions.
306
+ DWORD ucode = static_cast<DWORD>(result);
307
+ if (ucode == SCARD_E_SERVICE_STOPPED ||
308
+ ucode == SCARD_E_NO_SERVICE ||
309
+ ucode == SCARD_E_INVALID_HANDLE) {
310
+ // mutex_ also guards context_/contextValid_ against Stop()
311
+ // and the destructor reading them for SCardCancel.
312
+ std::lock_guard<std::mutex> lock(mutex_);
313
+ if (contextValid_) {
314
+ SCardReleaseContext(context_);
315
+ contextValid_ = false;
316
+ }
317
+ context_ = 0;
318
+
319
+ LONG establishResult = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context_);
320
+ if (establishResult == SCARD_S_SUCCESS) {
321
+ contextValid_ = true;
322
+ // Reader states were tracked against the dead context:
323
+ // rebuild, emit whatever changed during the outage, and
324
+ // tell the JS layer to refresh its own context.
325
+ ResyncReaderList();
326
+ EmitEvent("monitor-recovered", "", 0, {});
327
+ } else {
328
+ // The error event above already fired this cycle - stay
329
+ // at one error event per second while the service is down.
330
+ context_ = 0;
331
+ }
332
+ }
333
+
309
334
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
310
335
  continue;
311
336
  }
312
337
 
313
338
  // Process changes - use reader name for lookup (Issue #111 fix)
314
339
  std::lock_guard<std::mutex> lock(mutex_);
315
- bool pnpTriggered = false;
316
340
 
317
341
  for (size_t i = 0; i < states.size(); i++) {
318
342
  if (!(states[i].dwEventState & SCARD_STATE_CHANGED)) {
319
343
  continue;
320
344
  }
321
345
 
322
- // PnP notification - reader list changed
346
+ // PnP notification - reader list changed. The PnP entry is
347
+ // always pushed last, and ResyncReaderList rebuilds the map, so
348
+ // stop here: any entry processed after it would apply stale
349
+ // states[] data against the rebuilt map.
323
350
  if (readerNames[i] == "\\\\?PnP?\\Notification") {
324
- pnpTriggered = true;
325
- // Get old reader names
326
- std::vector<std::string> oldNames;
327
- for (const auto& pair : readerStates_) {
328
- oldNames.push_back(pair.first);
329
- }
330
-
331
- // Update reader list (this rebuilds readerStates_ map)
332
- UpdateReaderList();
333
-
334
- // Find new readers
335
- for (const auto& pair : readerStates_) {
336
- bool found = false;
337
- for (const auto& old : oldNames) {
338
- if (old == pair.first) {
339
- found = true;
340
- break;
341
- }
342
- }
343
- if (!found) {
344
- EmitEvent("reader-attached", pair.first, pair.second.lastState, pair.second.atr);
345
- }
346
- }
347
-
348
- // Find removed readers
349
- for (const auto& old : oldNames) {
350
- if (readerStates_.find(old) == readerStates_.end()) {
351
- EmitEvent("reader-detached", old, 0, {});
352
- }
353
- }
354
- continue;
355
- }
356
-
357
- // Skip reader state processing if PnP was triggered in this iteration
358
- // The reader list has changed, so indices are no longer valid
359
- // We'll pick up any card changes on the next iteration with fresh state
360
- if (pnpTriggered) {
361
- continue;
351
+ ResyncReaderList();
352
+ break;
362
353
  }
363
354
 
364
355
  // Reader state change - look up by name, not index (Issue #111 fix)
@@ -366,29 +357,83 @@ void ReaderMonitor::MonitorLoop() {
366
357
  auto it = readerStates_.find(readerName);
367
358
 
368
359
  if (it != readerStates_.end()) {
369
- DWORD oldState = it->second.lastState;
370
- DWORD newState = states[i].dwEventState;
360
+ ApplyCardStateChange(it->second, readerName, states[i]);
361
+ }
362
+ }
363
+ }
364
+ }
371
365
 
372
- bool wasPresent = (oldState & SCARD_STATE_PRESENT) != 0;
373
- bool isPresent = (newState & SCARD_STATE_PRESENT) != 0;
366
+ // Re-query every tracked reader with SCARD_STATE_UNAWARE and commit/emit any
367
+ // missed transitions - the shared body of the periodic refresh and the
368
+ // timeout re-query (Issue #111). Caller holds mutex_.
369
+ void ReaderMonitor::RefreshAllReaderStates() {
370
+ if (readerStates_.empty()) {
371
+ return;
372
+ }
374
373
 
375
- // Get ATR
376
- std::vector<uint8_t> atr;
377
- if (states[i].cbAtr > 0) {
378
- atr.assign(states[i].rgbAtr, states[i].rgbAtr + states[i].cbAtr);
379
- }
374
+ // Reserve before taking c_str() pointers: a reallocating push_back moves
375
+ // SSO strings and dangles every previously captured szReader
376
+ std::vector<SCARD_READERSTATE> states;
377
+ std::vector<std::string> names;
378
+ names.reserve(readerStates_.size());
379
+ states.reserve(readerStates_.size());
380
+
381
+ for (const auto& pair : readerStates_) {
382
+ names.push_back(pair.first);
383
+ SCARD_READERSTATE state = {};
384
+ state.szReader = names.back().c_str();
385
+ state.dwCurrentState = SCARD_STATE_UNAWARE; // Force fresh state
386
+ states.push_back(state);
387
+ }
380
388
 
381
- // Update stored state using the map
382
- it->second.lastState = newState & ~SCARD_STATE_CHANGED;
383
- it->second.atr = atr;
389
+ if (SCardGetStatusChange(context_, 0, states.data(), states.size()) != SCARD_S_SUCCESS) {
390
+ return;
391
+ }
384
392
 
385
- // Emit appropriate event
386
- if (!wasPresent && isPresent) {
387
- EmitEvent("card-inserted", readerName, newState, atr);
388
- } else if (wasPresent && !isPresent) {
389
- EmitEvent("card-removed", readerName, newState, {});
390
- }
391
- }
393
+ for (size_t i = 0; i < states.size(); i++) {
394
+ auto it = readerStates_.find(names[i]);
395
+ if (it != readerStates_.end()) {
396
+ ApplyCardStateChange(it->second, names[i], states[i]);
397
+ }
398
+ }
399
+ }
400
+
401
+ // Rebuild readerStates_ and emit the difference: reader-attached/detached
402
+ // for membership changes, card-inserted/removed for presence changes on
403
+ // surviving readers. Needed because UpdateReaderList re-seeds lastState
404
+ // from a fresh SCARD_STATE_UNAWARE query, which would otherwise silently
405
+ // latch away any transition that happened since the last wait (PnP churn,
406
+ // or a service outage the recovery path just healed). Caller holds mutex_.
407
+ void ReaderMonitor::ResyncReaderList() {
408
+ std::unordered_map<std::string, DWORD> oldStates;
409
+ for (const auto& pair : readerStates_) {
410
+ oldStates[pair.first] = pair.second.lastState;
411
+ }
412
+
413
+ UpdateReaderList();
414
+
415
+ for (const auto& pair : readerStates_) {
416
+ if (oldStates.find(pair.first) == oldStates.end()) {
417
+ EmitEvent("reader-attached", pair.first, pair.second.lastState, pair.second.atr);
418
+ }
419
+ }
420
+
421
+ for (const auto& pair : oldStates) {
422
+ if (readerStates_.find(pair.first) == readerStates_.end()) {
423
+ EmitEvent("reader-detached", pair.first, 0, {});
424
+ }
425
+ }
426
+
427
+ for (const auto& pair : readerStates_) {
428
+ auto oldIt = oldStates.find(pair.first);
429
+ if (oldIt == oldStates.end()) {
430
+ continue; // New reader - reader-attached already emitted
431
+ }
432
+ CardEvent event = DetectCardStateChange(oldIt->second, pair.second.lastState, SCARD_STATE_PRESENT);
433
+ if (event == CardEvent::Inserted) {
434
+ EmitEvent("card-inserted", pair.first, pair.second.lastState, pair.second.atr);
435
+ } else if (event == CardEvent::Removed) {
436
+ EmitEvent("card-removed", pair.first, pair.second.lastState, {});
392
437
  }
393
438
  }
394
439
  }
@@ -398,7 +443,7 @@ void ReaderMonitor::UpdateReaderList() {
398
443
  DWORD readersLen = 0;
399
444
  LONG result = SCardListReaders(context_, nullptr, nullptr, &readersLen);
400
445
 
401
- if (result == SCARD_E_NO_READERS_AVAILABLE || readersLen == 0) {
446
+ if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE) || readersLen == 0) {
402
447
  readerStates_.clear();
403
448
  return;
404
449
  }
@@ -430,25 +475,42 @@ void ReaderMonitor::UpdateReaderList() {
430
475
  states[i].dwCurrentState = SCARD_STATE_UNAWARE;
431
476
  }
432
477
 
433
- SCardGetStatusChange(context_, 0, states.data(), states.size());
478
+ LONG statusResult = SCardGetStatusChange(context_, 0, states.data(), states.size());
479
+ bool seeded = (statusResult == SCARD_S_SUCCESS);
434
480
 
435
481
  // Update reader states map (Issue #111 fix: use map keyed by name)
436
- readerStates_.clear();
482
+ std::unordered_map<std::string, ReaderInfo> newStates;
437
483
  for (size_t i = 0; i < newNames.size(); i++) {
438
484
  ReaderInfo info;
439
- info.lastState = states[i].dwEventState & ~SCARD_STATE_CHANGED;
440
- if (states[i].cbAtr > 0) {
441
- info.atr.assign(states[i].rgbAtr, states[i].rgbAtr + states[i].cbAtr);
485
+ info.lastState = SCARD_STATE_UNAWARE;
486
+ if (seeded) {
487
+ info.lastState = states[i].dwEventState & ~SCARD_STATE_CHANGED;
488
+ DWORD atrLen = states[i].cbAtr;
489
+ if (atrLen > sizeof(states[i].rgbAtr)) {
490
+ atrLen = sizeof(states[i].rgbAtr);
491
+ }
492
+ if (atrLen > 0) {
493
+ info.atr.assign(states[i].rgbAtr, states[i].rgbAtr + atrLen);
494
+ }
495
+ } else {
496
+ // Seed query failed: keep what we already knew about this reader
497
+ // instead of zeroing it - a zeroed lastState reads as a card
498
+ // removal to ResyncReaderList and as UNAWARE to the main wait.
499
+ auto existing = readerStates_.find(newNames[i]);
500
+ if (existing != readerStates_.end()) {
501
+ info = existing->second;
502
+ }
442
503
  }
443
- readerStates_[newNames[i]] = info;
504
+ newStates[newNames[i]] = info;
444
505
  }
506
+ readerStates_ = std::move(newStates);
445
507
  }
446
508
 
447
509
  void ReaderMonitor::EmitEvent(const std::string& eventType, const std::string& readerName,
448
- DWORD state, const std::vector<uint8_t>& atr) {
510
+ DWORD state, const std::vector<uint8_t>& atr, DWORD code) {
449
511
  // Use shared_ptr to ensure memory is freed even if ThreadSafeFunction is released
450
512
  // before the callback executes (prevents memory leak)
451
- auto data = std::make_shared<EventData>(EventData{eventType, readerName, state, atr});
513
+ auto data = std::make_shared<EventData>(EventData{eventType, readerName, state, atr, code});
452
514
 
453
515
  // Call JavaScript callback on main thread
454
516
  // Capture shared_ptr by value to extend lifetime until callback executes
@@ -465,6 +527,10 @@ void ReaderMonitor::EmitEvent(const std::string& eventType, const std::string& r
465
527
  event.Set("atr", env.Null());
466
528
  }
467
529
 
530
+ if (ptr->code != 0) {
531
+ event.Set("code", Napi::Number::New(env, ptr->code));
532
+ }
533
+
468
534
  // Call the callback
469
535
  callback.Call({event});
470
536
  // shared_ptr automatically cleaned up when lambda is destroyed
@@ -3,6 +3,7 @@
3
3
  #include <napi.h>
4
4
  #include <thread>
5
5
  #include <atomic>
6
+ #include <memory>
6
7
  #include <vector>
7
8
  #include <string>
8
9
  #include <mutex>
@@ -37,12 +38,16 @@ private:
37
38
  std::atomic<bool> running_;
38
39
  std::mutex mutex_;
39
40
 
40
- // Thread-safe function for emitting events
41
+ // Thread-safe function for emitting events. tsfnActive_ tracks whether
42
+ // tsfn_ holds a live handle that still needs Release().
41
43
  Napi::ThreadSafeFunction tsfn_;
44
+ bool tsfnActive_;
42
45
 
43
46
  // Current known reader states (Issue #111: keyed by reader name for reliable lookup)
44
47
  struct ReaderInfo {
45
48
  DWORD lastState;
49
+ // Cached for reader-attached emissions; seeded by UpdateReaderList
50
+ // and kept coherent on transitions by ApplyCardStateChange
46
51
  std::vector<uint8_t> atr;
47
52
  };
48
53
  std::unordered_map<std::string, ReaderInfo> readerStates_;
@@ -53,8 +58,13 @@ private:
53
58
  Napi::Value GetIsRunning(const Napi::CallbackInfo& info);
54
59
 
55
60
  // Internal methods
56
- void MonitorLoop();
61
+ void MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive);
57
62
  void UpdateReaderList();
63
+ void ResyncReaderList();
64
+ void RefreshAllReaderStates();
65
+ // code: the PC/SC error code, for "error" events only
58
66
  void EmitEvent(const std::string& eventType, const std::string& readerName,
59
- DWORD state, const std::vector<uint8_t>& atr);
67
+ DWORD state, const std::vector<uint8_t>& atr, DWORD code = 0);
68
+ void ApplyCardStateChange(ReaderInfo& info, const std::string& readerName,
69
+ const SCARD_READERSTATE& readerState);
60
70
  };
@@ -0,0 +1,24 @@
1
+ // src/reader_state_utils.h
2
+ #pragma once
3
+ #include <cstdint>
4
+
5
+ namespace smartcard {
6
+
7
+ enum class CardEvent { None, Inserted, Removed };
8
+
9
+ // presentMask is the platform's SCARD_STATE_PRESENT bit, passed in by the
10
+ // caller. This header deliberately includes no PC/SC headers so the logic is
11
+ // testable in isolation - receiving the mask instead of mirroring its value
12
+ // means there is no hand-typed copy of the constant to drift out of sync
13
+ // (the bug class behind the original 0x10/0x20 inversion).
14
+ inline CardEvent DetectCardStateChange(uint64_t oldState, uint64_t newState,
15
+ uint64_t presentMask) {
16
+ bool wasPresent = (oldState & presentMask) != 0;
17
+ bool isPresent = (newState & presentMask) != 0;
18
+
19
+ if (!wasPresent && isPresent) return CardEvent::Inserted;
20
+ if (wasPresent && !isPresent) return CardEvent::Removed;
21
+ return CardEvent::None;
22
+ }
23
+
24
+ } // namespace smartcard