# Core Services

## Introduction

The `Trust1Connector` core services address communication functionality with local, unmanaged devices. The `Trust1Connector` core exposes 2 main interfaces:

* interface for web/native applications
* framework interface for private or community plugins

In this guide, we target only the use of `Trust1Connector's` core interface for web/native applications.\
The GCL exposes protected and unprotected resources.

### Protected resources

Protected resources are administration resources. The JavaScript library must be initialized with a correct token in order to access the resource.

* Download `Trust1Connector` Instance `Trust1Connector` Core with default plugins)
* Get registration information
* Register device
* Synchronize device
* Container update (administration resource)

Executing these functionality is explained further.

### Un-protected resources

Un-protected resources can be used without the need of an additional security token.

* `Trust1Connector` Initialization (administration resource)
* `Trust1Connector` Information (administration resource)
* Get pub-key certificate (administration resource)
* Update pub-key certificate (administration resource)
* List card-readers
* List plugins
* Get plugin
* Get card-reader
* Get card-readers with card inserted
* Get card-readers without card
* Get consent
* Detect card for card-reader (polling utility resource)
* Detect any card (polling utility resource)
* Detect card-readers (polling utility resource)
* OS Information (utility resource)
* Browser Information (utility resource)

Executing these functionality is explained further.

## Core Functionality

The core functionality is about `communication` with device hardware.\
The document highlights communication with smart card readers - contact and contact-less. In the future, documentation will be updates with information for USB and Bluetooth connectivity.

### Information

In order to retrieve information about the installed device, the following function can be called:

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.info(callback);
});
```

```javascript
{
  "info": {
      "activated": true, 
      "arch": "x86_64",
      "citrix": false,
      "log_level": "info", 
      "managed": false, 
      "os": "10.12.5",
      "uid": "99E320ED7D519495", 
      "version": "1.2.5"
  }
}
```

| Property   | Description                                                                        |
| ---------- | ---------------------------------------------------------------------------------- |
| activated  | GCL activation flag                                                                |
| arch       | GCL targeted architecture                                                          |
| citrix     | Indicates whether GCL is running in Citrix mode                                    |
| log\_level | The GCL log level, possible values: full, debug, info, notification, waning, error |
| managed    | Indicated if GCL is in managed mode (no activation required)                       |
| os         | GCL targeted OS version                                                            |
| uid        | GCL identifier                                                                     |
| version    | GCL version                                                                        |

### List card readers

Returns a list of available card readers. Multiple readers can be connected. Each reader is identified by a unique `reader_id`.

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.readers(callback);
});
```

The response will contains a list of card readers:

```javascript
{
  "data": [
    {
      "id": "57a3e2e71c48cee9",
      "name": "Some fancy card reader",
      "pinpad": false
    }
  ],
  "success": true
}
```

When multiple readers are attached to a device, the response will show *all* connected card readers:

```javascript
{
  "data": [
    {
      "id": "ec3109c84ee9eeb5",
      "name": "Identiv uTrust 4701 F Dual Interface Reader(2)",
      "pinpad": false
    },
    {
      "card": {
        "atr": "3B9813400AA503010101AD1311",
        "description": [
          "Belgium Electronic ID card"
        ]
      },
      "id": "57a3e2e71c48cee9",
      "name": "Bit4id miniLector",
      "pinpad": false
    },
    {
      "id": "c8d31f8fed44d952",
      "name": "Identiv uTrust 4701 F Dual Interface Reader(1)",
      "pinpad": false
    }
  ],
  "success": true
}
```

Important to notice:

* The response adds a `card`-element when a card is inserted into the card reader.
* The response contains card-reader `pin-pad` capabilities

#### Card Inserted

As mentioned in the `List card-readers`, when a smart-card is inserted/detected, the reader will contain the cart-type based on the ATR. The ATR (**A**nwser **T**o **R**eset), is the response from any smart-card when powered, and defines the card type.\
The `Trust1Connector` recognized more than 3k smart-card types.

```javascript
{
  "data": [
    {
      "card": {
        "atr": "3B9813400AA503010101AD1311",
        "description": [
          "Belgium Electronic ID card"
        ]
      },
      "id": "57a3e2e71c48cee9",
      "name": "Bit4id miniLector",
      "pinpad": false
    }
  ],
  "success": true
}
```

#### Pin-Pad Capabilities

As mentioned in the `List card-readers`, when a card-reader has pin-pad capabilities, this will be mentioned in the response (notice the `pinpad`property):

