Node

Reference for the Magic Admin SDK for Node.js / server-side JavaScript: https://github.com/magiclabs/magic-admin-js

Overview

The Magic SDK for server-side JavaScript makes it easy to leverage Decentralized ID Tokens to protect routes and restricted resources for your app. This guide will cover some important topics for getting started with server-side APIs and to make the most of Magic's features.

  • Install the Magic Admin SDK to get started

  • View the API documentation below to learn the methods you'll be using

  • Go to Examples for an introduction to common patterns and use-cases

note

Looking for a client-side API instead? Check out:

๐Ÿ‘‰ Magic Client SDK for web

๐Ÿ‘‰ Magic Client SDK for React Native

Installation

npm install --save @magic-sdk/admin

Creating an SDK Instance

Examples for the server-side JavaScript SDK use the CommonJS pattern by default.

const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY'); // โœจ

Constructor

Arguments

new Magic(secretApiKey, options?)

  • secretApiKey (String): Your secret API Key retrieved from the Magic Dashboard.
  • options.endpoint?(String): A URL pointing to the Magic API. You should not need to provide this value except in case you are building highly custom integration tests.

Example

const { Magic } = require('@magic-sdk/admin');
let m;
// Construct with an API key:
m = new Magic('API_KEY');
// Construct with an API key plus options:
m = new Magic('API_KEY', { endpoint: '...' });

Token Module

The Token Module and its members are accessible on the Magic Admin SDK instance by the token property.

const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
mAdmin.token;
mAdmin.token.getIssuer;
mAdmin.token.getPublicAddress;
mAdmin.token.decode;
mAdmin.token.validate;

getIssuer

Arguments

getIssuer(didToken)

didToken (String): A Decentralized ID Token generated by a Magic user on the client-side.

Returns

string: The Decentralized ID of the Magic User who generated the DID Token.

Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
/* Gets the DID token from a login request */
app.get('/login', async (req: any, res: any) => {
/*
Assumes DIDToken was passed in the Authorization header
in the standard `Bearer {token}` format.
*/
const DIDToken = req.headers.authorization.substring(7);
const issuer = mAdmin.token.getIssuer(DIDToken);
/* You can use this as the ID column in your own tables */
});

getPublicAddress

Gets the cryptographic public address of the Magic User who generated the supplied token.

Arguments

getPublicAddress(didToken)

Returns

string: The public address of the Magic User who generated the DID Token.

Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
/* Gets the DID token from a login request */
app.get('/login', async (req: any, res: any) => {
/*
Assumes DIDToken was passed in the Authorization header
in the standard `Bearer {token}` format.
*/
const DIDToken = req.headers.authorization.substring(7);
const publicAddress = mAdmin.token.getPublicAddress(DIDToken);
/* You can use this as the ID column in your own tables */
});

decode

Decodes a Decentralized ID Token from a Base64 string into a tuple of its individual components.

Arguments

decode(didToken)

Returns

[string, Claim]: containing the [proof, claim] that composes the DID Token. The claim, while given as a JSON string, is automatically parsed to the following interface:

interface Claim {
iat: number; // Issued At Timestamp
ext: number; // Expiration Timestamp
iss: string; // Issuer of DID Token
sub: string; // Subject
aud: string; // Audience
nbf: number; // Not Before Timestamp
tid: string; // DID Token ID
add: string; // (optional) Misc additional signed data
}

As a convenience, the above interface is available to your code in TypeScript:

import { Claim } from '@magic-sdk/admin';
Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
/* Gets the DID token from a login request */
app.get('/login', async (req: any, res: any) => {
/*
Assumes DIDToken was passed in the Authorization header
in the standard `Bearer {token}` format.
*/
const DIDToken = req.headers.authorization.substring(7);
const [proof, claim] = mAdmin.token.decode(DIDToken);
console.log(proof); // => string
console.log(claim);
/*
=> {
iat: number,
ext: number,
iss: string,
sub: string,
aud: string,
nbf: number,
tid: string
}
*/
});

validate

Validates a Decentralized ID token.

Arguments

validate(didToken, attachment? = 'none')

  • didToken (String): A Decentralized ID Token generated by a Magic user on the client-side.
  • attachment? (String): Arbitrary, serialized data to be used for recovery of the add field on the Decentralized ID Token (Defaults to "none").
Returns

void: The function will return if the specified DID token is authentic and not expired. If the token is forged or otherwise invalid, the function will throw a descriptive error.

Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
/* Gets the DID token from a login request */
app.get('/login', async (req: any, res: any) => {
/*
Assumes DIDToken was passed in the Authorization header
in the standard `Bearer {token}` format.
*/
const DIDToken = req.headers.authorization.substring(7);
mAdmin.token.validate(DIDToken);
/* User is logged in. Set cookies! */
});

User Module

logoutByIssuer

Logs a user out of all client-side Magic SDK sessions given the user's Decentralized ID.

Arguments

logoutByIssuer(issuer)

Returns

Promise<void>

Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
// Grabs user's Decentralized ID from the DID Token
const issuer = mAdmin.token.getIssuer(DIDToken);
// logs the user out of all valid browser sessions.
await mAdmin.users.logoutByIssuer(issuer);

logoutByPublicAddress

Logs a user out of all client-side Magic SDK sessions given the user's public address.

