iso7816 1.0.20 → 2.0.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/README.md CHANGED
@@ -1,63 +1,180 @@
1
- # Smartcard API
1
+ # ISO 7816
2
2
 
3
+ A library for building and parsing ISO 7816 APDU commands and responses.
3
4
 
4
- ## Examples
5
+ This library is card reader agnostic - it works with any transport that can send/receive byte arrays. The examples below use the [smartcard](https://www.npmjs.com/package/smartcard) package, but you can use any PC/SC library or even a custom transport.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install iso7816
11
+ ```
12
+
13
+ ## Requirements
14
+
15
+ - Node.js 18.0.0 or higher
16
+
17
+ ## Usage
18
+
19
+ ### With smartcard package
20
+
21
+ ```bash
22
+ npm install iso7816 smartcard
23
+ ```
5
24
 
6
25
  ```javascript
7
- var cardreader = require('card-reader');
8
- var iso7816 = require('iso7816');
26
+ import { Devices } from 'smartcard';
27
+ import iso7816 from 'iso7816';
9
28
 
10
- cardreader.on('device-activated', function (reader) {
11
- console.info(`Device '${reader.name}' activated`);
12
- });
29
+ const devices = new Devices();
13
30
 
14
- cardreader.on('device-deactivated', function (reader) {
15
- console.info(`Device '${reader.name}' deactivated`);
16
- });
31
+ devices.on('card-inserted', async ({ reader, card }) => {
32
+ console.log(`Card inserted into '${reader.name}'`);
17
33
 
18
- cardreader.on('card-removed', function (reader) {
19
- console.info(`Card removed from '${reader.name}' `);
20
- });
34
+ const application = iso7816(card);
21
35
 
22
- cardreader.on('command-issued', function (reader, command) {
23
- console.info(`Command '${command.toString('hex')}' issued to '${reader.name}' `);
36
+ try {
37
+ // Select PSE (Payment System Environment)
38
+ const response = await application.selectFile([
39
+ 0x31, 0x50, 0x41, 0x59, 0x2e, 0x53, 0x59, 0x53, 0x2e, 0x44, 0x44, 0x46, 0x30, 0x31,
40
+ ]);
41
+
42
+ console.log(`Response: ${response.getStatus().meaning}`);
43
+
44
+ if (response.isOk()) {
45
+ // Read a record
46
+ const record = await application.readRecord(1, 1);
47
+ console.log(`Record: ${record.toString()}`);
48
+ }
49
+ } catch (error) {
50
+ console.error('Error:', error.message);
51
+ }
24
52
  });
25
53
 
26
- cardreader.on('response-received', function (reader, response) {
27
- console.info(`Response '${response}' received from '${reader.name}' `);
54
+ devices.on('error', (error) => {
55
+ console.error(`Error: ${error.message}`);
28
56
  });
29
57
 
58
+ devices.start();
59
+ ```
60
+
61
+ ### With custom transport
62
+
63
+ ```typescript
64
+ import iso7816, { createCommandApdu, createResponseApdu } from 'iso7816';
30
65
 
31
- cardreader.on('card-inserted', function (reader, status) {
66
+ // Any object with a transmit method works
67
+ const card = {
68
+ atr: Buffer.from([0x3b, 0x00]),
69
+ async transmit(command: Buffer): Promise<Buffer> {
70
+ // Send command to your card reader and return response
71
+ return yourCardReader.send(command);
72
+ },
73
+ };
32
74
 
33
- console.info(`Card inserted into '${reader.name}', atr: '${status.atr.toString('hex')}'`);
75
+ const application = iso7816(card);
76
+ const response = await application.selectFile([0xa0, 0x00, 0x00]);
77
+ ```
34
78
 
35
- var application = iso7816(cardreader);
36
- application
37
- .selectFile([0x31, 0x50, 0x41, 0x59, 0x2E, 0x53, 0x59, 0x53, 0x2E, 0x44, 0x44, 0x46, 0x30, 0x31])
38
- .then(function (response) {
39
- console.info(`Select PSE Response: '${response}'`);
40
- }).catch(function (error) {
41
- console.error('Error:', error, error.stack);
42
- });
79
+ ### Building APDUs directly
43
80
 
81
+ ```typescript
82
+ import { createCommandApdu, createResponseApdu } from 'iso7816';
83
+
84
+ // Build a SELECT command
85
+ const command = createCommandApdu({
86
+ cla: 0x00,
87
+ ins: 0xa4,
88
+ p1: 0x04,
89
+ p2: 0x00,
90
+ data: [0xa0, 0x00, 0x00],
44
91
  });
45
92
 
93
+ console.log(command.toString()); // "00a4040003a0000000"
94
+ console.log(command.toBuffer()); // <Buffer 00 a4 04 00 03 a0 00 00 00>
46
95
 
96
+ // Parse a response
97
+ const response = createResponseApdu(Buffer.from([0x90, 0x00]));
98
+ console.log(response.isOk()); // true
99
+ console.log(response.getStatus()); // { code: '9000', meaning: 'Normal processing' }
47
100
  ```
48
101
 
102
+ ## API
103
+
104
+ ### `iso7816(card)`
105
+
106
+ Create an ISO 7816 application instance.
107
+
108
+ - `card` - Any object with `transmit(buffer: Buffer): Promise<Buffer>` method
109
+
110
+ Returns an `Iso7816` instance.
49
111
 
50
- ## Compatible Readers
112
+ ### `application.selectFile(bytes, p1?, p2?)`
51
113
 
52
- Tested on Mac OSX with the SCM SCR3500 Smart Card Reader.
53
- This library *should* work with most PC/SC readers - I'll update this page when I get to test others.
54
- If you know of any other devices that work please let me know.
55
-
114
+ Select a file on the card.
115
+
116
+ - `bytes` - Array of bytes representing the file identifier (e.g., AID)
117
+ - `p1` - Optional P1 parameter (default: `0x04`)
118
+ - `p2` - Optional P2 parameter (default: `0x00`)
119
+
120
+ ### `application.readRecord(sfi, record)`
121
+
122
+ Read a record from a file.
123
+
124
+ - `sfi` - Short File Identifier
125
+ - `record` - Record number
126
+
127
+ ### `application.getData(p1, p2)`
128
+
129
+ Get data from the card.
130
+
131
+ ### `application.getResponse(length)`
132
+
133
+ Get additional response bytes.
134
+
135
+ ### `application.issueCommand(commandApdu, maxRetries?)`
136
+
137
+ Issue a raw APDU command.
138
+
139
+ - `commandApdu` - A `CommandApdu` instance
140
+ - `maxRetries` - Maximum retries for wrong length responses (default: `3`)
141
+
142
+ ### `createCommandApdu(options)`
143
+
144
+ Create a command APDU.
145
+
146
+ ```typescript
147
+ const apdu = createCommandApdu({
148
+ cla: 0x00, // Class byte
149
+ ins: 0xa4, // Instruction byte
150
+ p1: 0x04, // Parameter 1
151
+ p2: 0x00, // Parameter 2
152
+ data: [...], // Optional command data
153
+ le: 0x00, // Optional expected response length
154
+ });
155
+
156
+ apdu.toString(); // Hex string
157
+ apdu.toBuffer(); // Node.js Buffer
158
+ apdu.toByteArray(); // number[]
159
+ apdu.setLe(0x10); // Update expected length
160
+ ```
161
+
162
+ ### `createResponseApdu(buffer)`
163
+
164
+ Parse a response APDU.
165
+
166
+ ```typescript
167
+ const response = createResponseApdu(buffer);
168
+
169
+ response.isOk(); // true if status is 9000
170
+ response.getStatusCode(); // "9000"
171
+ response.getStatus(); // { code: "9000", meaning: "Normal processing" }
172
+ response.getBuffer(); // Raw buffer
173
+ response.toString(); // Hex string
174
+ response.hasMoreBytesAvailable(); // true if 61xx status
175
+ response.isWrongLength(); // true if 6cxx status
176
+ ```
56
177
 
57
- <div align="center">
58
- <img src="docs/scr3500-collapsed.JPG" width=600 style="margin:1rem;" />
59
- </div>
178
+ ## License
60
179
 
61
- <div align="center">
62
- <img src="docs/scr3500-expanded.JPG" width=600 style="margin:1rem;" />
63
- </div>
180
+ MIT
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Options for creating a CommandApdu
3
+ */
4
+ export interface CommandApduOptions {
5
+ /** Class byte */
6
+ cla: number;
7
+ /** Instruction byte */
8
+ ins: number;
9
+ /** Parameter 1 */
10
+ p1: number;
11
+ /** Parameter 2 */
12
+ p2: number;
13
+ /** Command data */
14
+ data?: number[];
15
+ /** Expected response length */
16
+ le?: number;
17
+ }
18
+ /**
19
+ * APDU Command class for building ISO 7816 command APDUs
20
+ */
21
+ export declare class CommandApdu {
22
+ private _bytes;
23
+ constructor(options: CommandApduOptions);
24
+ /**
25
+ * Get the bytes array (read-only copy)
26
+ */
27
+ get bytes(): number[];
28
+ /**
29
+ * Convert to hex string representation
30
+ */
31
+ toString(): string;
32
+ /**
33
+ * Get bytes as array
34
+ */
35
+ toByteArray(): number[];
36
+ /**
37
+ * Convert to Node.js Buffer
38
+ */
39
+ toBuffer(): Buffer;
40
+ /**
41
+ * Update expected response length (Le)
42
+ */
43
+ setLe(le: number): void;
44
+ }
45
+ /**
46
+ * Factory function to create a CommandApdu
47
+ */
48
+ export default function createCommandApdu(options: CommandApduOptions): CommandApdu;
49
+ //# sourceMappingURL=command-apdu.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-apdu.d.ts","sourceRoot":"","sources":["../src/command-apdu.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAC/B,iBAAiB;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,uBAAuB;IACvB,GAAG,EAAE,MAAM,CAAC;IACZ,kBAAkB;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,kBAAkB;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,mBAAmB;IACnB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,+BAA+B;IAC/B,EAAE,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,qBAAa,WAAW;IACpB,OAAO,CAAC,MAAM,CAAW;gBAEb,OAAO,EAAE,kBAAkB;IAavC;;OAEG;IACH,IAAI,KAAK,IAAI,MAAM,EAAE,CAEpB;IAED;;OAEG;IACH,QAAQ,IAAI,MAAM;IAIlB;;OAEG;IACH,WAAW,IAAI,MAAM,EAAE;IAIvB;;OAEG;IACH,QAAQ,IAAI,MAAM;IAIlB;;OAEG;IACH,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;CAI1B;AAED;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,OAAO,EAAE,kBAAkB,GAAG,WAAW,CAElF"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * APDU Command class for building ISO 7816 command APDUs
3
+ */
4
+ export class CommandApdu {
5
+ _bytes;
6
+ constructor(options) {
7
+ const { cla, ins, p1, p2, data, le = 0 } = options;
8
+ this._bytes = [cla, ins, p1, p2];
9
+ if (data) {
10
+ this._bytes.push(data.length);
11
+ this._bytes = this._bytes.concat(data);
12
+ }
13
+ this._bytes.push(le);
14
+ }
15
+ /**
16
+ * Get the bytes array (read-only copy)
17
+ */
18
+ get bytes() {
19
+ return [...this._bytes];
20
+ }
21
+ /**
22
+ * Convert to hex string representation
23
+ */
24
+ toString() {
25
+ return Buffer.from(this._bytes).toString('hex');
26
+ }
27
+ /**
28
+ * Get bytes as array
29
+ */
30
+ toByteArray() {
31
+ return this._bytes;
32
+ }
33
+ /**
34
+ * Convert to Node.js Buffer
35
+ */
36
+ toBuffer() {
37
+ return Buffer.from(this._bytes);
38
+ }
39
+ /**
40
+ * Update expected response length (Le)
41
+ */
42
+ setLe(le) {
43
+ this._bytes.pop();
44
+ this._bytes.push(le);
45
+ }
46
+ }
47
+ /**
48
+ * Factory function to create a CommandApdu
49
+ */
50
+ export default function createCommandApdu(options) {
51
+ return new CommandApdu(options);
52
+ }
53
+ //# sourceMappingURL=command-apdu.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-apdu.js","sourceRoot":"","sources":["../src/command-apdu.ts"],"names":[],"mappings":"AAkBA;;GAEG;AACH,MAAM,OAAO,WAAW;IACZ,MAAM,CAAW;IAEzB,YAAY,OAA2B;QACnC,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE,GAAG,CAAC,EAAE,GAAG,OAAO,CAAC;QAEnD,IAAI,CAAC,MAAM,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;QAEjC,IAAI,IAAI,EAAE,CAAC;YACP,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC3C,CAAC;QAED,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACzB,CAAC;IAED;;OAEG;IACH,IAAI,KAAK;QACL,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5B,CAAC;IAED;;OAEG;IACH,QAAQ;QACJ,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC;IAED;;OAEG;IACH,WAAW;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,QAAQ;QACJ,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,EAAU;QACZ,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;QAClB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACzB,CAAC;CACJ;AAED;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,OAA2B;IACjE,OAAO,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * ISO 7816 Smartcard Communication Library
3
+ */
4
+ export { default, Iso7816, Instructions, Card } from './iso7816-application.js';
5
+ export { CommandApdu, CommandApduOptions, default as createCommandApdu } from './command-apdu.js';
6
+ export { ResponseApdu, Status, default as createResponseApdu } from './response-apdu.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * ISO 7816 Smartcard Communication Library
3
+ */
4
+ export { default, Iso7816, Instructions } from './iso7816-application.js';
5
+ export { CommandApdu, default as createCommandApdu } from './command-apdu.js';
6
+ export { ResponseApdu, default as createResponseApdu } from './response-apdu.js';
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAQ,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,WAAW,EAAsB,OAAO,IAAI,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAClG,OAAO,EAAE,YAAY,EAAU,OAAO,IAAI,kBAAkB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,90 @@
1
+ import { CommandApdu } from './command-apdu.js';
2
+ import { ResponseApdu } from './response-apdu.js';
3
+ /**
4
+ * ISO 7816 instruction codes
5
+ */
6
+ export declare const Instructions: {
7
+ readonly APPEND_RECORD: 226;
8
+ readonly ENVELOPE: 194;
9
+ readonly ERASE_BINARY: 14;
10
+ readonly EXTERNAL_AUTHENTICATE: 130;
11
+ readonly GET_CHALLENGE: 132;
12
+ readonly GET_DATA: 202;
13
+ readonly GET_RESPONSE: 192;
14
+ readonly INTERNAL_AUTHENTICATE: 136;
15
+ readonly MANAGE_CHANNEL: 112;
16
+ readonly PUT_DATA: 218;
17
+ readonly READ_BINARY: 176;
18
+ readonly READ_RECORD: 178;
19
+ readonly SELECT_FILE: 164;
20
+ readonly UPDATE_BINARY: 214;
21
+ readonly UPDATE_RECORD: 220;
22
+ readonly VERIFY: 32;
23
+ readonly WRITE_BINARY: 208;
24
+ readonly WRITE_RECORD: 210;
25
+ };
26
+ /**
27
+ * Card interface for any transport that can send/receive APDUs
28
+ */
29
+ export interface Card {
30
+ /** Card ATR (Answer To Reset) */
31
+ atr: Buffer;
32
+ /** Transmit APDU command to card */
33
+ transmit(data: Buffer | number[]): Promise<Buffer>;
34
+ }
35
+ /**
36
+ * ISO 7816 Application class for APDU communication
37
+ */
38
+ export declare class Iso7816 {
39
+ private readonly _card;
40
+ constructor(card: Card);
41
+ /**
42
+ * Get the underlying card
43
+ */
44
+ get card(): Card;
45
+ /**
46
+ * Issue a raw APDU command
47
+ * @param commandApdu The command to send
48
+ * @param maxRetries Maximum number of retries for wrong length responses (default: 3)
49
+ * @returns Promise resolving to the response
50
+ * @throws Error if maximum retries exceeded
51
+ */
52
+ issueCommand(commandApdu: CommandApdu, maxRetries?: number): Promise<ResponseApdu>;
53
+ /**
54
+ * Select a file on the smartcard
55
+ * @param bytes File identifier bytes (e.g., AID)
56
+ * @param p1 P1 parameter (default: 0x04)
57
+ * @param p2 P2 parameter (default: 0x00)
58
+ * @returns Promise resolving to the response
59
+ */
60
+ selectFile(bytes: number[], p1?: number, p2?: number): Promise<ResponseApdu>;
61
+ /**
62
+ * Get additional response bytes
63
+ * @param length Number of bytes to retrieve
64
+ * @returns Promise resolving to the response
65
+ */
66
+ getResponse(length: number): Promise<ResponseApdu>;
67
+ /**
68
+ * Read a record from a file
69
+ * @param sfi Short File Identifier
70
+ * @param record Record number
71
+ * @returns Promise resolving to the response
72
+ */
73
+ readRecord(sfi: number, record: number): Promise<ResponseApdu>;
74
+ /**
75
+ * Get data from the card
76
+ * @param p1 P1 parameter
77
+ * @param p2 P2 parameter
78
+ * @returns Promise resolving to the response
79
+ */
80
+ getData(p1: number, p2: number): Promise<ResponseApdu>;
81
+ }
82
+ /**
83
+ * Factory function to create an Iso7816 application
84
+ * @param card A card object from the smartcard package
85
+ * @returns An Iso7816 application instance
86
+ */
87
+ export default function createIso7816(card: Card): Iso7816;
88
+ export { CommandApdu, CommandApduOptions } from './command-apdu.js';
89
+ export { ResponseApdu, Status } from './response-apdu.js';
90
+ //# sourceMappingURL=iso7816-application.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iso7816-application.d.ts","sourceRoot":"","sources":["../src/iso7816-application.ts"],"names":[],"mappings":"AAAA,OAA0B,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAA2B,EAAE,YAAY,EAAE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CommandApdu from './command-apdu.js';
2
+ import createResponseApdu from './response-apdu.js';
3
+ /**
4
+ * ISO 7816 instruction codes
5
+ */
6
+ export const Instructions = {
7
+ APPEND_RECORD: 0xe2,
8
+ ENVELOPE: 0xc2,
9
+ ERASE_BINARY: 0x0e,
10
+ EXTERNAL_AUTHENTICATE: 0x82,
11
+ GET_CHALLENGE: 0x84,
12
+ GET_DATA: 0xca,
13
+ GET_RESPONSE: 0xc0,
14
+ INTERNAL_AUTHENTICATE: 0x88,
15
+ MANAGE_CHANNEL: 0x70,
16
+ PUT_DATA: 0xda,
17
+ READ_BINARY: 0xb0,
18
+ READ_RECORD: 0xb2,
19
+ SELECT_FILE: 0xa4,
20
+ UPDATE_BINARY: 0xd6,
21
+ UPDATE_RECORD: 0xdc,
22
+ VERIFY: 0x20,
23
+ WRITE_BINARY: 0xd0,
24
+ WRITE_RECORD: 0xd2,
25
+ };
26
+ /**
27
+ * ISO 7816 Application class for APDU communication
28
+ */
29
+ export class Iso7816 {
30
+ _card;
31
+ constructor(card) {
32
+ this._card = card;
33
+ }
34
+ /**
35
+ * Get the underlying card
36
+ */
37
+ get card() {
38
+ return this._card;
39
+ }
40
+ /**
41
+ * Issue a raw APDU command
42
+ * @param commandApdu The command to send
43
+ * @param maxRetries Maximum number of retries for wrong length responses (default: 3)
44
+ * @returns Promise resolving to the response
45
+ * @throws Error if maximum retries exceeded
46
+ */
47
+ async issueCommand(commandApdu, maxRetries = 3) {
48
+ let retries = 0;
49
+ const execute = async () => {
50
+ const resp = await this._card.transmit(commandApdu.toBuffer());
51
+ const response = createResponseApdu(resp);
52
+ if (response.hasMoreBytesAvailable()) {
53
+ return this.getResponse(response.numberOfBytesAvailable());
54
+ }
55
+ else if (response.isWrongLength()) {
56
+ if (retries >= maxRetries) {
57
+ throw new Error(`Maximum retries (${maxRetries}) exceeded for wrong length response`);
58
+ }
59
+ retries++;
60
+ commandApdu.setLe(response.correctLength());
61
+ return execute();
62
+ }
63
+ return response;
64
+ };
65
+ return execute();
66
+ }
67
+ /**
68
+ * Select a file on the smartcard
69
+ * @param bytes File identifier bytes (e.g., AID)
70
+ * @param p1 P1 parameter (default: 0x04)
71
+ * @param p2 P2 parameter (default: 0x00)
72
+ * @returns Promise resolving to the response
73
+ */
74
+ selectFile(bytes, p1 = 0x04, p2 = 0x00) {
75
+ return this.issueCommand(createCommandApdu({
76
+ cla: 0x00,
77
+ ins: Instructions.SELECT_FILE,
78
+ p1,
79
+ p2,
80
+ data: bytes,
81
+ }));
82
+ }
83
+ /**
84
+ * Get additional response bytes
85
+ * @param length Number of bytes to retrieve
86
+ * @returns Promise resolving to the response
87
+ */
88
+ getResponse(length) {
89
+ return this.issueCommand(createCommandApdu({
90
+ cla: 0x00,
91
+ ins: Instructions.GET_RESPONSE,
92
+ p1: 0x00,
93
+ p2: 0x00,
94
+ le: length,
95
+ }));
96
+ }
97
+ /**
98
+ * Read a record from a file
99
+ * @param sfi Short File Identifier
100
+ * @param record Record number
101
+ * @returns Promise resolving to the response
102
+ */
103
+ readRecord(sfi, record) {
104
+ return this.issueCommand(createCommandApdu({
105
+ cla: 0x00,
106
+ ins: Instructions.READ_RECORD,
107
+ p1: record,
108
+ p2: (sfi << 3) + 4,
109
+ le: 0,
110
+ }));
111
+ }
112
+ /**
113
+ * Get data from the card
114
+ * @param p1 P1 parameter
115
+ * @param p2 P2 parameter
116
+ * @returns Promise resolving to the response
117
+ */
118
+ getData(p1, p2) {
119
+ return this.issueCommand(createCommandApdu({
120
+ cla: 0x00,
121
+ ins: Instructions.GET_DATA,
122
+ p1,
123
+ p2,
124
+ le: 0,
125
+ }));
126
+ }
127
+ }
128
+ /**
129
+ * Factory function to create an Iso7816 application
130
+ * @param card A card object from the smartcard package
131
+ * @returns An Iso7816 application instance
132
+ */
133
+ export default function createIso7816(card) {
134
+ return new Iso7816(card);
135
+ }
136
+ // Re-export types for convenience
137
+ export { CommandApdu } from './command-apdu.js';
138
+ export { ResponseApdu } from './response-apdu.js';
139
+ //# sourceMappingURL=iso7816-application.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iso7816-application.js","sourceRoot":"","sources":["../src/iso7816-application.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAkC,MAAM,mBAAmB,CAAC;AACnE,OAAO,kBAAoC,MAAM,oBAAoB,CAAC;AAEtE;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IACxB,aAAa,EAAE,IAAI;IACnB,QAAQ,EAAE,IAAI;IACd,YAAY,EAAE,IAAI;IAClB,qBAAqB,EAAE,IAAI;IAC3B,aAAa,EAAE,IAAI;IACnB,QAAQ,EAAE,IAAI;IACd,YAAY,EAAE,IAAI;IAClB,qBAAqB,EAAE,IAAI;IAC3B,cAAc,EAAE,IAAI;IACpB,QAAQ,EAAE,IAAI;IACd,WAAW,EAAE,IAAI;IACjB,WAAW,EAAE,IAAI;IACjB,WAAW,EAAE,IAAI;IACjB,aAAa,EAAE,IAAI;IACnB,aAAa,EAAE,IAAI;IACnB,MAAM,EAAE,IAAI;IACZ,YAAY,EAAE,IAAI;IAClB,YAAY,EAAE,IAAI;CACZ,CAAC;AAYX;;GAEG;AACH,MAAM,OAAO,OAAO;IACC,KAAK,CAAO;IAE7B,YAAY,IAAU;QAClB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACtB,CAAC;IAED;;OAEG;IACH,IAAI,IAAI;QACJ,OAAO,IAAI,CAAC,KAAK,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,YAAY,CAAC,WAAwB,EAAE,aAAqB,CAAC;QAC/D,IAAI,OAAO,GAAG,CAAC,CAAC;QAEhB,MAAM,OAAO,GAAG,KAAK,IAA2B,EAAE;YAC9C,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC;YAC/D,MAAM,QAAQ,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;YAE1C,IAAI,Q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E,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC;YAClB,EAAE,EAAE,CAAC;SACR,CAAC,CACL,CAAC;IACN,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,EAAU,EAAE,EAAU;QAC1B,OAAO,IAAI,CAAC,YAAY,CACpB,iBAAiB,CAAC;YACd,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,YAAY,CAAC,QAAQ;YAC1B,EAAE;YACF,EAAE;YACF,EAAE,EAAE,CAAC;SACR,CAAC,CACL,CAAC;IACN,CAAC;CACJ;AAED;;;;GAIG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,IAAU;IAC5C,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC;AAED,kCAAkC;AAClC,OAAO,EAAE,WAAW,EAAsB,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAU,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Status information from a response
3
+ */
4
+ export interface Status {
5
+ /** 4-character hex status code (e.g., "9000") */
6
+ code: string;
7
+ /** Human-readable meaning of the status */
8
+ meaning: string;
9
+ }
10
+ /**
11
+ * APDU Response class for parsing ISO 7816 response APDUs
12
+ */
13
+ export declare class ResponseApdu {
14
+ private readonly _buffer;
15
+ private readonly _data;
16
+ constructor(buffer: Buffer);
17
+ /**
18
+ * Get SW1 (first status byte) as 2-character hex string
19
+ */
20
+ private getSW1;
21
+ /**
22
+ * Get SW2 (second status byte) as 2-character hex string
23
+ */
24
+ private getSW2;
25
+ /**
26
+ * Get status code and meaning
27
+ */
28
+ getStatus(): Status;
29
+ /**
30
+ * Get 4-character hex status code (SW1 + SW2)
31
+ */
32
+ getStatusCode(): string;
33
+ /**
34
+ * Check if status is 9000 (success)
35
+ */
36
+ isOk(): boolean;
37
+ /**
38
+ * Get the raw buffer
39
+ */
40
+ getBuffer(): Buffer;
41
+ /**
42
+ * Check if more bytes are available (61xx status)
43
+ */
44
+ hasMoreBytesAvailable(): boolean;
45
+ /**
46
+ * Get number of additional bytes available (from 61xx status)
47
+ */
48
+ numberOfBytesAvailable(): number;
49
+ /**
50
+ * Check if wrong length was specified (6cxx status)
51
+ */
52
+ isWrongLength(): boolean;
53
+ /**
54
+ * Get the correct length from 6cxx response
55
+ */
56
+ correctLength(): number;
57
+ /**
58
+ * Convert to hex string
59
+ */
60
+ toString(): string;
61
+ }
62
+ /**
63
+ * Factory function to create a ResponseApdu
64
+ */
65
+ export default function createResponseApdu(buffer: Buffer): ResponseApdu;
66
+ //# sourceMappingURL=response-apdu.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-apdu.d.ts","sourceRoot":"","sources":["../src/response-apdu.ts"],"names":[],"mappings":"AAsDA;;GAEG;AACH,MAAM,WAAW,MAAM;IACnB,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAC;IACb,2CAA2C;IAC3C,OAAO,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,qBAAa,YAAY;IACrB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAQ1B;;OAEG;IACH,OAAO,CAAC,MAAM;IAId;;OAEG;IACH,OAAO,CAAC,MAAM;IAId;;OAEG;IACH,SAAS,IAAI,MAAM;IAYnB;;OAEG;IACH,aAAa,IAAI,MAAM;IAIvB;;OAEG;IACH,IAAI,IAAI,OAAO;IAIf;;OAEG;IACH,SAAS,IAAI,MAAM;IAInB;;OAEG;IACH,qBAAqB,IAAI,OAAO;IAIhC;;OAEG;IACH,sBAAsB,IAAI,MAAM;IAIhC;;OAEG;IACH,aAAa,IAAI,OAAO;IAIxB;;OAEG;IACH,aAAa,IAAI,MAAM;IAIvB;;OAEG;IACH,QAAQ,IAAI,MAAM;CAGrB;AAED;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,CAEvE"}
@@ -0,0 +1,146 @@
1
+ /**
2
+ * ISO 7816 status code mappings (ordered from most specific to least specific)
3
+ */
4
+ const statusCodes = [
5
+ // Specific status codes first
6
+ [/^9000$/, 'Normal processing'],
7
+ [/^6200$/, 'No information given'],
8
+ [/^6281$/, 'Part of return data may be corrupted'],
9
+ [/^6282$/, 'End of file/record reached before reading Le bytes'],
10
+ [/^6283$/, 'Selected file invalidated'],
11
+ [/^6284$/, 'FCI not formatted correctly'],
12
+ [/^6285$/, 'File control info not in required format'],
13
+ [/^6286$/, 'Unsuccessful writing'],
14
+ [/^6300$/, 'Authentication failed'],
15
+ [/^6381$/, 'Last write filled up file'],
16
+ [/^6382$/, 'Execution successful after retry'],
17
+ [/^6500$/, 'No information given'],
18
+ [/^6581$/, 'Memory failure'],
19
+ [/^6700$/, 'Wrong length'],
20
+ [/^6800$/, 'No information given'],
21
+ [/^6881$/, 'Logical channel not supported'],
22
+ [/^6882$/, 'Secure messaging not supported'],
23
+ [/^6981$/, 'Command incompatible with file structure'],
24
+ [/^6982$/, 'Security status not satisfied'],
25
+ [/^6983$/, 'Authentication method blocked'],
26
+ [/^6984$/, 'Referenced data invalidated'],
27
+ [/^6985$/, 'Conditions of use not satisfied'],
28
+ [/^6986$/, 'Command not allowed (no current EF)'],
29
+ [/^6a80$/, 'Incorrect parameters in command data field'],
30
+ [/^6a81$/, 'Function not supported'],
31
+ [/^6a82$/, 'File not found'],
32
+ [/^6a83$/, 'Record not found'],
33
+ [/^6a84$/, 'Not enough memory space'],
34
+ [/^6a85$/, 'Lc inconsistent with TLV structure'],
35
+ [/^6a86$/, 'Incorrect parameters P1-P2'],
36
+ [/^6a87$/, 'Lc inconsistent with P1-P2'],
37
+ [/^6a88$/, 'Referenced data not found'],
38
+ // Generic status codes (wildcards) last
39
+ [/^61(.{2})$/, 'More data available'],
40
+ [/^62(.{2})$/, 'Warning processing'],
41
+ [/^63(.{2})$/, 'Warning processing'],
42
+ [/^64(.{2})$/, 'Execution error'],
43
+ [/^65(.{2})$/, 'Execution error'],
44
+ [/^66(.{2})$/, 'Reserved for future use'],
45
+ [/^68(.{2})$/, 'Functions in CLA not supported'],
46
+ [/^69(.{2})$/, 'Command not allowed'],
47
+ [/^6a(.{2})$/, 'Wrong parameters P1-P2'],
48
+ [/^6b(.{2})$/, 'Wrong parameters'],
49
+ [/^6c(.{2})$/, 'Wrong length Le'],
50
+ [/^6d(.{2})$/, 'Instruction not supported'],
51
+ [/^6e(.{2})$/, 'Class not supported'],
52
+ [/^6f(.{2})$/, 'No precise diagnosis'],
53
+ ];
54
+ /**
55
+ * APDU Response class for parsing ISO 7816 response APDUs
56
+ */
57
+ export class ResponseApdu {
58
+ _buffer;
59
+ _data;
60
+ constructor(buffer) {
61
+ if (buffer.length < 2) {
62
+ throw new Error('Response APDU must contain at least 2 bytes (SW1 and SW2)');
63
+ }
64
+ this._buffer = buffer;
65
+ this._data = buffer.toString('hex');
66
+ }
67
+ /**
68
+ * Get SW1 (first status byte) as 2-character hex string
69
+ */
70
+ getSW1() {
71
+ return this._data.slice(-4, -2);
72
+ }
73
+ /**
74
+ * Get SW2 (second status byte) as 2-character hex string
75
+ */
76
+ getSW2() {
77
+ return this._data.slice(-2);
78
+ }
79
+ /**
80
+ * Get status code and meaning
81
+ */
82
+ getStatus() {
83
+ const statusCode = this.getStatusCode();
84
+ for (const [pattern, meaning] of statusCodes) {
85
+ if (pattern.test(statusCode)) {
86
+ return { code: statusCode, meaning };
87
+ }
88
+ }
89
+ return { code: statusCode, meaning: 'Unknown' };
90
+ }
91
+ /**
92
+ * Get 4-character hex status code (SW1 + SW2)
93
+ */
94
+ getStatusCode() {
95
+ return this._data.slice(-4);
96
+ }
97
+ /**
98
+ * Check if status is 9000 (success)
99
+ */
100
+ isOk() {
101
+ return this.getStatusCode() === '9000';
102
+ }
103
+ /**
104
+ * Get the raw buffer
105
+ */
106
+ getBuffer() {
107
+ return this._buffer;
108
+ }
109
+ /**
110
+ * Check if more bytes are available (61xx status)
111
+ */
112
+ hasMoreBytesAvailable() {
113
+ return this.getSW1() === '61';
114
+ }
115
+ /**
116
+ * Get number of additional bytes available (from 61xx status)
117
+ */
118
+ numberOfBytesAvailable() {
119
+ return parseInt(this.getSW2(), 16);
120
+ }
121
+ /**
122
+ * Check if wrong length was specified (6cxx status)
123
+ */
124
+ isWrongLength() {
125
+ return this.getSW1() === '6c';
126
+ }
127
+ /**
128
+ * Get the correct length from 6cxx response
129
+ */
130
+ correctLength() {
131
+ return parseInt(this.getSW2(), 16);
132
+ }
133
+ /**
134
+ * Convert to hex string
135
+ */
136
+ toString() {
137
+ return this._data;
138
+ }
139
+ }
140
+ /**
141
+ * Factory function to create a ResponseApdu
142
+ */
143
+ export default function createResponseApdu(buffer) {
144
+ return new ResponseApdu(buffer);
145
+ }
146
+ //# sourceMappingURL=response-apdu.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-apdu.js","sourceRoot":"","sources":["../src/response-apdu.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,GAA4B;IACzC,8BAA8B;IAC9B,CAAC,QAAQ,EAAE,mBAAmB,CAAC;IAC/B,CAAC,QAAQ,EAAE,sBAAsB,CAAC;IAClC,CAAC,QAAQ,EAAE,sCAAsC,CAAC;IAClD,CAAC,QAAQ,EAAE,oDAAoD,CAAC;IAChE,CAAC,QAAQ,EAAE,2BAA2B,CAAC;IACvC,CAAC,QAAQ,EAAE,6BAA6B,CAAC;IACzC,CAAC,QAAQ,EAAE,0CAA0C,CAAC;IACtD,CAAC,QAAQ,EAAE,sBAAsB,CAAC;IAClC,CAAC,QAAQ,EAAE,uBAAuB,CAAC;IACnC,CAAC,QAAQ,EAAE,2BAA2B,CAAC;IACvC,CAAC,QAAQ,EAAE,kCAAkC,CAAC;IAC9C,CAAC,QAAQ,EAAE,sBAAsB,CAAC;IAClC,CAAC,QAAQ,EAAE,gBAAgB,CAAC;IAC5B,CAAC,QAAQ,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AAS;QACL,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED;;OAEG;IACH,qBAAqB;QACjB,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC;IAClC,CAAC;IAED;;OAEG;IACH,sBAAsB;QAClB,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;IACvC,CAAC;IAED;;OAEG;IACH,aAAa;QACT,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC;IAClC,CAAC;IAED;;OAEG;IACH,aAAa;QACT,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;IACvC,CAAC;IAED;;OAEG;IACH,QAAQ;QACJ,OAAO,IAAI,CAAC,KAAK,CAAC;IACtB,CAAC;CACJ;AAED;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,kBAAkB,CAAC,MAAc;IACrD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC"}
package/package.json CHANGED
@@ -1,13 +1,35 @@
1
1
  {
2
2
  "name": "iso7816",
3
- "version": "1.0.20",
4
- "description": "",
5
- "main": "lib/iso7816-application.js",
3
+ "version": "2.0.0",
4
+ "description": "ISO 7816 APDU command and response handling library",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
6
17
  "scripts": {
7
- "compile": "babel -d lib/ src/",
8
- "compile:watch": "babel -w -d lib/ src/",
9
- "prepublish": "npm run compile",
10
- "release:patch": "npm run compile && npm version patch && git push && npm publish"
18
+ "build": "tsc",
19
+ "clean": "rm -rf dist",
20
+ "prebuild": "npm run clean",
21
+ "test": "vitest run",
22
+ "test:watch": "vitest",
23
+ "test:coverage": "vitest run --coverage",
24
+ "typecheck": "tsc --noEmit",
25
+ "lint": "eslint src/",
26
+ "format": "prettier --write src/",
27
+ "format:check": "prettier --check src/",
28
+ "prepublishOnly": "npm run build",
29
+ "release:patch": "npm run lint && npm run typecheck && npm test && npm run build && npm version patch && git push --follow-tags && npm publish"
30
+ },
31
+ "engines": {
32
+ "node": ">=20.0.0"
11
33
  },
12
34
  "author": "tomkp <tom@tomkp.com>",
13
35
  "keywords": [
@@ -18,7 +40,8 @@
18
40
  "iso-7816",
19
41
  "chip-and-pin",
20
42
  "emv",
21
- "es6"
43
+ "esm",
44
+ "typescript"
22
45
  ],
23
46
  "license": "MIT",
24
47
  "bugs": {
@@ -29,13 +52,15 @@
29
52
  "url": "https://github.com/tomkp/iso7816.git"
30
53
  },
31
54
  "homepage": "https://github.com/tomkp/iso7816",
32
- "dependencies": {
33
- "apdu": "^0.0.3",
34
- "card-reader": "^1.0.3",
35
- "hexify": "^1.0.1"
36
- },
37
55
  "devDependencies": {
38
- "babel-cli": "^6.6.5",
39
- "babel-preset-es2015": "^6.6.0"
56
+ "@eslint/js": "^9.39.2",
57
+ "@types/node": "^22.0.0",
58
+ "@vitest/coverage-v8": "^4.0.16",
59
+ "eslint": "^9.39.2",
60
+ "eslint-config-prettier": "^10.1.8",
61
+ "prettier": "^3.7.4",
62
+ "typescript": "^5.7.0",
63
+ "typescript-eslint": "^8.50.1",
64
+ "vitest": "^4.0.16"
40
65
  }
41
66
  }
package/.babelrc DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "presets": ["es2015"]
3
- }
package/.npmignore DELETED
@@ -1 +0,0 @@
1
- src/
@@ -1,45 +0,0 @@
1
- var devices = require('card-reader');
2
- var iso7816 = require('../lib/iso7816-application');
3
-
4
-
5
- devices.on('device-activated', function (event) {
6
- console.log(`Device '${event.reader.name}' activated, devices: ${devices.listDevices()}`);
7
- });
8
-
9
- devices.on('device-deactivated', function (event) {
10
- console.log(`Device '${event.reader.name}' deactivated, devices: ${devices.listDevices()}`);
11
- });
12
-
13
- devices.on('card-removed', function (event) {
14
- console.log(`Card removed from '${event.reader.name}' `);
15
- });
16
-
17
- devices.on('command-issued', function (event) {
18
- console.log(`Command '${event.command}' issued to '${event.reader.name}' `);
19
- });
20
-
21
- devices.on('response-received', function (event) {
22
- console.log(`Response '${event.response}' received from '${event.reader.name}' in response to '${event.command}'`);
23
- });
24
-
25
- devices.on('error', function (event) {
26
- console.log(`Error '${event.error}' received`);
27
- });
28
-
29
- devices.on('card-inserted', function (event) {
30
-
31
- console.log(`List devices: ${devices.listDevices()}`);
32
-
33
- var reader = event.reader;
34
- console.log(`Card inserted into '${reader.name}', atr: '${event.status.atr.toString('hex')}'`);
35
-
36
- var application = iso7816(devices, reader);
37
- application
38
- .selectFile([0x31, 0x50, 0x41, 0x59, 0x2E, 0x53, 0x59, 0x53, 0x2E, 0x44, 0x44, 0x46, 0x30, 0x31])
39
- .then(function (response) {
40
- console.info(`Select PSE Response: '${response}'`);
41
- }).catch(function (error) {
42
- console.error('Error:', error, error.stack);
43
- });
44
-
45
- });
Binary file
Binary file
@@ -1,86 +0,0 @@
1
- 'use strict';
2
-
3
- var _hexify = require("hexify");
4
-
5
- var _hexify2 = _interopRequireDefault(_hexify);
6
-
7
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
8
-
9
- function CommandApdu(obj) {
10
-
11
- var size = obj.size;
12
- var cla = obj.cla;
13
- var ins = obj.ins;
14
- var p1 = obj.p1;
15
- var p2 = obj.p2;
16
- var data = obj.data;
17
- var le = obj.le || 0;
18
- var lc = void 0;
19
-
20
- // case 1
21
- if (!size && !data && !le) {
22
- //le = -1;
23
- //console.info('case 1');
24
- size = 4;
25
- }
26
- // case 2
27
- else if (!size && !data) {
28
- //console.info('case 2');
29
- size = 4 + 2;
30
- }
31
-
32
- // case 3
33
- else if (!size && !le) {
34
- //console.info('case 3');
35
- size = data.length + 5 + 4;
36
- //le = -1;
37
- }
38
-
39
- // case 4
40
- else if (!size) {
41
- //console.info('case 4');
42
- size = data.length + 5 + 4;
43
- }
44
-
45
- // set data
46
- if (data) {
47
- lc = data.length;
48
- } else {
49
- //lc = 0;
50
- }
51
-
52
- this.bytes = [];
53
- this.bytes.push(cla);
54
- this.bytes.push(ins);
55
- this.bytes.push(p1);
56
- this.bytes.push(p2);
57
-
58
- if (data) {
59
- this.bytes.push(lc);
60
- this.bytes = this.bytes.concat(data);
61
- }
62
- this.bytes.push(le);
63
- }
64
-
65
- CommandApdu.prototype.toString = function () {
66
- return _hexify2.default.toHexString(bytes);
67
- };
68
-
69
- CommandApdu.prototype.toByteArray = function () {
70
- return this.bytes;
71
- };
72
-
73
- CommandApdu.prototype.toBuffer = function () {
74
- return new Buffer(this.bytes);
75
- };
76
-
77
- CommandApdu.prototype.setLe = function (le) {
78
- this.bytes.pop();
79
- this.bytes.push(le);
80
- };
81
-
82
- function create(obj) {
83
- return new CommandApdu(obj);
84
- }
85
-
86
- module.exports = create;
@@ -1,96 +0,0 @@
1
- 'use strict';
2
-
3
- var _commandApdu = require('./command-apdu');
4
-
5
- var _commandApdu2 = _interopRequireDefault(_commandApdu);
6
-
7
- var _responseApdu = require('./response-apdu');
8
-
9
- var _responseApdu2 = _interopRequireDefault(_responseApdu);
10
-
11
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
-
13
- var ins = {
14
- APPEND_RECORD: 0xE2,
15
- ENVELOPE: 0xC2,
16
- ERASE_BINARY: 0x0E,
17
- EXTERNAL_AUTHENTICATE: 0x82,
18
- GET_CHALLENGE: 0x84,
19
- GET_DATA: 0xCA,
20
- GET_RESPONSE: 0xC0,
21
- INTERNAL_AUTHENTICATE: 0x88,
22
- MANAGE_CHANNEL: 0x70,
23
- PUT_DATA: 0xDA,
24
- READ_BINARY: 0xB0,
25
- READ_RECORD: 0xB2,
26
- SELECT_FILE: 0xA4,
27
- UPDATE_BINARY: 0xD6,
28
- UPDATE_RECORD: 0xDC,
29
- VERIFY: 0x20,
30
- WRITE_BINARY: 0xD0,
31
- WRITE_RECORD: 0xD2
32
- };
33
-
34
- function Iso7816(devices, cardReader) {
35
- this.devices = devices;
36
- this.cardReader = cardReader;
37
- }
38
-
39
- Iso7816.prototype.issueCommand = function (commandApdu) {
40
- var _this = this;
41
-
42
- //console.log(`Iso7816.issueCommand '${commandApdu}' `);
43
- return this.devices.issueCommand(this.cardReader, commandApdu.toBuffer()).then(function (resp) {
44
- var response = (0, _responseApdu2.default)(resp);
45
- //console.log(`status code '${response.statusCode()}'`);
46
- if (response.hasMoreBytesAvailable()) {
47
- //console.log(`has '${response.numberOfBytesAvailable()}' more bytes available`);
48
- return _this.getResponse(response.numberOfBytesAvailable());
49
- } else if (response.isWrongLength()) {
50
- //console.log(`'le' should be '${response.correctLength()}' bytes`);
51
- commandApdu.setLe(response.correctLength());
52
- return _this.issueCommand(commandApdu);
53
- }
54
- //console.log(`return response '${response}' `);
55
- return response;
56
- });
57
- };
58
-
59
- Iso7816.prototype.selectFile = function (bytes, p1, p2) {
60
- //console.log(`Iso7816.selectFile, file='${bytes}'`);
61
- return this.issueCommand((0, _commandApdu2.default)({
62
- cla: 0x00,
63
- ins: ins.SELECT_FILE,
64
- p1: p1 || 0x04,
65
- p2: p2 || 0x00,
66
- data: bytes
67
- }));
68
- };
69
-
70
- Iso7816.prototype.getResponse = function (length) {
71
- //console.log(`Iso7816.getResponse, length='${length}'`);
72
- return this.issueCommand((0, _commandApdu2.default)({
73
- cla: 0x00,
74
- ins: ins.GET_RESPONSE,
75
- p1: 0x00,
76
- p2: 0x00,
77
- le: length
78
- }));
79
- };
80
-
81
- Iso7816.prototype.readRecord = function (sfi, record) {
82
- //console.log(`Iso7816.readRecord, sfi='${sfi}', record=${record}`);
83
- return this.issueCommand((0, _commandApdu2.default)({
84
- cla: 0x00,
85
- ins: ins.READ_RECORD,
86
- p1: record,
87
- p2: (sfi << 3) + 4,
88
- le: 0
89
- }));
90
- };
91
-
92
- function create(devices, cardReader) {
93
- return new Iso7816(devices, cardReader);
94
- }
95
-
96
- module.exports = create;
@@ -1,93 +0,0 @@
1
- 'use strict';
2
-
3
- var statusCodes = {
4
- '^9000$': 'Normal processing',
5
- '^61(.{2})$': 'Normal processing, (sw2 indicates the number of response bytes still available)',
6
- '^62(.{2})$': 'Warning processing',
7
- '^6200$': 'no info',
8
- '^6281$': 'Part of return data may be corrupted',
9
- '^6282$': 'end of file/record reached before reading le bytes',
10
- '^6283$': 'ret data may contain structural info',
11
- '^6284$': 'selected file is invalidated',
12
- '^6285$': 'file control info not in required format',
13
- '^6286$': 'unsuccessful writing',
14
- '^63(.{2})$': 'Warning processing',
15
- '^6300$': 'no info',
16
- '^6381$': 'last write filled up file',
17
- '^6382$': 'execution successful after retry',
18
- // c0 least significant nibble is a counter....
19
- // .. ..valued from 0 to 15
20
- // cf
21
- '^64(.{2})$': 'Execution error',
22
- '^65(.{2})$': 'Execution error',
23
- '^6500$': 'no info',
24
- '^6581$': 'memory failure',
25
- '^66(.{2})$': 'Reserved for future use',
26
- '^6700$': 'Wrong length',
27
- '^68(.{2})$': 'Checking error: functions in CLA not supported (see sw2)',
28
- '^6800$': 'no info',
29
- '^6881$': 'logical channel not supported',
30
- '^6882$': 'secure messaging not supported',
31
- '^69(.{2})$': 'Checking error: command not allowed (see sw2)',
32
- '^6a(.{2})$': 'Checking error: wrong parameters (p1 or p2) (see sw2)',
33
- '^6b(.{2})$': 'Checking error: wrong parameters',
34
- '^6c(.{2})$': 'Checking error: wrong length (sw2 indicates correct length for le)',
35
- '^6d(.{2})$': 'Checking error: wrong ins',
36
- '^6e(.{2})$': 'Checking error: class not supported',
37
- '^6f(.{2})$': 'Checking error: no precise diagnosis'
38
- };
39
-
40
- function ResponseApdu(buffer) {
41
- this.buffer = buffer;
42
- this.data = buffer.toString('hex');
43
- }
44
-
45
- ResponseApdu.prototype.getStatus = function () {
46
- var statusCode = this.getStatusCode();
47
- var meaning = 'Unknown';
48
- for (var prop in statusCodes) {
49
- if (statusCodes.hasOwnProperty(prop)) {
50
- var result = statusCodes[prop];
51
- if (statusCode.match(prop)) {
52
- meaning = result;
53
- break;
54
- }
55
- }
56
- }
57
- return {
58
- code: statusCode,
59
- meaning: meaning
60
- };
61
- };
62
- ResponseApdu.prototype.getStatusCode = function () {
63
- return this.data.substr(-4);
64
- };
65
- ResponseApdu.prototype.isOk = function () {
66
- return this.getStatusCode() === '9000';
67
- };
68
- ResponseApdu.prototype.buffer = function () {
69
- return this.buffer;
70
- };
71
- ResponseApdu.prototype.hasMoreBytesAvailable = function () {
72
- return this.data.substr(-4, 2) === '61';
73
- };
74
- ResponseApdu.prototype.numberOfBytesAvailable = function () {
75
- var hexLength = this.data.substr(-2, 2);
76
- return parseInt(hexLength, 16);
77
- };
78
- ResponseApdu.prototype.isWrongLength = function () {
79
- return this.data.substr(-4, 2) === '6c';
80
- };
81
- ResponseApdu.prototype.correctLength = function () {
82
- var hexLength = this.data.substr(-2, 2);
83
- return parseInt(hexLength, 16);
84
- };
85
- ResponseApdu.prototype.toString = function () {
86
- return this.data;
87
- };
88
-
89
- function create(buffer) {
90
- return new ResponseApdu(buffer);
91
- }
92
-
93
- module.exports = create;