```javascript
{
  "data": [
    {
      "card": {
        "atr": "3B9813400AA503010101AD1311",
        "description": [
          "Belgium Electronic ID card"
        ]
      },
      "id": "57a3e2e71c48cee9",
      "name": "Bit4id miniLector",
      "pinpad": false
    }
  ],
  "success": true
}
```

#### List Card-Readers - Explained Example

The following example is the response for `List card-readers` on a device with 4 different card-readers attached:

```javascript
{
  "data": [
    {
      "id": "ec3109c84ee9eeb5",
      "name": "Identiv uTrust 4701 F Dual Interface Reader(2)",
      "pinpad": false
    },
    {
      "card": {
        "atr": "3B67000000000000009000",
        "description": [
          "MisterCash & Proton card",
          "VISA Card (emitted by Bank Card Company - Belgium)"
        ]
      },
      "id": "e5863fcc71478871",
      "name": "Gemalto Ezio Shield Secure Channel",
      "pinpad": true
    },
    {
      "card": {
        "atr": "3B9813400AA503010101AD1311",
        "description": [
          "Belgium Electronic ID card"
        ]
      },
      "id": "57a3e2e71c48cee9",
      "name": "Bit4id miniLector",
      "pinpad": false
    },
    {
      "id": "c8d31f8fed44d952",
      "name": "Identiv uTrust 4701 F Dual Interface Reader(1)",
      "pinpad": false
    }
  ],
  "success": true
}
```

In the above example you notice that 4 card-readers are connected. Each card-reader receives his temporary `id` which can be used for other functions where a card-reader id is needed.\
This method can be requested in order to list all available card-readers, and optional cards-inserted.\
Each card-reader has a vendor provided name, which is retrieved from the card-reader itself.\
An additional property `pinpad`, a `boolean` value, denotes if the card-reader has pin-pad capabilities. A pin-pad is a card-reader, most of the times with its own display and key-pad.\
From a security perspective, it's considered best practice to use *as much as possible* pin-pad capabilities of a pin-pad card-reader.\
When a reader has a smart-card inserted (contact interface) or detected (contactless interface), the card type will be resolved by the GCL in order to respond with a meaningfull type.\
In the above examples you see that; one card-reader has a Belgian eID card; another card-reader has a `MisterCash` or `VISA Card` available for interaction.

The readers returned, are the card-readers with a card available. The card-readers where no card is presented, are ignored.

### Get Card-Reader

We can address a specific card-reader by using the card-reader `id` received from the previous call `List card-readers`:

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.reader(reader_id, callback);
});
```

The response will contain the information for the card-reader; including pin-pad capabilities or a `card` property when a smart-card is inserted or detected:

```javascript
{
  "data": {
    "card": {
      "atr": "3B9813400AA503010101AD1311",
      "description": [
        "Belgium Electronic ID card"
      ]
    },
    "id": "57a3e2e71c48cee9",
    "name": "Bit4id miniLector",
    "pinpad": false
  },
  "success": true
}
```

### Get card reader with card inserted

Returns a list of available card readers with a smart card inserted. Multiple readers can be connected with multiple smart cards inserted. Each reader is identified by a unique `reader_id` and contains information about a connected smart card. A smart card is of a certain type. The `Trust1Connector` detects the type of the smart card and returns this information in the JSON response.

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.readersCardAvailable(callback);
});
```

Response:

```javascript
{
  "data": [
    {
      "card": {
        "atr": "3B9813400AA503010101AD1311",
        "description": []
      },
      "id": "57a3e2e71c48cee9",
      "name": "Bit4id miniLector",
      "pinpad": false
    }
  ],
  "success": true
}
```

### List plugins

Returns a list of available plugins and plugins versions. Multiple versions of a plugin can run on the same `Trust1Connector` framework. In order to select the correct plugin, a `plugin_id` defines the unique id of a plugin.

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.plugins(callback);
});
```

Response:

```javascript
{
  "data": [
    {
      "id": "card",
      "name": "CardType",
      "version": "1.0.5-SNAPSHOT"
    },
    {
      "id": "emv",
      "name": "Emv",
      "version": "1.0.5-SNAPSHOT"
    },
    {
      "id": "beid",
      "name": "BelgiumEid",
      "version": "1.0.5-SNAPSHOT"
    }
  ],
  "success": true
}
```

### Get plugin

Returns information about a specific plugin, using its `plugin_id`.

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.plugins(plugin_id, callback);
});
```

