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,6 +1,7 @@
1
1
  #include "async_workers.h"
2
2
  #include "pcsc_card.h"
3
3
  #include "pcsc_errors.h"
4
+ #include "pcsc_napi_error.h"
4
5
  #include <cstring>
5
6
 
6
7
  // ============================================================================
@@ -9,12 +10,14 @@
9
10
 
10
11
  WaitForChangeWorker::WaitForChangeWorker(
11
12
  Napi::Env env,
13
+ Napi::Object owner,
12
14
  SCARDCONTEXT context,
13
15
  std::vector<std::string> readerNames,
14
16
  std::vector<DWORD> currentStates,
15
17
  DWORD timeout,
16
18
  Napi::Promise::Deferred deferred)
17
19
  : Napi::AsyncWorker(env),
20
+ ownerRef_(Napi::Persistent(owner)),
18
21
  context_(context),
19
22
  readerNames_(std::move(readerNames)),
20
23
  timeout_(timeout),
@@ -60,14 +63,14 @@ void WaitForChangeWorker::OnOK() {
60
63
  }
61
64
 
62
65
  deferred_.Resolve(changes);
63
- } else if (result_ == SCARD_E_CANCELLED) {
66
+ } else if (result_ == static_cast<LONG>(SCARD_E_CANCELLED)) {
64
67
  // Cancelled - resolve with null
65
68
  deferred_.Resolve(env.Null());
66
- } else if (result_ == SCARD_E_TIMEOUT) {
69
+ } else if (result_ == static_cast<LONG>(SCARD_E_TIMEOUT)) {
67
70
  // Timeout - resolve with empty array
68
71
  deferred_.Resolve(Napi::Array::New(env, 0));
69
72
  } else {
70
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
73
+ deferred_.Reject(NewPCSCError(env, result_).Value());
71
74
  }
72
75
  }
73
76
 
@@ -81,12 +84,14 @@ void WaitForChangeWorker::OnError(const Napi::Error& error) {
81
84
 
82
85
  TransmitWorker::TransmitWorker(
83
86
  Napi::Env env,
87
+ Napi::Object owner,
84
88
  SCARDHANDLE card,
85
89
  DWORD protocol,
86
90
  std::vector<uint8_t> sendBuffer,
87
91
  size_t maxRecvLength,
88
92
  Napi::Promise::Deferred deferred)
89
93
  : Napi::AsyncWorker(env),
94
+ ownerRef_(Napi::Persistent(owner)),
90
95
  card_(card),
91
96
  protocol_(protocol),
92
97
  sendBuffer_(std::move(sendBuffer)),
@@ -137,7 +142,7 @@ void TransmitWorker::OnOK() {
137
142
  env, recvBuffer_.data(), recvLength_);
138
143
  deferred_.Resolve(buffer);
139
144
  } else {
140
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
145
+ deferred_.Reject(NewPCSCError(env, result_).Value());
141
146
  }
142
147
  }
143
148
 
@@ -151,11 +156,13 @@ void TransmitWorker::OnError(const Napi::Error& error) {
151
156
 
152
157
  ControlWorker::ControlWorker(
153
158
  Napi::Env env,
159
+ Napi::Object owner,
154
160
  SCARDHANDLE card,
155
161
  DWORD controlCode,
156
162
  std::vector<uint8_t> sendBuffer,
157
163
  Napi::Promise::Deferred deferred)
158
164
  : Napi::AsyncWorker(env),
165
+ ownerRef_(Napi::Persistent(owner)),
159
166
  card_(card),
160
167
  controlCode_(controlCode),
161
168
  sendBuffer_(std::move(sendBuffer)),
@@ -186,7 +193,7 @@ void ControlWorker::OnOK() {
186
193
  env, recvBuffer_.data(), bytesReturned_);
187
194
  deferred_.Resolve(buffer);
188
195
  } else {
189
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
196
+ deferred_.Reject(NewPCSCError(env, result_).Value());
190
197
  }
191
198
  }
192
199
 
