smartcard 3.7.2 → 3.9.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.
package/src/pcsc_card.cpp CHANGED
@@ -1,10 +1,10 @@
1
1
  #include "pcsc_card.h"
2
2
  #include "pcsc_errors.h"
3
+ #include "pcsc_napi_error.h"
4
+ #include "addon_data.h"
3
5
  #include "async_workers.h"
4
6
  #include <cstring>
5
7
 
6
- Napi::FunctionReference PCSCCard::constructor;
7
-
8
8
  Napi::Object PCSCCard::Init(Napi::Env env, Napi::Object exports) {
9
9
  Napi::Function func = DefineClass(env, "Card", {
10
10
  InstanceAccessor("protocol", &PCSCCard::GetProtocolValue, nullptr),
@@ -17,17 +17,18 @@ Napi::Object PCSCCard::Init(Napi::Env env, Napi::Object exports) {
17
17
  InstanceMethod("reconnect", &PCSCCard::Reconnect),
18
18
  });
19
19
 
20
- constructor = Napi::Persistent(func);
21
- constructor.SuppressDestruct();
20
+ env.GetInstanceData<AddonData>()->cardConstructor = Napi::Persistent(func);
22
21
 
23
22
  exports.Set("Card", func);
24
23
  return exports;
25
24
  }
26
25
 
27
- Napi::Object PCSCCard::NewInstance(Napi::Env env, SCARDHANDLE card,
28
- DWORD protocol, const std::string& readerName) {
29
- Napi::Object obj = constructor.New({});
26
+ Napi::Object PCSCCard::NewInstance(Napi::Env env, ContextHandlePtr context,
27
+ SCARDHANDLE card, DWORD protocol,
28
+ const std::string& readerName) {
29
+ Napi::Object obj = env.GetInstanceData<AddonData>()->cardConstructor.New({});
30
30
  PCSCCard* cardObj = Napi::ObjectWrap<PCSCCard>::Unwrap(obj);
31
+ cardObj->context_ = std::move(context);
31
32
  cardObj->card_ = card;
32
33
  cardObj->protocol_ = protocol;
33
34
  cardObj->readerName_ = readerName;
@@ -44,7 +45,7 @@ PCSCCard::PCSCCard(const Napi::CallbackInfo& info)
44
45
  }
45
46
 
46
47
  PCSCCard::~PCSCCard() {
47
- if (connected_ && card_ != 0) {
48
+ if (IsConnected() && card_ != 0) {
48
49
  SCardDisconnect(card_, SCARD_LEAVE_CARD);
49
50
  connected_ = false;
50
51
  card_ = 0;
@@ -56,13 +57,13 @@ Napi::Value PCSCCard::GetProtocolValue(const Napi::CallbackInfo& info) {
56
57
  }
57
58
 
58
59
  Napi::Value PCSCCard::GetConnectedValue(const Napi::CallbackInfo& info) {
59
- return Napi::Boolean::New(info.Env(), connected_);
60
+ return Napi::Boolean::New(info.Env(), IsConnected());
60
61
  }
61
62
 
62
63
  Napi::Value PCSCCard::GetAtr(const Napi::CallbackInfo& info) {
63
64
  Napi::Env env = info.Env();
64
65
 
65
- if (!connected_) {
66
+ if (!IsConnected()) {
66
67
  return env.Null();
67
68
  }
68
69
 
@@ -85,8 +86,8 @@ Napi::Value PCSCCard::GetAtr(const Napi::CallbackInfo& info) {
85
86
  Napi::Value PCSCCard::Transmit(const Napi::CallbackInfo& info) {
86
87
  Napi::Env env = info.Env();
87
88
 
88
- if (!connected_) {
89
- Napi::Error::New(env, "Card is not connected").ThrowAsJavaScriptException();
89
+ if (!IsConnected()) {
90
+ NewInvalidHandleError(env, "Card is not connected").ThrowAsJavaScriptException();
90
91
  return env.Null();
91
92
  }
92
93
 
@@ -124,7 +125,8 @@ Napi::Value PCSCCard::Transmit(const Napi::CallbackInfo& info) {
124
125
  Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
125
126
 
126
127
  TransmitWorker* worker = new TransmitWorker(
127
- env, card_, protocol_, sendBuffer, maxRecvLength, deferred);
128
+ env, info.This().As<Napi::Object>(), card_, protocol_, sendBuffer,
129
+ maxRecvLength, deferred);
128
130
  worker->Queue();
129
131
 
130
132
  return deferred.Promise();
@@ -133,8 +135,8 @@ Napi::Value PCSCCard::Transmit(const Napi::CallbackInfo& info) {
133
135
  Napi::Value PCSCCard::Control(const Napi::CallbackInfo& info) {
134
136
  Napi::Env env = info.Env();
135
137
 
136
- if (!connected_) {
137
- Napi::Error::New(env, "Card is not connected").ThrowAsJavaScriptException();
138
+ if (!IsConnected()) {
139
+ NewInvalidHandleError(env, "Card is not connected").ThrowAsJavaScriptException();
138
140
  return env.Null();
139
141
  }
140
142
 
@@ -163,7 +165,7 @@ Napi::Value PCSCCard::Control(const Napi::CallbackInfo& info) {
163
165
  Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
164
166
 
165
167
  ControlWorker* worker = new ControlWorker(
166
- env, card_, controlCode, sendBuffer, deferred);
168
+ env, info.This().As<Napi::Object>(), card_, controlCode, sendBuffer, deferred);
167
169
  worker->Queue();
168
170
 
169
171
  return deferred.Promise();
@@ -172,8 +174,8 @@ Napi::Value PCSCCard::Control(const Napi::CallbackInfo& info) {
172
174
  Napi::Value PCSCCard::GetStatus(const Napi::CallbackInfo& info) {
173
175
  Napi::Env env = info.Env();
174
176
 
175
- if (!connected_) {
176
- Napi::Error::New(env, "Card is not connected").ThrowAsJavaScriptException();
177
+ if (!IsConnected()) {
178
+ NewInvalidHandleError(env, "Card is not connected").ThrowAsJavaScriptException();
177
179
  return env.Null();
178
180
  }
179
181
 
@@ -187,7 +189,7 @@ Napi::Value PCSCCard::GetStatus(const Napi::CallbackInfo& info) {
187
189
  LONG result = SCardStatus(card_, nullptr, &readerLen, &state, &protocol, atr, &atrLen);
188
190
 
189
191
  if (result != SCARD_S_SUCCESS) {
190
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
192
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
191
193
  return env.Null();
192
194
  }
193
195
 
@@ -202,7 +204,7 @@ Napi::Value PCSCCard::GetStatus(const Napi::CallbackInfo& info) {
202
204
  Napi::Value PCSCCard::Disconnect(const Napi::CallbackInfo& info) {
203
205
  Napi::Env env = info.Env();
204
206
 
205
- if (!connected_) {
207
+ if (!IsConnected()) {
206
208
  return env.Undefined();
207
209
  }
208
210
 
@@ -216,7 +218,7 @@ Napi::Value PCSCCard::Disconnect(const Napi::CallbackInfo& info) {
216
218
  card_ = 0;
217
219
 
218
220
  if (result != SCARD_S_SUCCESS) {
219
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
221
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
220
222
  }
221
223
 
222
224
  return env.Undefined();
@@ -225,8 +227,8 @@ Napi::Value PCSCCard::Disconnect(const Napi::CallbackInfo& info) {
225
227
  Napi::Value PCSCCard::Reconnect(const Napi::CallbackInfo& info) {
226
228
  Napi::Env env = info.Env();
227
229
 
228
- if (!connected_) {
229
- Napi::Error::New(env, "Card is not connected").ThrowAsJavaScriptException();
230
+ if (!IsConnected()) {
231
+ NewInvalidHandleError(env, "Card is not connected").ThrowAsJavaScriptException();
230
232
  return env.Null();
231
233
  }
232
234
 
@@ -248,7 +250,8 @@ Napi::Value PCSCCard::Reconnect(const Napi::CallbackInfo& info) {
248
250
  Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
249
251
 
250
252
  ReconnectWorker* worker = new ReconnectWorker(
251
- env, card_, shareMode, preferredProtocols, initialization, &protocol_, deferred);
253
+ env, info.This().As<Napi::Object>(), card_, shareMode, preferredProtocols,
254
+ initialization, &protocol_, deferred);
252
255
  worker->Queue();
253
256
 
254
257
  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,15 @@ 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
- static Napi::FunctionReference constructor;
24
-
28
+ // Keeps the context alive for as long as this card; destroyed after
29
+ // ~PCSCCard's body, so the card disconnects before the context goes
30
+ ContextHandlePtr context_;
25
31
  SCARDHANDLE card_;
26
32
  DWORD protocol_;
27
33
  std::string readerName_;
@@ -1,11 +1,10 @@
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
 
7
- Napi::FunctionReference PCSCContext::constructor;
8
-
9
8
  Napi::Object PCSCContext::Init(Napi::Env env, Napi::Object exports) {
10
9
  Napi::Function func = DefineClass(env, "Context", {
11
10
  InstanceMethod("listReaders", &PCSCContext::ListReaders),
@@ -15,69 +14,58 @@ Napi::Object PCSCContext::Init(Napi::Env env, Napi::Object exports) {
15
14
  InstanceAccessor("isValid", &PCSCContext::GetIsValid, nullptr),
16
15
  });
17
16
 
18
- constructor = Napi::Persistent(func);
19
- constructor.SuppressDestruct();
20
-
21
17
  exports.Set("Context", func);
22
18
  return exports;
23
19
  }
24
20
 
25
- Napi::Object PCSCContext::NewInstance(Napi::Env env) {
26
- return constructor.New({});
27
- }
28
-
29
21
  PCSCContext::PCSCContext(const Napi::CallbackInfo& info)
30
- : Napi::ObjectWrap<PCSCContext>(info), context_(0), valid_(false) {
22
+ : Napi::ObjectWrap<PCSCContext>(info),
23
+ pendingWaits_(std::make_shared<WaitForChangeWorker::PendingWaits>()) {
31
24
 
32
25
  Napi::Env env = info.Env();
33
26
 
34
27
  // Establish PC/SC context
35
- LONG result = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context_);
28
+ SCARDCONTEXT context = 0;
29
+ LONG result = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context);
36
30
 
37
31
  if (result != SCARD_S_SUCCESS) {
38
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
32
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
39
33
  return;
40
34
  }
41
35
 
42
- valid_ = true;
43
- }
44
-
45
- PCSCContext::~PCSCContext() {
46
- if (valid_ && context_ != 0) {
47
- SCardReleaseContext(context_);
48
- valid_ = false;
49
- context_ = 0;
50
- }
36
+ handle_ = std::make_shared<ContextHandle>(context);
51
37
  }
52
38
 
53
39
  Napi::Value PCSCContext::ListReaders(const Napi::CallbackInfo& info) {
54
40
  Napi::Env env = info.Env();
55
41
 
56
- if (!valid_) {
57
- Napi::Error::New(env, "Context is not valid").ThrowAsJavaScriptException();
42
+ if (!IsValid()) {
43
+ NewInvalidHandleError(env, "Context is not valid").ThrowAsJavaScriptException();
58
44
  return env.Null();
59
45
  }
60
46
 
47
+ SCARDCONTEXT context = handle_->Get();
48
+
61
49
  // First call to get buffer size
62
50
  DWORD readersLen = 0;
63
- LONG result = SCardListReaders(context_, nullptr, nullptr, &readersLen);
51
+ LONG result = SCardListReaders(context, nullptr, nullptr, &readersLen);
64
52
 
65
- if (result == SCARD_E_NO_READERS_AVAILABLE) {
53
+ if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)) {
66
54
  // No readers - return empty array
67
55
  return Napi::Array::New(env, 0);
68
56
  }
69
57
 
70
58
  if (result != SCARD_S_SUCCESS) {
71
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
59
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
72
60
  return env.Null();
73
61
  }
74
62
 
75
63
  // Allocate buffer and get reader names
76
64
  std::vector<char> readersBuffer(readersLen);
77
- result = SCardListReaders(context_, nullptr, readersBuffer.data(), &readersLen);
65
+ result = SCardListReaders(context, nullptr, readersBuffer.data(), &readersLen);
78
66
 
79
67
  if (result != SCARD_S_SUCCESS) {
80
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
68
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
81
69
  return env.Null();
82
70
  }
83
71
 
@@ -97,7 +85,7 @@ Napi::Value PCSCContext::ListReaders(const Napi::CallbackInfo& info) {
97
85
  }
98
86
 
99
87
  // Get current state (non-blocking with 0 timeout)
100
- result = SCardGetStatusChange(context_, 0, states.data(), states.size());
88
+ result = SCardGetStatusChange(context, 0, states.data(), states.size());
101
89
 
102
90
  // Create Reader objects
103
91
  Napi::Array readers = Napi::Array::New(env, readerNames.size());
@@ -108,7 +96,7 @@ Napi::Value PCSCContext::ListReaders(const Napi::CallbackInfo& info) {
108
96
  }
109
97
  DWORD state = (result == SCARD_S_SUCCESS) ? states[i].dwEventState : 0;
110
98
 
111
- Napi::Object reader = PCSCReader::NewInstance(env, context_, readerNames[i], state, atr);
99
+ Napi::Object reader = PCSCReader::NewInstance(env, handle_, readerNames[i], state, atr);
112
100
  readers.Set(static_cast<uint32_t>(i), reader);
113
101
  }
114
102
 
@@ -118,11 +106,13 @@ Napi::Value PCSCContext::ListReaders(const Napi::CallbackInfo& info) {
118
106
  Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
119
107
  Napi::Env env = info.Env();
120
108
 
121
- if (!valid_) {
122
- Napi::Error::New(env, "Context is not valid").ThrowAsJavaScriptException();
109
+ if (!IsValid()) {
110
+ NewInvalidHandleError(env, "Context is not valid").ThrowAsJavaScriptException();
123
111
  return env.Null();
124
112
  }
125
113
 
114
+ SCARDCONTEXT context = handle_->Get();
115
+
126
116
  // Parse arguments: readers array (optional), timeout (optional)
127
117
  std::vector<std::string> readerNames;
128
118
  std::vector<DWORD> currentStates;
@@ -162,15 +152,15 @@ Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
162
152
  // If no readers specified, get all readers
163
153
  if (readerNames.empty()) {
164
154
  DWORD readersLen = 0;
165
- LONG result = SCardListReaders(context_, nullptr, nullptr, &readersLen);
155
+ LONG result = SCardListReaders(context, nullptr, nullptr, &readersLen);
166
156
 
167
- if (result == SCARD_E_NO_READERS_AVAILABLE) {
157
+ if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)) {
168
158
  // Add PnP notification to detect when readers are attached
169
159
  readerNames.push_back("\\\\?PnP?\\Notification");
170
160
  currentStates.push_back(SCARD_STATE_UNAWARE);
171
161
  } else if (result == SCARD_S_SUCCESS) {
172
162
  std::vector<char> readersBuffer(readersLen);
173
- result = SCardListReaders(context_, nullptr, readersBuffer.data(), &readersLen);
163
+ result = SCardListReaders(context, nullptr, readersBuffer.data(), &readersLen);
174
164
  if (result == SCARD_S_SUCCESS) {
175
165
  const char* p = readersBuffer.data();
176
166
  while (*p != '\0') {
@@ -180,45 +170,49 @@ Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
180
170
  }
181
171
  }
182
172
  }
173
+ if (result != SCARD_S_SUCCESS &&
174
+ result != static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)) {
175
+ // No list to wait on: a wait on no readers would return at
176
+ // once, as if it had timed out
177
+ Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
178
+ deferred.Reject(NewPCSCError(env, result).Value());
179
+ return deferred.Promise();
180
+ }
183
181
  }
184
182
 
185
- // Create promise and start async worker
186
- Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
187
-
188
- WaitForChangeWorker* worker = new WaitForChangeWorker(
189
- env, context_, readerNames, currentStates, timeout, deferred);
190
- worker->Queue();
191
-
192
- return deferred.Promise();
183
+ return WaitForChangeWorker::Start(
184
+ env, pendingWaits_, std::move(readerNames), std::move(currentStates), timeout);
193
185
  }
194
186
 
195
- Napi::Value PCSCContext::Cancel(const Napi::CallbackInfo& info) {
196
- Napi::Env env = info.Env();
197
-
198
- if (!valid_) {
199
- return env.Undefined();
200
- }
201
-
202
- LONG result = SCardCancel(context_);
203
- if (result != SCARD_S_SUCCESS && result != SCARD_E_INVALID_HANDLE) {
204
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
187
+ void PCSCContext::CancelPendingWaits() {
188
+ for (WaitForChangeWorker* wait : *pendingWaits_) {
189
+ wait->Cancel();
205
190
  }
191
+ }
206
192
 
207
- return env.Undefined();
193
+ // Ends every waitForChange() pending on this context: one that hasn't
194
+ // returned yet resolves with null. A wait has a context of its own, so
195
+ // this works even once close() has released this one.
196
+ Napi::Value PCSCContext::Cancel(const Napi::CallbackInfo& info) {
197
+ CancelPendingWaits();
198
+ return info.Env().Undefined();
208
199
  }
209
200
 
210
201
  Napi::Value PCSCContext::Close(const Napi::CallbackInfo& info) {
211
202
  Napi::Env env = info.Env();
212
203
 
213
- if (valid_ && context_ != 0) {
214
- SCardReleaseContext(context_);
215
- valid_ = false;
216
- context_ = 0;
204
+ // Pending waits end as if cancelled
205
+ CancelPendingWaits();
206
+
207
+ // Release now, even if readers or cards still hold the handle: they
208
+ // see it as invalid from here on and stop using it
209
+ if (handle_) {
210
+ handle_->Release();
217
211
  }
218
212
 
219
213
  return env.Undefined();
220
214
  }
221
215
 
222
216
  Napi::Value PCSCContext::GetIsValid(const Napi::CallbackInfo& info) {
223
- return Napi::Boolean::New(info.Env(), valid_);
217
+ return Napi::Boolean::New(info.Env(), IsValid());
224
218
  }
@@ -4,24 +4,29 @@
4
4
  #include <string>
5
5
  #include <vector>
6
6
  #include "platform/pcsc.h"
7
+ #include "pcsc_context_handle.h"
8
+ #include "async_workers.h"
7
9
 
8
10
  class PCSCContext : public Napi::ObjectWrap<PCSCContext> {
9
11
  public:
10
12
  static Napi::Object Init(Napi::Env env, Napi::Object exports);
11
- 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
- static Napi::FunctionReference constructor;
21
+ // Shared with the Readers (and their Cards) created from this context;
22
+ // released when the last of them is finalized, or by close()
23
+ ContextHandlePtr handle_;
22
24
 
23
- SCARDCONTEXT context_;
24
- bool valid_;
25
+ // waitForChange() calls still pending, each on a context of its own:
26
+ // cancel() and close() end them
27
+ WaitForChangeWorker::PendingWaitsPtr pendingWaits_;
28
+
29
+ void CancelPendingWaits();
25
30
 
26
31
  // JavaScript-exposed methods
27
32
  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>;
package/src/pcsc_errors.h CHANGED
@@ -40,6 +40,41 @@ inline const char* GetPCSCErrorString(LONG code) {
40
40
  if (ucode == SCARD_W_UNRESPONSIVE_CARD) return "Card is unresponsive";
41
41
  if (ucode == SCARD_W_UNSUPPORTED_CARD) return "Card is not supported";
42
42
 
43
+ // Extended mappings - numeric literals because macro availability differs
44
+ // between winscard.h and pcsc-lite while the code values are shared
45
+ // (MS SCARD error space). Note: 0x8010001F is SCARD_E_UNEXPECTED on
46
+ // Windows but SCARD_E_UNSUPPORTED_FEATURE on pcsc-lite.
47
+ if (ucode == 0x80100007) return "Waited too long"; // SCARD_F_WAITED_TOO_LONG
48
+ if (ucode == 0x80100014) return "Unknown internal error"; // SCARD_F_UNKNOWN_ERROR
49
+ if (ucode == 0x80100018) return "Service shutting down"; // SCARD_P_SHUTDOWN
50
+ if (ucode == 0x8010001A) return "Reader unsupported"; // SCARD_E_READER_UNSUPPORTED
51
+ if (ucode == 0x8010001B) return "Duplicate reader name"; // SCARD_E_DUPLICATE_READER
52
+ if (ucode == 0x8010001C) return "Card unsupported"; // SCARD_E_CARD_UNSUPPORTED
53
+ if (ucode == 0x8010001F) return "Unexpected error / unsupported feature"; // SCARD_E_UNEXPECTED (win) / SCARD_E_UNSUPPORTED_FEATURE (pcsc-lite)
54
+ if (ucode == 0x80100020) return "ICC installation error"; // SCARD_E_ICC_INSTALLATION
55
+ if (ucode == 0x80100021) return "ICC create-order error"; // SCARD_E_ICC_CREATEORDER
56
+ if (ucode == 0x80100022) return "Unsupported feature"; // SCARD_E_UNSUPPORTED_FEATURE (win)
57
+ if (ucode == 0x80100023) return "Directory not found"; // SCARD_E_DIR_NOT_FOUND
58
+ if (ucode == 0x80100024) return "File not found"; // SCARD_E_FILE_NOT_FOUND
59
+ if (ucode == 0x80100025) return "No directory"; // SCARD_E_NO_DIR
60
+ if (ucode == 0x80100026) return "No file"; // SCARD_E_NO_FILE
61
+ if (ucode == 0x80100027) return "Access denied"; // SCARD_E_NO_ACCESS
62
+ if (ucode == 0x80100028) return "Too many writes"; // SCARD_E_WRITE_TOO_MANY
63
+ if (ucode == 0x80100029) return "Bad seek"; // SCARD_E_BAD_SEEK
64
+ if (ucode == 0x8010002A) return "Invalid CHV/PIN"; // SCARD_E_INVALID_CHV
65
+ if (ucode == 0x8010002B) return "Unknown resource manager"; // SCARD_E_UNKNOWN_RES_MNG
66
+ if (ucode == 0x8010002C) return "No such certificate"; // SCARD_E_NO_SUCH_CERTIFICATE
67
+ if (ucode == 0x8010002D) return "Certificate unavailable"; // SCARD_E_CERTIFICATE_UNAVAILABLE
68
+ if (ucode == 0x8010002F) return "Communication data lost"; // SCARD_E_COMM_DATA_LOST
69
+ if (ucode == 0x80100030) return "No key container"; // SCARD_E_NO_KEY_CONTAINER
70
+ if (ucode == 0x80100031) return "Server too busy"; // SCARD_E_SERVER_TOO_BUSY
71
+ if (ucode == 0x8010006A) return "Security violation"; // SCARD_W_SECURITY_VIOLATION
72
+ if (ucode == 0x8010006B) return "Wrong CHV/PIN"; // SCARD_W_WRONG_CHV
73
+ if (ucode == 0x8010006C) return "CHV/PIN blocked"; // SCARD_W_CHV_BLOCKED
74
+ if (ucode == 0x8010006D) return "End of file"; // SCARD_W_EOF
75
+ if (ucode == 0x8010006E) return "Cancelled by user"; // SCARD_W_CANCELLED_BY_USER
76
+ if (ucode == 0x8010006F) return "Card not authenticated"; // SCARD_W_CARD_NOT_AUTHENTICATED
77
+
43
78
  return "Unknown PC/SC error";
44
79
  }
45
80
 
@@ -0,0 +1,36 @@
1
+ #pragma once
2
+
3
+ #include <napi.h>
4
+ #include <string>
5
+ #include "pcsc_errors.h"
6
+ #include "addon_data.h"
7
+
8
+ // Build a JS Error for a PC/SC failure. The code is exposed unsigned
9
+ // (e.g. 0x80100069) to match the constants in lib/errors.ts; message
10
+ // defaults to the description of the code.
11
+ inline Napi::Error NewPCSCError(Napi::Env env, LONG code, const char* message = nullptr) {
12
+ std::string text = message != nullptr ? message : GetPCSCErrorString(code);
13
+ Napi::Number ucode = Napi::Number::New(env, static_cast<double>(static_cast<DWORD>(code)));
14
+
15
+ AddonData* data = env.GetInstanceData<AddonData>();
16
+ if (data != nullptr && !data->errorFactory.IsEmpty()) {
17
+ try {
18
+ Napi::Value err = data->errorFactory.Call({Napi::String::New(env, text), ucode});
19
+ if (err.IsObject()) {
20
+ return Napi::Error(env, err);
21
+ }
22
+ } catch (const Napi::Error&) {
23
+ // Factory threw - fall back to a plain coded Error
24
+ }
25
+ }
26
+
27
+ Napi::Error err = Napi::Error::New(env, text);
28
+ err.Set("code", ucode);
29
+ return err;
30
+ }
31
+
32
+ // For a handle this library already knows is unusable (disconnected card,
33
+ // closed context): coded as the SCARD_E_INVALID_HANDLE PC/SC would return
34
+ inline Napi::Error NewInvalidHandleError(Napi::Env env, const char* message) {
35
+ return NewPCSCError(env, static_cast<LONG>(SCARD_E_INVALID_HANDLE), message);
36
+ }
@@ -1,10 +1,10 @@
1
1
  #include "pcsc_reader.h"
2
2
  #include "pcsc_card.h"
3
3
  #include "pcsc_errors.h"
4
+ #include "pcsc_napi_error.h"
5
+ #include "addon_data.h"
4
6
  #include "async_workers.h"
5
7
 
6
- Napi::FunctionReference PCSCReader::constructor;
7
-
8
8
  Napi::Object PCSCReader::Init(Napi::Env env, Napi::Object exports) {
9
9
  Napi::Function func = DefineClass(env, "Reader", {
10
10
  InstanceAccessor("name", &PCSCReader::GetNameValue, nullptr),
@@ -13,19 +13,18 @@ Napi::Object PCSCReader::Init(Napi::Env env, Napi::Object exports) {
13
13
  InstanceMethod("connect", &PCSCReader::Connect),
14
14
  });
15
15
 
16
- constructor = Napi::Persistent(func);
17
- constructor.SuppressDestruct();
16
+ env.GetInstanceData<AddonData>()->readerConstructor = Napi::Persistent(func);
18
17
 
19
18
  exports.Set("Reader", func);
20
19
  return exports;
21
20
  }
22
21
 
23
- Napi::Object PCSCReader::NewInstance(Napi::Env env, SCARDCONTEXT context,
22
+ Napi::Object PCSCReader::NewInstance(Napi::Env env, ContextHandlePtr context,
24
23
  const std::string& name, DWORD state,
25
24
  const std::vector<uint8_t>& atr) {
26
- Napi::Object obj = constructor.New({});
25
+ Napi::Object obj = env.GetInstanceData<AddonData>()->readerConstructor.New({});
27
26
  PCSCReader* reader = Napi::ObjectWrap<PCSCReader>::Unwrap(obj);
28
- reader->context_ = context;
27
+ reader->context_ = std::move(context);
29
28
  reader->name_ = name;
30
29
  reader->state_ = state;
31
30
  reader->atr_ = atr;
@@ -34,7 +33,6 @@ Napi::Object PCSCReader::NewInstance(Napi::Env env, SCARDCONTEXT context,
34
33
 
35
34
  PCSCReader::PCSCReader(const Napi::CallbackInfo& info)
36
35
  : Napi::ObjectWrap<PCSCReader>(info),
37
- context_(0),
38
36
  state_(SCARD_STATE_UNAWARE) {
39
37
  // Properties set via NewInstance
40
38
  }
@@ -66,6 +64,13 @@ Napi::Value PCSCReader::GetAtrValue(const Napi::CallbackInfo& info) {
66
64
  Napi::Value PCSCReader::Connect(const Napi::CallbackInfo& info) {
67
65
  Napi::Env env = info.Env();
68
66
 
67
+ // The context may have been closed since listReaders(); connecting on
68
+ // its released handle would reach whatever PC/SC reassigned it to
69
+ if (!context_ || !context_->IsValid()) {
70
+ NewInvalidHandleError(env, "Context is not valid").ThrowAsJavaScriptException();
71
+ return env.Null();
72
+ }
73
+
69
74
  // Parse arguments: shareMode (optional), preferredProtocols (optional)
70
75
  DWORD shareMode = SCARD_SHARE_SHARED;
71
76
  DWORD preferredProtocols = SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1;
@@ -82,7 +87,8 @@ Napi::Value PCSCReader::Connect(const Napi::CallbackInfo& info) {
82
87
  Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
83
88
 
84
89
  ConnectWorker* worker = new ConnectWorker(
85
- env, context_, name_, shareMode, preferredProtocols, deferred);
90
+ env, info.This().As<Napi::Object>(), context_, name_, shareMode,
91
+ preferredProtocols, deferred);
86
92
  worker->Queue();
87
93
 
88
94
  return deferred.Promise();