smartcard 3.7.1 → 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,111 +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) {
248
- // Timeout - check for state divergence on Windows (Issue #111)
249
- // Windows PC/SC may not always set SCARD_STATE_CHANGED correctly
281
+ if (result == static_cast<LONG>(SCARD_E_TIMEOUT)) {
282
+ // Timeout - query fresh state to detect missed events (Issue #111)
283
+ // On Windows, dwEventState after timeout may just mirror dwCurrentState
284
+ // rather than reflecting actual hardware state. We must explicitly
285
+ // query with SCARD_STATE_UNAWARE to get the real current state.
250
286
  std::lock_guard<std::mutex> lock(mutex_);
251
-
252
- // Guard against underflow if states only has PnP entry
253
- if (states.size() <= 1) {
254
- continue;
255
- }
256
-
257
- for (size_t i = 0; i < states.size() - 1; i++) { // Skip PnP entry
258
- const std::string& name = readerNames[i];
259
- auto it = readerStates_.find(name);
260
- if (it != readerStates_.end()) {
261
- DWORD currentState = states[i].dwEventState & ~SCARD_STATE_CHANGED;
262
- DWORD storedState = it->second.lastState;
263
-
264
- bool wasPresent = (storedState & SCARD_STATE_PRESENT) != 0;
265
- bool isPresent = (currentState & SCARD_STATE_PRESENT) != 0;
266
-
267
- // If the PRESENT flag differs, we missed an event
268
- if (wasPresent != isPresent) {
269
- std::vector<uint8_t> atr;
270
- if (states[i].cbAtr > 0) {
271
- atr.assign(states[i].rgbAtr, states[i].rgbAtr + states[i].cbAtr);
272
- }
273
-
274
- it->second.lastState = currentState;
275
- it->second.atr = atr;
276
-
277
- if (isPresent) {
278
- EmitEvent("card-inserted", name, currentState, atr);
279
- } else {
280
- EmitEvent("card-removed", name, currentState, {});
281
- }
282
- }
283
- }
284
- }
287
+ RefreshAllReaderStates();
285
288
  continue;
286
289
  }
287
290
 
288
291
  if (result != SCARD_S_SUCCESS) {
289
- // Error - emit and continue
290
- 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
+
291
334
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
292
335
  continue;
293
336
  }
294
337
 
295
338
  // Process changes - use reader name for lookup (Issue #111 fix)
296
339
  std::lock_guard<std::mutex> lock(mutex_);
297
- bool pnpTriggered = false;
298
340
 
299
341
  for (size_t i = 0; i < states.size(); i++) {
300
342
  if (!(states[i].dwEventState & SCARD_STATE_CHANGED)) {
301
343
  continue;
302
344
  }
303
345
 
304
- // 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.
305
350
  if (readerNames[i] == "\\\\?PnP?\\Notification") {
306
- pnpTriggered = true;
307
- // Get old reader names
308
- std::vector<std::string> oldNames;
309
- for (const auto& pair : readerStates_) {
310
- oldNames.push_back(pair.first);
311
- }
312
-
313
- // Update reader list (this rebuilds readerStates_ map)
314
- UpdateReaderList();
315
-
316
- // Find new readers
317
- for (const auto& pair : readerStates_) {
318
- bool found = false;
319
- for (const auto& old : oldNames) {
320
- if (old == pair.first) {
321
- found = true;
322
- break;
323
- }
324
- }
325
- if (!found) {
326
- EmitEvent("reader-attached", pair.first, pair.second.lastState, pair.second.atr);
327
- }
328
- }
329
-
330
- // Find removed readers
331
- for (const auto& old : oldNames) {
332
- if (readerStates_.find(old) == readerStates_.end()) {
333
- EmitEvent("reader-detached", old, 0, {});
334
- }
335
- }
336
- continue;
337
- }
338
-
339
- // Skip reader state processing if PnP was triggered in this iteration
340
- // The reader list has changed, so indices are no longer valid
341
- // We'll pick up any card changes on the next iteration with fresh state
342
- if (pnpTriggered) {
343
- continue;
351
+ ResyncReaderList();
352
+ break;
344
353
  }
345
354
 
346
355
  // Reader state change - look up by name, not index (Issue #111 fix)
@@ -348,29 +357,83 @@ void ReaderMonitor::MonitorLoop() {
348
357
  auto it = readerStates_.find(readerName);
349
358
 
350
359
  if (it != readerStates_.end()) {
351
- DWORD oldState = it->second.lastState;
352
- DWORD newState = states[i].dwEventState;
360
+ ApplyCardStateChange(it->second, readerName, states[i]);
361
+ }
362
+ }
363
+ }
364
+ }
353
365
 