Arguments

logoutByPublicAddress(publicAddress)

  • publicAddress (String): The user's public address to log out via the Magic API.
Returns

Promise<void>

Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
// Grabs user's public address by DIDToken
const userPublicAddress = mAdmin.token.getPublicAddress(DIDToken);
// logs the user out of all valid browser sessions.
await mAdmin.users.logoutByPublicAddress(userPublicAddress);

logoutByToken

Logs a user out of all client-side Magic SDK sessions given the user's public address.

Arguments

logoutByToken(didToken)

Returns

Promise<void>

Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
// Get a token however you wish! Perhaps this is attached
// to `req.authorization`
const DIDToken = // ...
// logs the user out of all valid browser sessions.
await mAdmin.users.logoutByToken(DIDToken);

getMetadataByIssuer

Retrieves information about user by the supplied "issuer".

Arguments

getMetadataByIssuer(issuer)

Returns

Promise<{ issuer, email, publicAddress }>: an object containing the issuer, email and cryptographic public address of the authenticated user.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • email (String): Email address of the authenticated user.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
// Grabs the issuer from a DID Token
const issuer = mAdmin.token.getIssuer(DIDToken);
// Gets user metadata based on the given issuer
const metadata = await mAdmin.users.getMetadataByIssuer(issuer);

getMetadataByPublicAddress

Retrieves information about user by the supplied public address.

Arguments

getMetadataByPublicAddress(publicAddress)

Returns

Promise<{ issuer, email, publicAddress }>: an object containing the issuer, email and cryptographic public address of the authenticated user.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • email (String): Email address of the authenticated user.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
// Grabs the issuer from a DID Token
const userPublicAddress = mAdmin.token.getPublicAddress(DIDToken);
// Gets user metadata based on the given issuer
const metadata = await mAdmin.users.getMetadataByPublicAddress(userPublicAddress);

getMetadataByToken

Retrieves information about user by the supplied DID Token.

Arguments

getMetadataByToken(didToken)

Returns

Promise<{ issuer, email, publicAddress }>: an object containing the issuer, email and cryptographic public address of the authenticated user.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • email (String): Email address of the authenticated user.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic('SECRET_API_KEY');
...
// Get a token however you wish! Perhaps this is attached
// to `req.authorization`
const DIDToken = // ...
// Retrieves user information by DID token
const metadata = await mAdmin.users.getMetadataByToken(DIDToken);

Utils Module

The Utils Module and it's members are accessible on the Magic Admin SDK instance by the utils property.

const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic();
mAdmin.utils;
mAdmin.utils.parseAuthorizationHeader;

parseAuthorizationHeader

Arguments

parseAuthorizationHeader(header)

  • header (String): A request authorization header passed in front the client-side application that looks like Bearer WyIweG...n0iXQ==.
Returns

string: The DID token embedded in the authorization header.

{% hint style="info" %} This is only available to Admin SDK version 1.1.0 and above. {% endhint %}

Example
const { Magic } = require('@magic-sdk/admin');
const mAdmin = new Magic();
...
/* Gets the DID token from a login request */
app.get('/login', async (req: any, res: any) => {
/*
Assumes DIDToken was passed in the Authorization header
in the standard `Bearer {token}` format.
*/
const didToken = mAdmin.utils.parseAuthorizationHeader(req.headers.authorization);
/* You can now do stuff with the DID token */
});

Errors & Warnings

SDKError

The SDKError class is exposed for instanceof operations.

import { SDKError } from '@magic-sdk/admin';
try {
// Something async...
catch (err) {
if (err instanceof SDKError) {
// Handle...
}
}

Additionally, an enumeration of relevant error codes is also exposed for convenience and human readability:

import { ErrorCode } from '@magic-sdk/admin';
ErrorCode.MissingApiKey
ErrorCode.MissingAuthHeader
ErrorCode.IncorrectSignerAddress
// and so forth...
// Please reference the `Enum Key` column of the error table below.

Error Codes

Enum KeyDescription
TokenExpiredThe supplied DID Token is invalid due to an expired timestamp.
TokenCannotBeUsedYetThe nbf ("not before") field of the supplied DID Token is set in the future. By default, a 5 minute leeway is added to the timestamp.
IncorrectSignerAddressThe supplied DID Token is invalid due to a mismatch between the signature origin and the claimed user public address.
FailedRecoveryProofThe supplied DID Token could not be recovered using Elliptic Curve recovery.
ApiKeyMissingThe API key required for a particular action is missing or malformed.
MalformedTokenErrorThe supplied DID Token could not be successfully parsed.
ServiceErrorAn error occurred while communicating with the Magic API. Be sure to check the data property of the error object for additional context.

data & Nested Errors

For additional context about an error, the SDKError.data property contains an array of potentially illuminating metadata. At the moment, this property is reserved for service errors when communication to Magic APIs fail.


Examples

Log Out a User's Magic Session

Sometimes you will find yourself needing to log your users out from the server-side. This provides a small example of how to do so.

0. Prerequisite: Install Magic Admin SDKโ€‹

1. Invalidate the user session:

app.post('/logout', (req: any, res: any) => {
const userPublicAddress = magicAdmin.token.getPublicAddress(
req.headers.authorization
);
magicAdmin.users.logoutByPublicAddress(userPublicAddress);
});