Response: TBD

### Get Browser information

Returns browser information that is needed in order to download a GCL instance.

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.browserInfo(callback);
});
```

Response:

```javascript
{
    "browser": {
        "name": "Chrome",
        "version": "51.0.2704.103"
    },
    "manufacturer": "",
    "os": {
        "architecture": 32,
        "name": "OS X",
        "version": "10.11.6"
    },
    "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
}
```

## Administration Services

The T1C-JS can be used to execute administration services.\
In the JavaScript library, administration services are called with an additional Bearer token in the request header:\
The underlying GCL service will be requested, for example, with the following headers:

```bash
curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer eyJhbGciOiJSUzI...kRIIXz6bxTHFnqFX28oXk' 'https://localhost:10443/v1/core/update'
```

### Initialization (fail-silent)

The initialization process performs 2 main tasks:

* **one-time** registration/activation of the GCL
* retrieve JWT and check for updates

The one-time registration is explained further in `Register Device`.\
Upon initialization the T1C-JS will try to retrieve a valid JWT in order to check for updates.

More information for the configuration of the T1C-JS can be found in [Client Configuration](/t1c-js-guide/core/client-configuration.md).\
Depending of the initialization of the T1C-JS, we have the following possibilities:

| Key      | Use Case                                                                                                                                                                                                                                                |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OAuth2` | OAuth2 client\_id and client\_secret will be used towards the T1C-DS in order to receive a `client credential` access token. The access token will be used to retrieve a JWT for administration purposes, only when needed and in a `fail-silent` mode. |
| `none`   | No synchronization will be done with T1C-DS. No check will be performed for updates, and no additional plugins will be available.                                                                                                                       |
| `apiKey` | The api-key will be used to request a new JWT. The JWT will be used for administration purpose, only when needed and in a `fail-silent` mode.                                                                                                           |
| `JWT`    | The JWT is already received through a back-end request, and used for the initialization of the T1C-JS.                                                                                                                                                  |

In order to refresh JWT, the T1C-JS lib will request automatically a new JWT, by exchange of the existing JWT, as long as the token expiration time is still valid.

### Download GCL

Upon the initization of the JavaScript library, an info request will be send to the GCL instance. If the GLC instance could not be detected, a download trigger will be executed.

![Download Sequence](/files/-L9hsbsvErMO8IBO49vV)

| ref    | name                             | description                                                                                                                                                                                                      |
| ------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1      | `verify GCL URI`                 | the JavaScript library will verify for running GCL service on the hosting OS                                                                                                                                     |
| 1.1    | `get info`                       | the JavaScript library sends a request for information towards unprotected resource on GCL                                                                                                                       |
| 1.2    | `connection refused`             | a connection refused is sent when the GCL is not running as a local service on the hosting OS                                                                                                                    |
| 1.3    | `get info OS`                    | the JavaScript library requests for available OS information                                                                                                                                                     |
| 1.4    | `return OS info`                 | OS info received by the JavaScript library                                                                                                                                                                       |
| 1.5.\* | `get downloadLink(OSInfo)`       | the JavaScript library ask for a GCL download link towards a proxy or API Gateway. The JavaScript request is proxied after applying applicable policies (api-key validation, intermediate proxy validation, ...) |
| 1.6    | `installerLink`                  | the installer link is provided in the response and varies based on the OS information sent in the request                                                                                                        |
| 1.6.\* | `download installer and execute` | GCL installer is downloaded and installed in an admin context on the local device; GCL will push certificate to key-store; GCL will verify checksum - init pre-condition; GCL service enable auto-start          |

After a successful download, the consumer will be asked to refresh the browser. The JavaScript will trigger a 'registration' use case automatically.

The JavaScript library provides a function to call the download explicitly. Upon initialization of the library, upon requesting GCL info, a download is triggered automatically.

Function call:

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    client.download(callback);
});
```

### Register Device

This function is automatically called after a successful download. The GCL will keep state upon:

* registration: boolean value registration state
* update\_available: boolean value update availability state

![GCL Activation](/files/-L9hscB1memtcmdoWfYW)

### Synchronize Device

![GCL Synchronization](/files/-L9hscBcPCePT6aoJjwH)

## Utility Services

Utility services are function calls, available in the JavaScript library, implementing flows using the aforementioned elementary core functionality. A flow is the execution of a logical sequence of one or more resources\
Utility services are there to ease the integration, but can be implemented by the consumer itself.

### Detect Card Readers

A utility function in order to detect a card reader. The goal of this function is to start a card reader detection-process for a fixed amount in time&#x20;

(

web application controls the poll-time

)

. When a card-reader has been found, the card-reader info is returned and the poll process stops looking for card-readers

![Detect Card Reader](/files/-L9hscCMyDRRYJVvhwO6)

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.pollReaders(secondsToPollReader, callback, connectReader, readerTimeout);
});
```

