Node API Reference
Node API Reference
#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)
didToken
(String): A Decentralized ID Token generated by a Magic user on the client-side.
#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)
didToken
(String): A Decentralized ID Token generated by a Magic user on the client-side.
#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 theadd
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)
issuer
(String): The user's Decentralized ID, which can be parsed usingTokenModule.getIssuer
.
#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)
didToken
(String): A valid Decentralized ID Token generated client-side by a Magic user.
#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)
issuer
(String): The user's Decentralized ID, which can be parsed usingTokenModule.getIssuer
.
#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)
publicAddress
(String): The user's Ethereum public address, which can be parsed usingTokenModule.getPublicAddress
.
#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)
didToken
(String): A valid Decentralized ID Token generated client-side by a Magic user.
#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 from the client-side application that looks likeBearer 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 Key | Description |
TokenExpired | The supplied DID Token is invalid due to an expired timestamp. |
TokenCannotBeUsedYet | The 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. |
IncorrectSignerAddress | The supplied DID Token is invalid due to a mismatch between the signature origin and the claimed user public address. |
FailedRecoveryProof | The supplied DID Token could not be recovered using Elliptic Curve recovery. |
ApiKeyMissing | The API key required for a particular action is missing or malformed. |
MalformedTokenError | The supplied DID Token could not be successfully parsed. |
ServiceError | An 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.