@@ -200,13 +207,16 @@ void ControlWorker::OnError(const Napi::Error& error) {
200
207
 
201
208
  ConnectWorker::ConnectWorker(
202
209
  Napi::Env env,
203
- SCARDCONTEXT context,
210
+ Napi::Object owner,
211
+ ContextHandlePtr context,
204
212
  std::string readerName,
205
213
  DWORD shareMode,
206
214
  DWORD preferredProtocols,
207
215
  Napi::Promise::Deferred deferred)
208
216
  : Napi::AsyncWorker(env),
209
- context_(context),
217
+ ownerRef_(Napi::Persistent(owner)),
218
+ contextHandle_(std::move(context)),
219
+ context_(contextHandle_->Get()),
210
220
  readerName_(std::move(readerName)),
211
221
  shareMode_(shareMode),
212
222
  preferredProtocols_(preferredProtocols),
@@ -231,10 +241,11 @@ void ConnectWorker::OnOK() {
231
241
  Napi::Env env = Env();
232
242
 
233
243
  if (result_ == SCARD_S_SUCCESS) {
234
- Napi::Object card = PCSCCard::NewInstance(env, card_, activeProtocol_, readerName_);
244
+ Napi::Object card = PCSCCard::NewInstance(
245
+ env, contextHandle_, card_, activeProtocol_, readerName_);
235
246
  deferred_.Resolve(card);
236
247
  } else {
237
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
248
+ deferred_.Reject(NewPCSCError(env, result_).Value());
238
249
  }
239
250
  }
240
251
 
@@ -248,6 +259,7 @@ void ConnectWorker::OnError(const Napi::Error& error) {
248
259
 
249
260
  ReconnectWorker::ReconnectWorker(
250
261
  Napi::Env env,
262
+ Napi::Object owner,
251
263
  SCARDHANDLE card,
252
264
  DWORD shareMode,
253
265
  DWORD preferredProtocols,
@@ -255,6 +267,7 @@ ReconnectWorker::ReconnectWorker(
255
267
  DWORD* protocolOut,
256
268
  Napi::Promise::Deferred deferred)
257
269
  : Napi::AsyncWorker(env),
270
+ ownerRef_(Napi::Persistent(owner)),
258
271
  card_(card),
259
272
  shareMode_(shareMode),
260
273
  preferredProtocols_(preferredProtocols),
@@ -285,7 +298,7 @@ void ReconnectWorker::OnOK() {
285
298
  }
286
299
  deferred_.Resolve(Napi::Number::New(env, activeProtocol_));
287
300
  } else {
288
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
301
+ deferred_.Reject(NewPCSCError(env, result_).Value());
289
302
  }
290
303
  }
291
304
 
@@ -4,11 +4,20 @@
4
4
  #include <vector>
5
5
  #include <string>
6
6
  #include "platform/pcsc.h"
7
+ #include "pcsc_context_handle.h"
8
+
9
+ // Every worker holds a Napi::ObjectReference to the JS object that owns its
10
+ // PC/SC handle (Card, Reader, or Context). Without it, GC can finalize the
11
+ // owner while Execute() is blocked in a PC/SC call: the finalizer disconnects
12
+ // or releases the handle out from under the worker, and PC/SC reuses handle
13
+ // values, so a late call can even land on a different card. The reference is
14
+ // released when the worker is destroyed on the main thread after OnOK/OnError.
7
15
 
8
16
  // Async worker for SCardGetStatusChange
9
17
  class WaitForChangeWorker : public Napi::AsyncWorker {
10
18
  public:
11
19
  WaitForChangeWorker(Napi::Env env,
20
+ Napi::Object owner,
12
21
  SCARDCONTEXT context,
13
22
  std::vector<std::string> readerNames,
14
23
  std::vector<DWORD> currentStates,
@@ -20,6 +29,7 @@ public:
20
29
  void OnError(const Napi::Error& error) override;
21
30
 
22
31
  private:
32
+ Napi::ObjectReference ownerRef_;
23
33
  SCARDCONTEXT context_;
24
34
  std::vector<std::string> readerNames_;
25
35
  std::vector<SCARD_READERSTATE> states_;
@@ -32,6 +42,7 @@ private:
32
42
  class TransmitWorker : public Napi::AsyncWorker {
33
43
  public:
34
44
  TransmitWorker(Napi::Env env,
45
+ Napi::Object owner,
35
46
  SCARDHANDLE card,
36
47
  DWORD protocol,
37
48
  std::vector<uint8_t> sendBuffer,
@@ -43,6 +54,7 @@ public:
43
54
  void OnError(const Napi::Error& error) override;
44
55
 
45
56
  private:
57
+ Napi::ObjectReference ownerRef_;
46
58
  SCARDHANDLE card_;
47
59
  DWORD protocol_;
48
60
  std::vector<uint8_t> sendBuffer_;
@@ -56,6 +68,7 @@ private:
56
68
  class ControlWorker : public Napi::AsyncWorker {
57
69
  public:
58
70
  ControlWorker(Napi::Env env,
71
+ Napi::Object owner,
59
72
  SCARDHANDLE card,
60
73
  DWORD controlCode,
61
74
  std::vector<uint8_t> sendBuffer,
@@ -66,6 +79,7 @@ public:
66
79
  void OnError(const Napi::Error& error) override;
67
80
 
68
81
  private:
82
+ Napi::ObjectReference ownerRef_;
69
83
  SCARDHANDLE card_;
70
84
  DWORD controlCode_;
71
85
  std::vector<uint8_t> sendBuffer_;
@@ -79,7 +93,8 @@ private:
79
93
  class ConnectWorker : public Napi::AsyncWorker {
80
94
  public:
81
95
  ConnectWorker(Napi::Env env,
82
- SCARDCONTEXT context,
96
+ Napi::Object owner,
97
+ ContextHandlePtr context,
83
98
  std::string readerName,
84
99
  DWORD shareMode,
85
100
  DWORD preferredProtocols,
@@ -90,6 +105,10 @@ public:
90
105
  void OnError(const Napi::Error& error) override;
91
106
 
92
107
  private:
108
+ Napi::ObjectReference ownerRef_;
109
+ // Handed to the new Card, which needs the context alive as long as it is
110
+ ContextHandlePtr contextHandle_;
111
+ // Copied on the main thread; Execute() never touches contextHandle_
93
112
  SCARDCONTEXT context_;
94
113
  std::string readerName_;
95
114
  DWORD shareMode_;
@@ -104,6 +123,7 @@ private:
104
123
  class ReconnectWorker : public Napi::AsyncWorker {
105
124
  public:
106
125
  ReconnectWorker(Napi::Env env,
126
+ Napi::Object owner,
107
127
  SCARDHANDLE card,
108
128
  DWORD shareMode,
109
129
  DWORD preferredProtocols,
@@ -118,11 +138,14 @@ public:
118
138
  DWORD GetActiveProtocol() const { return activeProtocol_; }
119
139
 
120
140
  private:
141
+ Napi::ObjectReference ownerRef_;
121
142
  SCARDHANDLE card_;
122
143
  DWORD shareMode_;
123
144
  DWORD preferredProtocols_;
124
145
  DWORD initialization_;
125
146
  DWORD activeProtocol_;
147
+ // Points into the owning PCSCCard; ownerRef_ keeps that object alive
148
+ // for the duration, so the pointer cannot dangle
126
149
  DWORD* protocolOut_;
127
150
  LONG result_;
128
151
  Napi::Promise::Deferred deferred_;
package/src/pcsc_card.cpp CHANGED
@@ -1,5 +1,6 @@
1
1
  #include "pcsc_card.h"
2
2
  #include "pcsc_errors.h"
3
+ #include "pcsc_napi_error.h"
3
4
  #include "async_workers.h"
4
5
  #include <cstring>
5
6
 
@@ -24,10 +25,12 @@ Napi::Object PCSCCard::Init(Napi::Env env, Napi::Object exports) {
24
25
  return exports;
25
26
  }
26
27
 
27
- Napi::Object PCSCCard::NewInstance(Napi::Env env, SCARDHANDLE card,
28
- DWORD protocol, const std::string& readerName) {
28
+ Napi::Object PCSCCard::NewInstance(Napi::Env env, ContextHandlePtr context,
29
+ SCARDHANDLE card, DWORD protocol,
30
+ const std::string& readerName) {
29
31
  Napi::Object obj = constructor.New({});
30
32
  PCSCCard* cardObj = Napi::ObjectWrap<PCSCCard>::Unwrap(obj);
33
+ cardObj->context_ = std::move(context);
31
34
  cardObj->card_ = card;
32
35
  cardObj->protocol_ = protocol;
33
36
  cardObj->readerName_ = readerName;
@@ -44,7 +47,7 @@ PCSCCard::PCSCCard(const Napi::CallbackInfo& info)
44
47
  }
45
48
 
46
49
  PCSCCard::~PCSCCard() {
47
- if (connected_ && card_ != 0) {
50
+ if (IsConnected() && card_ != 0) {
48
51
  SCardDisconnect(card_, SCARD_LEAVE_CARD);
49
52
  connected_ = false;
50
53
  card_ = 0;
@@ -56,13 +59,13 @@ Napi::Value PCSCCard::GetProtocolValue(const Napi::CallbackInfo& info) {
56
59
  }
57
60
 
58
61
  Napi::Value PCSCCard::GetConnectedValue(const Napi::CallbackInfo& info) {
59
- return Napi::Boolean::New(info.Env(), connected_);
62
+ return Napi::Boolean::New(info.Env(), IsConnected());
60
63
  }
61
64
 
62
65
  Napi::Value PCSCCard::GetAtr(const Napi::CallbackInfo& info) {
63
66
  Napi::Env env = info.Env();
64
67
 
65
- if (!connected_) {
68
+ if (!IsConnected()) {
66
69
  return env.Null();
67
70
  }
68
71
 
@@ -85,8 +88,8 @@ Napi::Value PCSCCard::GetAtr(const Napi::CallbackInfo& info) {
85
88
  Napi::Value PCSCCard::Transmit(const Napi::CallbackInfo& info) {
86
89
  Napi::Env env = info.Env();
87
90
 
88
- if (!connected_) {
89
- Napi::Error::New(env, "Card is not connected").ThrowAsJavaScriptException();
91
+ if (!IsConnected()) {
92
+ NewInvalidHandleError(env, "Card is not connected").ThrowAsJavaScriptException();
90
93
  return env.Null();
91
94
  }
92
95
 
@@ -124,7 +127,8 @@ Napi::Value PCSCCard::Transmit(const Napi::CallbackInfo& info) {
124
127
  Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
125
128
 
126
129
  TransmitWorker* worker = new TransmitWorker(
127
- env, card_, protocol_, sendBuffer, maxRecvLength, deferred);
130
+ env, info.This().As<Napi::Object>(), card_, protocol_, sendBuffer,
131
+ maxRecvLength, deferred);
128
132
  worker->Queue();
129
133
 
130
134
  return deferred.Promise();
@@ -133,8 +137,8 @@ Napi::Value PCSCCard::Transmit(const Napi::CallbackInfo& info) {
133
137
  Napi::Value PCSCCard::Control(const Napi::CallbackInfo& info) {
134
138
  Napi::Env env = info.Env();
135
139
 
136
- if (!connected_) {
137
- Napi::Error::New(env, "Card is not connected").ThrowAsJavaScriptException();
140
+ if (!IsConnected()) {
141
+ NewInvalidHandleError(env, "Card is not connected").ThrowAsJavaScriptException();
138
142
  return env.Null();
139
143
  }
140
144
 
@@ -163,7 +167,7 @@ Napi::Value PCSCCard::Control(const Napi::CallbackInfo& info) {
163
167
  Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
164
168
 
165
169
  ControlWorker* worker = new ControlWorker(
166
- env, card_, controlCode, sendBuffer, deferred);
170
+ env, info.This().As<Napi::Object>(), card_, controlCode, sendBuffer, deferred);
167
171
  worker->Queue();
168
172
 
169
173
  return deferred.Promise();
@@ -172,8 +176,8 @@ Napi::Value PCSCCard::Control(const Napi::CallbackInfo& info) {
172
176
  Napi::Value PCSCCard::GetStatus(const Napi::CallbackInfo& info) {
173
177
  Napi::Env env = info.Env();
174
178
 
175
- if (!connected_) {
176
- Napi::Error::New(env, "Card is not connected").ThrowAsJavaScriptException();
179
+ if (!IsConnected()) {
180
+ NewInvalidHandleError(env, "Card is not connected").ThrowAsJavaScriptException();
177
181
  return env.Null();
178
182
  }
179
183
 
@@ -187,7 +191,7 @@ Napi::Value PCSCCard::GetStatus(const Napi::CallbackInfo& info) {
187
191
  LONG result = SCardStatus(card_, nullptr, &readerLen, &state, &protocol, atr, &atrLen);
188
192
 
189
193
  if (result != SCARD_S_SUCCESS) {
190
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
194
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
191
195
  return env.Null();
192
196
  }
193
197
 
@@ -202,7 +206,7 @@ Napi::Value PCSCCard::GetStatus(const Napi::CallbackInfo& info) {
202
206
  Napi::Value PCSCCard::Disconnect(const Napi::CallbackInfo& info) {
203
207
  Napi::Env env = info.Env();
204
208
 
205
- if (!connected_) {
209
+ if (!IsConnected()) {
206
210
  return env.Undefined();
207
211
  }
208
212
 
@@ -216,7 +220,7 @@ Napi::Value PCSCCard::Disconnect(const Napi::CallbackInfo& info) {
216
220
  card_ = 0;
217
221
 
218
222
  if (result != SCARD_S_SUCCESS) {
219
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
223
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
220
224
  }
221
225
 
222
226
  return env.Undefined();
@@ -225,8 +229,8 @@ Napi::Value PCSCCard::Disconnect(const Napi::CallbackInfo& info) {
225
229
  Napi::Value PCSCCard::Reconnect(const Napi::CallbackInfo& info) {
226
230
  Napi::Env env = info.Env();
227
231
 
228
- if (!connected_) {
229
- Napi::Error::New(env, "Card is not connected").ThrowAsJavaScriptException();
232
+ if (!IsConnected()) {
233
+ NewInvalidHandleError(env, "Card is not connected").ThrowAsJavaScriptException();
230
234
  return env.Null();
231
235
  }
232
236
 
@@ -248,7 +252,8 @@ Napi::Value PCSCCard::Reconnect(const Napi::CallbackInfo& info) {
248
252
  Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
249
253
 
250
254
  ReconnectWorker* worker = new ReconnectWorker(
251
- env, card_, shareMode, preferredProtocols, initialization, &protocol_, deferred);
255
+ env, info.This().As<Napi::Object>(), card_, shareMode, preferredProtocols,
256
+ initialization, &protocol_, deferred);
252
257
  worker->Queue();
253
258
 
254
259
  return deferred.Promise();
package/src/pcsc_card.h CHANGED
@@ -4,12 +4,14 @@
4
4
  #include <string>
5
5
  #include <vector>
6
6
  #include "platform/pcsc.h"
7
+ #include "pcsc_context_handle.h"
7
8
 
8
9
  class PCSCCard : public Napi::ObjectWrap<PCSCCard> {
9
10
  public:
10
11
  static Napi::Object Init(Napi::Env env, Napi::Object exports);
11
- static Napi::Object NewInstance(Napi::Env env, SCARDHANDLE card,
12
- DWORD protocol, const std::string& readerName);
12
+ static Napi::Object NewInstance(Napi::Env env, ContextHandlePtr context,
13
+ SCARDHANDLE card, DWORD protocol,
14
+ const std::string& readerName);
13
15
 
14
16
  PCSCCard(const Napi::CallbackInfo& info);
15
17
  ~PCSCCard();
@@ -17,11 +19,17 @@ public:
17
19
  // Accessors
18
20
  SCARDHANDLE GetHandle() const { return card_; }
19
21
  DWORD GetProtocol() const { return protocol_; }
20
- bool IsConnected() const { return connected_; }
22
+ // A card handle dies with its context: once Context.close() releases
23
+ // it, PC/SC may give the same handle value to a new connection, so the
24
+ // handle must never be used again
25
+ bool IsConnected() const { return connected_ && context_ && context_->IsValid(); }
21
26
 
22
27
  private:
23
28
  static Napi::FunctionReference constructor;
24
29
 
30
+ // Keeps the context alive for as long as this card; destroyed after
31
+ // ~PCSCCard's body, so the card disconnects before the context goes
32
+ ContextHandlePtr context_;
25
33
  SCARDHANDLE card_;
26
34
  DWORD protocol_;
27
35
  std::string readerName_;
@@ -1,6 +1,7 @@
1
1
  #include "pcsc_context.h"
2
2
  #include "pcsc_reader.h"
3
3
  #include "pcsc_errors.h"
4
+ #include "pcsc_napi_error.h"
4
5
  #include "async_workers.h"
5
6
  #include <cstring>
6
7
 
@@ -27,57 +28,52 @@ Napi::Object PCSCContext::NewInstance(Napi::Env env) {
27
28
  }
28
29
 
29
30
  PCSCContext::PCSCContext(const Napi::CallbackInfo& info)
30
- : Napi::ObjectWrap<PCSCContext>(info), context_(0), valid_(false) {
31
+ : Napi::ObjectWrap<PCSCContext>(info) {
31
32
 
32
33
  Napi::Env env = info.Env();
33
34
 
34
35
  // Establish PC/SC context
35
- LONG result = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context_);
36
+ SCARDCONTEXT context = 0;
37
+ LONG result = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context);
36
38
 
37
39
  if (result != SCARD_S_SUCCESS) {
38
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
40
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
39
41
  return;
40
42
  }
41
43
 
42
- valid_ = true;
43
- }
44
-
45
- PCSCContext::~PCSCContext() {
46
- if (valid_ && context_ != 0) {
47
- SCardReleaseContext(context_);
48
- valid_ = false;
49
- context_ = 0;
50
- }
44
+ handle_ = std::make_shared<ContextHandle>(context);
51
45
  }
52
46
 
53
47
  Napi::Value PCSCContext::ListReaders(const Napi::CallbackInfo& info) {
54
48
  Napi::Env env = info.Env();
55
49
 
56
- if (!valid_) {
57
- Napi::Error::New(env, "Context is not valid").ThrowAsJavaScriptException();
50
+ if (!IsValid()) {
51
+ NewInvalidHandleError(env, "Context is not valid").ThrowAsJavaScriptException();
58
52
  return env.Null();
59
53
  }
60
54
 
55
+ SCARDCONTEXT context = handle_->Get();
56
+
61
57
  // First call to get buffer size
62
58
  DWORD readersLen = 0;
63
- LONG result = SCardListReaders(context_, nullptr, nullptr, &readersLen);
59
+ LONG result = SCardListReaders(context, nullptr, nullptr, &readersLen);
64
60
 
65
- if (result == SCARD_E_NO_READERS_AVAILABLE) {
61
+ if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)) {
66
62
  // No readers - return empty array
67
63
  return Napi::Array::New(env, 0);
68
64
  }
69
65
 
70
66
  if (result != SCARD_S_SUCCESS) {
71
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
67
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
72
68
  return env.Null();
73
69
  }
74
70
 
75
71
  // Allocate buffer and get reader names
76
72
  std::vector<char> readersBuffer(readersLen);
77
- result = SCardListReaders(context_, nullptr, readersBuffer.data(), &readersLen);
73
+ result = SCardListReaders(context, nullptr, readersBuffer.data(), &readersLen);
78
74
 
79
75
  if (result != SCARD_S_SUCCESS) {
80
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
76
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
81
77
  return env.Null();
82
78
  }
83
79
 
@@ -97,7 +93,7 @@ Napi::Value PCSCContext::ListReaders(const Napi::CallbackInfo& info) {
97
93
  }
98
94
 
99
95
  // Get current state (non-blocking with 0 timeout)
100
- result = SCardGetStatusChange(context_, 0, states.data(), states.size());
96
+ result = SCardGetStatusChange(context, 0, states.data(), states.size());
101
97
 
102
98
  // Create Reader objects
103
99
  Napi::Array readers = Napi::Array::New(env, readerNames.size());
@@ -108,7 +104,7 @@ Napi::Value PCSCContext::ListReaders(const Napi::CallbackInfo& info) {
108
104
  }
109
105
  DWORD state = (result == SCARD_S_SUCCESS) ? states[i].dwEventState : 0;
110
106
 
111
- Napi::Object reader = PCSCReader::NewInstance(env, context_, readerNames[i], state, atr);
107
+ Napi::Object reader = PCSCReader::NewInstance(env, handle_, readerNames[i], state, atr);
112
108
  readers.Set(static_cast<uint32_t>(i), reader);
113
109
  }
114
110
 
@@ -118,11 +114,13 @@ Napi::Value PCSCContext::ListReaders(const Napi::CallbackInfo& info) {
118
114
  Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
119
115
  Napi::Env env = info.Env();
120
116
 
121
- if (!valid_) {
122
- Napi::Error::New(env, "Context is not valid").ThrowAsJavaScriptException();
117
+ if (!IsValid()) {
118
+ NewInvalidHandleError(env, "Context is not valid").ThrowAsJavaScriptException();
123
119
  return env.Null();
124
120
  }
125
121
 
122
+ SCARDCONTEXT context = handle_->Get();
123
+
126
124
  // Parse arguments: readers array (optional), timeout (optional)
127
125
  std::vector<std::string> readerNames;
128
126
  std::vector<DWORD> currentStates;
@@ -162,15 +160,15 @@ Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
162
160
  // If no readers specified, get all readers
163
161
  if (readerNames.empty()) {
164
162
  DWORD readersLen = 0;
165
- LONG result = SCardListReaders(context_, nullptr, nullptr, &readersLen);
163
+ LONG result = SCardListReaders(context, nullptr, nullptr, &readersLen);
166
164
 
167
- if (result == SCARD_E_NO_READERS_AVAILABLE) {
165
+ if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)) {
168
166
  // Add PnP notification to detect when readers are attached
169
167
  readerNames.push_back("\\\\?PnP?\\Notification");
170
168
  currentStates.push_back(SCARD_STATE_UNAWARE);
171
169
  } else if (result == SCARD_S_SUCCESS) {
172
170
  std::vector<char> readersBuffer(readersLen);
173
- result = SCardListReaders(context_, nullptr, readersBuffer.data(), &readersLen);
171
+ result = SCardListReaders(context, nullptr, readersBuffer.data(), &readersLen);
174
172
  if (result == SCARD_S_SUCCESS) {
175
173
  const char* p = readersBuffer.data();
176
174
  while (*p != '\0') {
@@ -186,7 +184,8 @@ Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
186
184
  Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
187
185
 
188
186
  WaitForChangeWorker* worker = new WaitForChangeWorker(
189
- env, context_, readerNames, currentStates, timeout, deferred);
187
+ env, info.This().As<Napi::Object>(), context, readerNames, currentStates,
188
+ timeout, deferred);
190
189
  worker->Queue();
191
190
 
192
191
  return deferred.Promise();
@@ -195,13 +194,13 @@ Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
195
194
  Napi::Value PCSCContext::Cancel(const Napi::CallbackInfo& info) {
196
195
  Napi::Env env = info.Env();
197
196
 
198
- if (!valid_) {
197
+ if (!IsValid()) {
199
198
  return env.Undefined();
200
199
  }
201
200
 
202
- LONG result = SCardCancel(context_);
203
- if (result != SCARD_S_SUCCESS && result != SCARD_E_INVALID_HANDLE) {
204
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
201
+ LONG result = SCardCancel(handle_->Get());
202
+ if (result != SCARD_S_SUCCESS && result != static_cast<LONG>(SCARD_E_INVALID_HANDLE)) {
203
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
205
204
  }
206
205
 
207
206
  return env.Undefined();
@@ -210,15 +209,15 @@ Napi::Value PCSCContext::Cancel(const Napi::CallbackInfo& info) {
210
209
  Napi::Value PCSCContext::Close(const Napi::CallbackInfo& info) {
211
210
  Napi::Env env = info.Env();
212
211
 
213
- if (valid_ && context_ != 0) {
214
- SCardReleaseContext(context_);
215
- valid_ = false;
216
- context_ = 0;
212
+ // Release now, even if readers or cards still hold the handle: they
213
+ // see it as invalid from here on and stop using it
214
+ if (handle_) {
215
+ handle_->Release();
217
216
  }
218
217
 
219
218
  return env.Undefined();
220
219
  }
221
220
 
222
221
  Napi::Value PCSCContext::GetIsValid(const Napi::CallbackInfo& info) {
223
- return Napi::Boolean::New(info.Env(), valid_);
222
+ return Napi::Boolean::New(info.Env(), IsValid());
224
223
  }
@@ -4,6 +4,7 @@
4
4
  #include <string>
5
5
  #include <vector>
6
6
  #include "platform/pcsc.h"
7
+ #include "pcsc_context_handle.h"
7
8
 
8
9
  class PCSCContext : public Napi::ObjectWrap<PCSCContext> {
9
10
  public:
@@ -11,17 +12,17 @@ public:
11
12
  static Napi::Object NewInstance(Napi::Env env);
12
13
 
13
14
  PCSCContext(const Napi::CallbackInfo& info);
14
- ~PCSCContext();
15
15
 
16
16
  // Get the raw context handle (for use by other classes)
17
- SCARDCONTEXT GetContext() const { return context_; }
18
- bool IsValid() const { return valid_; }
17
+ SCARDCONTEXT GetContext() const { return handle_ ? handle_->Get() : 0; }
18
+ bool IsValid() const { return handle_ && handle_->IsValid(); }
19
19
 
20
20
  private:
21
21
  static Napi::FunctionReference constructor;
22
22
 
23
- SCARDCONTEXT context_;
24
- bool valid_;
23
+ // Shared with the Readers (and their Cards) created from this context;
24
+ // released when the last of them is finalized, or by close()
25
+ ContextHandlePtr handle_;
25
26
 
26
27
  // JavaScript-exposed methods
27
28
  Napi::Value ListReaders(const Napi::CallbackInfo& info);
@@ -0,0 +1,39 @@
1
+ #pragma once
2
+
3
+ #include <memory>
4
+ #include "platform/pcsc.h"
5
+
6
+ // An SCARDCONTEXT shared by the Context that established it and every Reader
7
+ // and Card created from it. PC/SC invalidates all card handles when their
8
+ // context is released, and GC finalizes those objects in no particular order,
9
+ // so the release waits for the last holder - unless Context.close() releases
10
+ // it explicitly, after which holders see IsValid() == false.
11
+ //
12
+ // Shared ownership rather than JS references between the objects: a
13
+ // persistent napi reference is a GC root, so Context <-> Reader/Card links
14
+ // held that way would keep a cycle alive forever.
15
+ //
16
+ // Main thread only. Async workers copy Get() when they are created.
17
+ class ContextHandle {
18
+ public:
19
+ explicit ContextHandle(SCARDCONTEXT context) : context_(context) {}
20
+ ~ContextHandle() { Release(); }
21
+
22
+ ContextHandle(const ContextHandle&) = delete;
23
+ ContextHandle& operator=(const ContextHandle&) = delete;
24
+
25
+ SCARDCONTEXT Get() const { return context_; }
26
+ bool IsValid() const { return context_ != 0; }
27
+
28
+ void Release() {
29
+ if (context_ != 0) {
30
+ SCardReleaseContext(context_);
31
+ context_ = 0;
32
+ }
33
+ }
34
+
35
+ private:
36
+ SCARDCONTEXT context_;
37
+ };
38
+
39
+ using ContextHandlePtr = std::shared_ptr<ContextHandle>;