All parameters are function callbacks with the exception of the `secondsToPollReader` object.\
The `secondsToPollReader` expects an integer and denotes the total time span to detect card-readers.

On success the function returns card-reader info (same response as in `card-reader info`).

The `connectReader` and `readerTimeout` are parameter-less functions, the JavaScript library will call those functions during flow execution.

| Function        | Signature                | Description                                                           |
| --------------- | ------------------------ | --------------------------------------------------------------------- |
| `callback`      | `callback(error,result)` | called upon result/error of use case                                  |
| `connectReader` | `connectReader()`        | called after each `poll`                                              |
| `readerTimeout` | `readerTimeout()`        | called after the total `seconds` are elapsed without finding a reader |

### Detect Card Inserted

A utility function in order to detect an inserted card. If a card is already inserted, the reader info, including card info will be send back as a response. The function verifies if there is a card-reader connected, and if so, request a callback for card insertion. When a card-reader is connected and a card is detected, the info is send back as a response.

![Detect card](/files/-L9hscTgskrd7Wl703Nc)

```javascript
GCLLib.GCLClient.initialize(config, function(err, client) {
    var coreService = client.core();
    core.pollCardInserted(secondsToPollReader, callback, connectReader, insertCard, cardTimeout);
});
```

All parameters are function callbacks with the exception of the `secondsToPollCard` object.\
The `secondsToPollCard` object provides a `timeout` value (in milliseconds) for detecting a card; this is the time the application is willing to wait for a card-reader to be connected and a card to be detected.\
Default callback definition:

```javascript
function callback (error, data){...}
```

On success returns valid data; upon an error, an error object is returned.\
The `connectReader`,`insertCard` and `cardTimeout` are parameter-less functions, the JavaScript library will call those functions during flow execution.

| Function        | Signature                | Description                                                           |
| --------------- | ------------------------ | --------------------------------------------------------------------- |
| `callback`      | `callback(error,result)` | called upon result/error of use case                                  |
| `connectReader` | `connectReader()`        | called after each `poll`                                              |
| `insertCard`    | `insertCard()`           | called after each poll when a card-reader is detected                 |
| `cardTimeout`   | `cardTimeout()`          | called after the total `seconds` are elapsed without detecting a card |

### Detect Card for Card-Reader

TBD

## Example HTML Modals

The T1C-JS is a JavaScript library that integrates easily in web applications. The concept of T1C-JS is to provide an interface in order to leave the web application in full control of operations towards GCL and towards back-end services.\
The examples mentioned here, are HTML, Bootstrap, jQuery examples that can be reused in a web application, but which can be fully customized as well.\
The documentation and the published web application example, available on Github, can be used in order to easy integration flows. See [Source Code downloads](/t1c-js-guide/core/source-code.md) for more information.

### PIN-validation Modal

This is an example for a PIN-entry modal for web application consumers:

![PIN-entry modal](/files/-L9hscpi-LTZbm-CCy5V)

Prerequisites:

* bootstrap
* jQuery

```markup
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.1/platform.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
```

Style example:

```css
<style media="screen">
        pre {
            background-color: #ddd;
            border: 2px solid #333;
            padding: .3em .5em;
        }

        pre#error,pre#validationError {
            border-color: #900;
        }
        .modal-header, h4, .close {
            background-color: #5cb85c;
            color:white !important;
            text-align: center;
            font-size: 30px;
        }
        .modal-footer {
            background-color: #f9f9f9;
        }
    </style>
```

Example of a PIN modal when no pin-pad enabled card reader is available:

```markup
<!-- PIN-entry Modal -->
    <div class="modal fade" id="pinModal" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header" style="padding:35px 50px;">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4><span class="glyphicon glyphicon-lock"></span> Validate PIN</h4>
                </div>
                <div class="modal-body" style="padding:40px 50px;">
                    <div class="form-group">
                        <label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Pin</label>
                        <input type="password" class="form-control" id="psw" placeholder="Enter pin code">
                    </div>
                    <div class="form-group">
                        <pre id="validationInfo" hidden="true"></pre>
                        <pre id="validationError" hidden="true"></pre>
                    </div>
                    <button id="buttonValidate" type="button" class="btn btn-default btn-lg">Validate</button>
                </div>
                <div class="modal-footer">

                </div>
            </div>
        </div>
    </div>
```

