# API Reference

This page contains comprehensive API documentation for the TypeScript / JavaScript SDK. If you're looking to get started quickly, visit our [quick start](https://docs.id.gov.sg/integrations-with-sgid/typescript-javascript) or our [framework-specific guides](https://docs.id.gov.sg/integrations-with-sgid/typescript-javascript/framework-guides).

The source code can be found on [GitHub](https://github.com/opengovsg/sgid-client).

## convertPkcs1ToPkcs8

```typescript
convertPkcs1ToPkcs8(pkcs1: string): string
```

Converts a private key in PKCS1 format to PKCS8.

**Parameters**

`<string>` Private key as a string.

**Returns**

`<string>` Private key in PKCS8 format.

## generateCodeChallenge

```typescript
generateCodeChallenge(codeVerifier: string): string
```

Calculates the S256 code challenge for a provided code verifier.

**Parameters**

`<string>` The code verifier.

**Returns**

`<string>` The calculated code challenge.

## generateCodeVerifier

```typescript
generateCodeVerifier(length: number = 43): string
```

Generates the random code verifier.

**Parameters**

`<number>` (Optional) The length of the code verifier to generate. Defaults to 43.

**Throws**

`Error` if length is < 43 or > 128.

**Returns**

`<string>` The generated code verifier.

## generatePkcePair

```typescript
generatePkcePair(length: number = 43): {
    codeVerifier: string;
    codeChallenge: string;
}
```

Generates a challenge pair where `code_challenge` is the generated S256 hash from `code_verifier`.

**Parameters**

`<number>` (Optional) The length of the code verifier. Defaults to 43.

**Throws**

`Error` if length is < 43 or > 128.

**Returns**

`<Object>`

* codeChallenge: `<string>` **S256** code challenge generated from the code verifier.
* codeVerifier: `<string>`

## SgidClient

Class which allows you to interact with the sgID API.

### constructor

```typescript
SgidClient({
    clientId,
    clientSecret,
    privateKey,
    redirectUri,
    hostname = "https://api.id.gov.sg",
}: {
    clientId: string;
    clientSecret: string;
    privateKey: string;
    redirectUri?: string;
    hostname?: string;
}): SgidClient
```

Initialises an SgidClient instance.

**Parameters**

`<Object>`

* clientId: `<string>` Client ID provided during client registration.
* clientSecret: `<string>` Client secret provided during client registration.
* privateKey: `<string>` Client private key provided during client registration.
* redirectUri: `<string>` (Optional) Redirection URI for user to return to your application after login. If not provided in the constructor, this must be provided to the authorization\_url and callback functions.
* hostname: `<string>` (Optional) Hostname of OpenID provider (sgID). Defaults to "<https://api.id.gov.sg>".

### authorizationUrl

```typescript
authorizationUrl({
    state,
    scope = "openid myinfo.name",
    nonce = generators.nonce(),
    redirectUri = this.getFirstRedirectUri(),
    codeChallenge
}: {
    state?: string;
    scope?: string | string[];
    nonce?: string | null;
    redirectUri?: string;
    codeChallenge: string;
}): {
    url: string;
    nonce?: string;
}
```

Generates authorization url to redirect end-user to sgID login page.

**Parameters**

`<Object>`

* state: `<string>` (Optional) A string which will be passed back to your application once the end-user logs in. You can also use this to track per-request state.
* scope: `<string> | <string[]>` (Optional) Scopes being requested. Can be provided as a string array or a space-concatenated string. "openid" must be provided as a scope. Defaults to "openid myinfo.name".
* nonce: `<string> | <null>` (Optional) Random, unique value to associate a user-session with an ID Token and to mitigate replay attacks. Set as `null` to omit the nonce. Defaults to a randomly generated nonce if unspecified or set as `undefined`.
* redirectUri: `<string>` (Optional) The redirect URI used in the authorization request. If this param is provided, it will be used instead of the redirect URI provided in the SgidClient constructor. If not provided in the constructor, the redirect URI must be provided here. Defaults to the `redirectUri` provided in the constructor.
* codeChallenge: `<string>` The code challenge generated from `generatePkcePair()`.

**Throws**

`Error` if redirect URI is provided in neither the constructor nor this function.

**Returns**

`<Object>`

* url: `<string>` Generated authorization url.
* nonce: `<string> | <undefined>` Provided nonce, randomly generated nonce, or `undefined` (based on nonce input). Should be stored in the user's session so it can be retrieved later for use in `callback`.

### callback

```typescript
async callback({
    code,
    nonce,
    redirectUri = this.getFirstRedirectUri(),
    codeVerifier
}: {
    code: string;
    nonce?: string | null;
    redirectUri?: string;
    codeVerifier: string;
}): Promise<{
    sub: string;
    accessToken: string;
}>
```

Exchanges authorization code for access token.

**Parameters**

`<Object>`

* code: `<string>` Authorization code returned in query params via the redirect URI after login.
* nonce: `<string> | <null>` (Optional) Nonce returned from `authorizationUrl` (Set as `null` if nonce was set as `null` in `authorizationUrl`).
* redirectUri: `<string>` (Optional) Overriding redirect URI used in `authorizationUrl` (if provided). Defaults to the `redirectUri` provided in the constructor.
* codeVerifier: `<string>` Code verifier for the code challenge provided in `authorizationUrl`.

**Throws**

`Error` if call to token endpoint fails.

`Error` if call to JWKS endpoint fails.

`Error` if ID token validation fails.

`Error` if access token validation fails.

**Returns**

`<Promise<Object>>`

* sub: `<string>` Sub (subject identifier claim) which is the end-user's unique ID.
* accessToken: `<string>` Access token used to request user info.

### userinfo

```typescript
async userinfo({
    sub,
    accessToken
}: {
    sub: string;
    accessToken: string;
}: Promise<{
    sub: string;
    data: Record<string, string>;
}>
```

Retrieves verified user info and decrypts it with your private key.

**Parameters**

`<Object>`

* sub: `<string>` Sub obtained from `callback`.
* accessToken: `<string>` Access token obtained from `callback`.

**Throws**

`Error` if call to userinfo endpoint fails.

`Error` if sub returned from userinfo endpoint does not match sub passed to this function.

`Error` if decryption fails.

**Returns**

`<Object>`

* sub: `<string>` Represents a unique identifer for the end-user.
* data: `<Record<string, string>>` A JSON object containing end-user info where the keys are the scopes requested in `authorizationUrl`.


---

# 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://docs.id.gov.sg/integrations-with-sgid/typescript-javascript/api-reference.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.