354
- bool wasPresent = (oldState & SCARD_STATE_PRESENT) != 0;
355
- 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
+ }
356
373
 
357
- // Get ATR
358
- std::vector<uint8_t> atr;
359
- if (states[i].cbAtr > 0) {
360
- atr.assign(states[i].rgbAtr, states[i].rgbAtr + states[i].cbAtr);
361
- }
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
+ }
362
388
 
363
- // Update stored state using the map
364
- it->second.lastState = newState & ~SCARD_STATE_CHANGED;
365
- it->second.atr = atr;
389
+ if (SCardGetStatusChange(context_, 0, states.data(), states.size()) != SCARD_S_SUCCESS) {
390
+ return;
391
+ }
366
392
 
367
- // Emit appropriate event
368
- if (!wasPresent && isPresent) {
369
- EmitEvent("card-inserted", readerName, newState, atr);
370
- } else if (wasPresent && !isPresent) {
371
- EmitEvent("card-removed", readerName, newState, {});
372
- }
373
- }
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, {});
374
437
  }
375
438
  }
376
439
  }
@@ -380,7 +443,7 @@ void ReaderMonitor::UpdateReaderList() {
380
443
  DWORD readersLen = 0;
381
444
  LONG result = SCardListReaders(context_, nullptr, nullptr, &readersLen);
382
445
 
383
- if (result == SCARD_E_NO_READERS_AVAILABLE || readersLen == 0) {
446
+ if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE) || readersLen == 0) {
384
447
  readerStates_.clear();
385
448
  return;
386
449
  }
@@ -412,25 +475,42 @@ void ReaderMonitor::UpdateReaderList() {
412
475
  states[i].dwCurrentState = SCARD_STATE_UNAWARE;
413
476
  }
414
477
 
415
- SCardGetStatusChange(context_, 0, states.data(), states.size());
478
+ LONG statusResult = SCardGetStatusChange(context_, 0, states.data(), states.size());
479
+ bool seeded = (statusResult == SCARD_S_SUCCESS);
416
480
 
417
481
  // Update reader states map (Issue #111 fix: use map keyed by name)
418
- readerStates_.clear();
482
+ std::unordered_map<std::string, ReaderInfo> newStates;
419
483
  for (size_t i = 0; i < newNames.size(); i++) {
420
484
  ReaderInfo info;
421
- info.lastState = states[i].dwEventState & ~SCARD_STATE_CHANGED;
422
- if (states[i].cbAtr > 0) {
423
- 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
+ }
424
503
  }
425
- readerStates_[newNames[i]] = info;
504
+ newStates[newNames[i]] = info;
426
505
  }
506
+ readerStates_ = std::move(newStates);
427
507
  }
428
508
 
429
509
  void ReaderMonitor::EmitEvent(const std::string& eventType, const std::string& readerName,
430
- DWORD state, const std::vector<uint8_t>& atr) {
510
+ DWORD state, const std::vector<uint8_t>& atr, DWORD code) {
431
511
  // Use shared_ptr to ensure memory is freed even if ThreadSafeFunction is released
432
512
  // before the callback executes (prevents memory leak)
433
- auto data = std::make_shared<EventData>(EventData{eventType, readerName, state, atr});
513
+ auto data = std::make_shared<EventData>(EventData{eventType, readerName, state, atr, code});
434
514
 
435
515
  // Call JavaScript callback on main thread
436
516
  // Capture shared_ptr by value to extend lifetime until callback executes
@@ -447,6 +527,10 @@ void ReaderMonitor::EmitEvent(const std::string& eventType, const std::string& r
447
527
  event.Set("atr", env.Null());
448
528
  }
449
529
 
530
+ if (ptr->code != 0) {
531
+ event.Set("code", Napi::Number::New(env, ptr->code));
532
+ }
533
+
450
534
  // Call the callback
451
535
  callback.Call({event});
452
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