### PIN-entry Modal

The PIN-entry modal can be used for content signing.

### Download Modal

Using the same CSS as in the aforementioned example, a simple `download-modal` provides user information about the actions that should be done upon first use. The user will be presented a link, which downloads an installer. After a successful download the user can launch the installer in order to setup a GCL service.\
The correct GCL installer is provided depending on the browser information captured from the T1C-JS library.

The following HTML displays a simple download modal:

```markup
<!-- Download Modal -->
  <div class="modal fade" id="downloadModal" role="dialog">
      <div class="modal-dialog">
          <div class="modal-content">
              <div class="modal-header" style="padding:35px 50px;">
                  <button type="button" class="close" data-dismiss="modal">&times;</button>
                  <h4><span class="glyphicon glyphicon-lock"></span> Download Instructions</h4>
              </div>
              <div class="modal-body" style="padding:40px 50px;">
                  <div id="modalDownloadLink" class="form-group">
                      <label for="psw">Click the download link to start downloading</label>

                  </div>
              </div>
              <div class="modal-footer">
                  Download provided by Trust1Team.
              </div>
          </div>
      </div>
  </div>
```

The following JavaScript can be added in order to request for a download link, the browser-info will be requests, and passed to the download function as a parameter:

```javascript
$("#downloadgcl").on('click',function(){
      var core = connector.core();
      var self = this;
      core.infoBrowser(function(error,data){
         if(error){$("#error").append('Could not retrieve browser info');}
         connector.ds().downloadLink(data.data, function(error,data) {
             if(error)$("#error").append('Error retrieving download link');
             $("#downloadModal").modal('toggle');
             $("a").remove('.downloadlinkref'); //remove previous links
             $("#modalDownloadLink").append('<a class= "downloadlinkref" href="'+ data.url +'">Download link GCL</a>');
         });
      });
  });
```

Based on the above code example, the web application will display the following modal:

![Download Modal](/files/-L9hsdWRg8jku9MLHx35)

### Connect Reader Modal

Upon requesting the `list card-readers` function, when the result is an empty JSON, one could show a modal to connect a card-reader.\
One or more card readers can be connected, and the T1C-JS can operate easily with all connected card-readers at the same time.\
In order to demonstrate the `Connect Reader Modal`, we'll start requesting for card-readers:

```javascript
var core = connector.core().readers(callback);
```

An empty response, showing there is no card reader connected:

```javascript
{
  "data": [],
  "success": true
}
```

This means, the user has no card-reader connected, we can now show an information-based modal to notify the user:

### Insert Card Modal

TBD

## Certificate Management

In order to the GCL to operate on locale devices, a trust relation must be available between the requests/responses send to/from the distribution server. The T1C-JS is considered unsecured, and only serves as the application mediator between the GCL and the T1C-DS. Therefore JWT (JSON Web Tokens) are used to validate tokens in the context of a local device. The issued tokens are signed with the private key of the Distribution Service (T1C-DS).\
During the initialization of a GCL instance, the T1C-JS will update the public key taking into consideration the targetted environment (development, acceptance, staging, production).\
The api-key issued for a customer or application consumer is resovled with the necessary information.

### Get GCL Public Key

In order to validate if a GCL instance has been successfully initialized, and contains a valid public key certificate. The following function can be called:

```javascript
gclClient.core().getPubKey(callback)
```

When the public key has been provided, the following response will be returned:

```javascript
{
  "success": true,
  "pubkey": "MIIBIjANBgkqh...1nTnoPeC5QIDAQAB"
}
```

### Update GCL Public Key

When the GCL is initially downloaded, it must be initialised with a valid public key. The GCL is distributed with a root CA and sub CA certificate. The public key must be issued by this root/sub authority in order to be valid.\
The public key issues, is specific for the environment in which the GCL operates. When the apikey (used in order to initialize the T1C-JS lib) is issued for a development environment, a development public key will be requested in order to initialize the locale GCL instance.

![Upload GCL Public Key](/files/-L9hsdjOLUv8HH05Uufz)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://t1t.gitbook.io/t1c-js-guide/core/core-services.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
