@glideidentity/glide-be-node-magical-auth
Glide Magical Auth SDK for Node.js — phone number authentication without SMS/OTP using carrier-based digital credentials.
Features
- Zero Dependencies - Uses only Node.js built-ins (Node 18+)
- TypeScript First - Full type safety with excellent IntelliSense support
- BYOC - Bring Your Own HTTP Client for custom implementations
- BYOL - Bring Your Own Logger for custom logging
- Automatic Token Management - OAuth2 tokens cached and refreshed automatically
- Thread-Safe - Safe for concurrent use with promise deduplication
Installation
npm install @glideidentity/glide-be-node-magical-auth
Requirements
- Node.js 18.0.0 or higher
Quick Start
import { MagicalAuthClient } from '@glideidentity/glide-be-node-magical-auth';
const client = new MagicalAuthClient({
clientId: process.env.GLIDE_CLIENT_ID!,
clientSecret: process.env.GLIDE_CLIENT_SECRET!,
});
// 1. Prepare authentication
const prepareResponse = await client.prepare({
phone_number: '+14155551234',
nonce: crypto.randomUUID(),
use_case: 'VerifyPhoneNumber',
client_info: {
user_agent: navigator.userAgent,
},
});
// 2. Handle based on authentication strategy
switch (prepareResponse.authentication_strategy) {
case 'ts43':
// Direct credential request via the Digital Credentials API
// (available in supported browsers and natively on Android via Credential Manager).
// Use the data.dcql_query payload to invoke the API on your client.
break;
case 'link':
// OAuth-style redirect flow on mobile.
// Redirect the user to prepareResponse.data.url.
break;
case 'desktop':
// QR-code flow for desktop browsers. The `data` field is a
// DesktopStrategyData wrapper; the QR payload lives at `data.data`:
// const desktop = prepareResponse.data; // DesktopStrategyData
// render(desktop.data.qr_image); // base64 PNG data URL
// showChallenge(prepareResponse.challenge?.pattern);
break;
}
// 3. Verify the phone number with credential from device
const verifyResponse = await client.verifyPhoneNumber({
session: prepareResponse.session,
credential: credentialFromDevice,
});
if (verifyResponse.verified) {
console.log('Phone verified:', verifyResponse.phone_number);
}
API Reference
MagicalAuthClient
The main client class for interacting with the Magical Auth API.
Constructor
new MagicalAuthClient(config: MagicalAuthConfig)
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
clientId | string | Yes | - | OAuth2 client ID |
clientSecret | string | Yes | - | OAuth2 client secret |
baseUrl | string | No | https://api.glideidentity.app | API base URL |
httpClient | HttpClient | No | Native fetch | Custom HTTP client |
logger | Logger | No | No-op | Custom logger |
timeout | number | No | 30000 | Request timeout in ms |
Methods
prepare(request: PrepareRequest): Promise<PrepareResponse>
Prepares authentication by checking carrier eligibility and generating protocol-specific requests.
const response = await client.prepare({
phone_number: '+14155551234', // Required for VerifyPhoneNumber
plmn: { mcc: '310', mnc: '260' }, // Optional carrier identifier
nonce: 'unique-nonce', // Required, base64url encoded
use_case: 'VerifyPhoneNumber', // or 'GetPhoneNumber'
client_info: { user_agent: '...' }, // Optional, helps strategy selection
consent_data: { ... }, // Optional consent text
options: { theme: 'dark' }, // Optional UI theme
});
PrepareOptions
| Field | Type | Description |
|---|---|---|
parent_session_id | string | Parent session for the desktop QR flow — set it on the companion/child prepare. |
theme | Theme | UI theme forwarded verbatim to every touchpoint. "dark" / "light", or any custom identifier (max 32 chars). |
link_type | LinkType | Overrides link dispatch (app_clip, app_link, headless, web_link). Link strategy only. |
network_origin | NetworkOrigin | The server-observed IP of the requesting device, stamped by your backend. Stamp it on both prepares to get network_check back. Never trust a client-supplied value. |
mobile_companion_passthrough | Record<string, unknown> | Opaque JSON forwarded to the branded companion app. Object only, ≤16 KB. |
completion_redirect_url | string | Where the browser lands once authentication completes. Selects one of your application's registered completion_redirect_urls (exact match per RFC 6749 §3.1.2). Stamp it server-side from your own deployment's origin — never from the request Host header or any client-controllable value. |
sim_swap_max_age_hours | number | SIM swap query window in hours. See below. |
biometric | boolean | Opt in to the TS43 biometric signal. See below. |
sim_swap_max_age_hours sets how far back a SIM/device swap check looks. Integer, 1–2400; anything outside that range is refused with 400 VALIDATION_ERROR before a session is created. When omitted, the server falls back to the carrier's configured default_max_age_hours and then to a 24 hour default. The window that actually produced the answer comes back as max_age_hours on the swap payloads, so you can always tell which window you are reading.
biometric asks the device to run a biometric step during the TS43 credential ceremony and report the outcome as biometric_verification. It is sent as-is: true and explicit false both go on the wire; unset is omitted. On Desktop (QR), set on the parent prepare; the phone inherits it. Ignored on Link. Requesting it never makes biometric mandatory: a device that cannot perform it still authenticates.
const response = await client.prepare({
phone_number: '+14155551234',
nonce: 'unique-nonce',
use_case: 'VerifyPhoneNumber',
client_info: { user_agent: req.headers['user-agent'] },
options: {
sim_swap_max_age_hours: 72,
biometric: true,
},
});
prepareMultiple(request: PrepareMultipleRequest, options?: RequestOptions): Promise<PrepareMultipleResult[]>
Prepares authentication for up to PREPARE_MULTIPLE_MAX (10) phone numbers in one call. Fans out one ordinary prepare per number — each gets its own nonce, session, and (for link strategy) feCode/feHash. Returns one result per input number, in input order.
Per-number failures are returned in the array, not thrown. The method throws only for caller-input errors (empty list, over cap, blank entry, or a shared prepare field that prepare would reject) and only before any HTTP request is issued.
CARRIER_NOT_ELIGIBLE and CARRIER_TEMPORARILY_UNAVAILABLE are both HTTP 422; only the code tells a durable refusal from a transient, retryable carrier outage — on each failed item, branch on its error (instanceof CarrierNotEligibleError or item.error.code), not on status, or a transiently breakered number gets hidden as permanently ineligible.
Strip feCode from each successful result before forwarding to a browser — it is the device-binding secret and must never reach client-side JavaScript.
Pass a short session_timeout (60–900 seconds, same as prepare) so unpicked sessions expire quickly.
const results = await client.prepareMultiple({
use_case: 'VerifyPhoneNumber',
phone_numbers: ['+14155551234', '+14155559876'],
client_info: { user_agent: req.headers['user-agent'] },
session_timeout: 120,
});
const picker = results
.filter((r) => r.ok)
.map((r) => {
const { feCode, ...prepareForClient } = r.result;
return {
id: myPhoneIdFor(r.phone_number),
label: mask(r.phone_number),
prepare: prepareForClient,
};
});
TypeScript uses a discriminated union on ok ({ ok: true; result } | { ok: false; error }). Go and Java expose the same semantics via nullable fields and OK() / isOk().
verifyPhoneNumber(request: VerifyPhoneNumberRequest): Promise<VerifyPhoneNumberResponse>
Verifies a phone number using digital credentials.
const result = await client.verifyPhoneNumber({
session: prepareResponse.session,
credential: 'sd-jwt-credential-from-device',
});
console.log(result.verified); // true or false
console.log(result.phone_number); // '+14155551234'
console.log(result.sim_swap?.risk_level); // 'RISK_LEVEL_LOW'
Verifying the signed verification record
The response also carries verification_record, a Glide-signed ES256 JWS of the verify result, and verification_record_status ('signed' or 'unavailable'). Keep the record if you need proof of the result later, and check it with verifyVerificationRecord(record, options?), passing the nonce you sent to prepare:
import { VerificationRecordError, VerificationRecordErrorCode } from '@glideidentity/glide-be-node-magical-auth';
try {
const { claims, signOffResults } = await client.verifyVerificationRecord(result.verification_record, {
expectedNonce: prepareNonce,
});
console.log(claims.verified, claims.sub);
} catch (err) {
if (err instanceof VerificationRecordError && err.code === VerificationRecordErrorCode.RECORD_UNAVAILABLE) {
// no signed record for this result
}
}
- An empty or missing record fails closed with
RECORD_UNAVAILABLE, so the response field can be passed straight in. - Records longer than 16 KiB are rejected as
MALFORMEDbefore decoding. - The other codes (
VerificationRecordErrorCode) areMALFORMED,DISALLOWED_HEADER,UNKNOWN_KEY,BAD_SIGNATURE,WRONG_ISSUER,WRONG_AUDIENCE(audmust equal the expected audience, default your client ID),EXPIRED,NOT_YET_VALID,NONCE_MISMATCH,ORIGIN_MISMATCH,UNSUPPORTED_VERSIONandREVOKED_KEY. Every failure throwsVerificationRecordErrorwithstatus0. - Claims that break the v1 contract fail with
MALFORMED:vermust be the string"1.0"(otherwiseUNSUPPORTED_VERSION),verifieda boolean,jti,nonceandsub(tel:+E164) non-empty strings,nbfequal toiat,use_caseexactlyVerifyPhoneNumber,origin(canonical device origin,UNKNOWNon Link) andbiometric_verificationstrings,exp1 to 60 s afteriat, andsign_offsan array of entries with non-emptyrole,signerandstatus(unavailablewith areason, orpresentwithformatandtoken), exactly one of them acarrierentry signedcarrier:<id>. Optionalstrategy(TS_43,LINK,DESKTOP__TS_43,DESKTOP__LINK,DESKTOP),phone_number_details,carrier({id, name, mvno}),sim_swapanddevice_swapare accepted when present; a wrong JSON type, acarrierwithout a non-empty stringid, or acarrier.idthat does not match the carrier sign-off signer (carrier:<id>), isMALFORMED. Recordsim_swap/device_swapcarryage_band{from, to}in hours (-1unknown) and omitchecked_at—iatis the authoritative check time. - Keys come only from
<baseUrl>/.well-known/us/jwks.json(it carries both regions' record keys), cached perCache-Control(300 s default); nothing in the token picks a URL. Only Glide's record-signing kids are accepted. Glide keeps a retired record key published for at least 90 days (the defaultmaxAuditAgeSeconds); a record whose key has since been unpublished failsUNKNOWN_KEY, even withallowExpired. - Set
expectedAudienceto the record audience you configured in the developer portal (empty checks your client ID). To pin the device origin, setexpectedOrigin(a list): the record's canonicaloriginmust equal one entry exactly, elseORIGIN_MISMATCH; Link records carryUNKNOWN, so leaveUNKNOWNout of the list to reject them. - To audit a stored record after
exp, setallowExpired: true;iatmust still be withinmaxAuditAgeSeconds(90 days by default) and revoked kids (revokedKidsplus the built-in list) are always rejected.issueroverrides the expectediss(default: the base URL). - In v1
claims.sign_offsholds onecarrierentry with statusunavailable;signOffResultsreports it asunavailable, and a present sign-off would be reportedunverified, never trusted. - Integer claims follow
JSON.parse, so1.0is accepted where an integer is required (the Go and Java SDKs reject it); Glide never signs such values.
getPhoneNumber(request: GetPhoneNumberRequest): Promise<GetPhoneNumberResponse>
Retrieves the phone number associated with the device.
const result = await client.getPhoneNumber({
session: prepareResponse.session,
credential: 'sd-jwt-credential-from-device',
});
console.log(result.phone_number); // '+14157400083'
Risk signals on the success response
VerifyPhoneNumberResponse and GetPhoneNumberResponse carry the same signals: biometric_verification, plus the optional sim_swap, device_swap and phone_number_details. Each optional one is omitted when the carrier or the session did not produce it, so branch on presence rather than assuming a falsy value is meaningful.
SimSwapInfo
| Field | Type | Description |
|---|---|---|
checked | boolean | Whether the check completed. When false, read reason and ignore the rest. |
risk_level | RiskLevel | RISK_LEVEL_HIGH | RISK_LEVEL_MEDIUM | RISK_LEVEL_LOW | RISK_LEVEL_UNKNOWN. |
age_band | string | When the SIM last changed, e.g. "0-4 hours", "7-14 days", "more than 3 years", "older than query window", "temporarily unavailable", "not available". |
carrier_name | string | The carrier that performed the check. |
checked_at | string | When the check ran, RFC3339. Kept as a string — the SDK passes the wire value through without parsing. |
swapped | boolean | Whether a swap fell inside max_age_hours. Omitted when the carrier gave no determinable answer (T-Mobile codes 999 / NA) — that is not the same as false. |
max_age_hours | number | The window this answer actually describes. |
reason | SimSwapFailureReason | Only when checked is false: timeout, carrier_not_supported, disabled, error. |
DeviceSwapInfo
Device (IMEI) change, reported only by carriers that support it — currently T-Mobile. It is a fully independent signal, not a variant of SimSwapInfo: identical fields except that it has no reason, because the server never populates one.
Reading the swap window
An absent swapped means the check was inconclusive — the carrier gave no determinable age. RISK_LEVEL_UNKNOWN is broader: it covers that inconclusive case and a CAMARA carrier successfully confirming no swap inside the window, which returns swapped: false and age_band: "older than query window" but still grades RISK_LEVEL_UNKNOWN, because the carrier never dated the last swap. That second case used to report RISK_LEVEL_LOW, so code reading LOW as "safe" now falls through to its default. Branch on swapped for "was there a swap in my window"; read RISK_LEVEL_UNKNOWN as "no risk grade available", not as a good or bad outcome.
A known age_band together with swapped: false is not a contradiction: it means the carrier dated the last swap and it fell outside the window. The flag is the band overlapped with the window, and a band straddling the boundary resolves to swapped rather than to an unknown — so with a 24-hour window a "14-30 days" band gives swapped: false alongside RISK_LEVEL_MEDIUM, because risk comes from the band's own recency, not from the window.
const s = result.sim_swap;
if (s?.checked) {
if (s.swapped === undefined) {
// carrier could not determine an age for this window
} else if (s.swapped) {
console.log(`SIM swapped within ${s.max_age_hours}h (${s.age_band})`);
}
}
biometric_verification
biometric_verification is on every success response, typed as BiometricVerification.
| Value | Meaning |
|---|---|
VERIFIED | The device performed biometric verification. |
FAILED | The device attempted it and reported a failure. |
NOT_ENROLLED | No biometric is enrolled on the device. |
UNSUPPORTED | Biometric was requested but no usable result came back. |
NOT_REQUESTED | Nothing to report. |
On verify it equals the signed record's biometric_verification claim. Values outside this list are kept as sent, so treat anything unrecognised as "no useful signal". It is a signal, not an authentication result — the phone number is verified either way.
reportInvocation(sessionId: string): Promise<ReportInvocationResponse>
Reports when a user clicks the authenticate button (for analytics).
await client.reportInvocation(sessionId);
checkStatus(sessionKey: string): Promise<StatusResponse>
Polls for verification status (authenticated endpoint).
const status = await client.checkStatus(sessionKey);
switch (status.status) {
case 'pending':
// Continue polling
break;
case 'scanned':
// QR code scanned, show device info
console.log(status.device_info);
break;
case 'completed':
// Verification complete
console.log(status.phone_number);
break;
case 'failed':
// Verification failed
console.log(status.error);
break;
}
checkStatusPublic(sessionKey: string): Promise<StatusResponse>
Polls for verification status (public endpoint, no auth required).
// Safe to use from browser without exposing credentials
const status = await client.checkStatusPublic(sessionKey);
invalidateToken(): void
Forces a token refresh on the next request.
client.invalidateToken();
Error Handling
All API errors are thrown as typed exceptions:
import {
MagicalAuthError,
ValidationError,
UnauthorizedError,
SessionNotFoundError,
CarrierNotEligibleError,
CarrierRejectedError,
CarrierAppUnavailableError,
RateLimitError,
} from '@glideidentity/glide-be-node-magical-auth';
try {
await client.prepare({ ... });
} catch (error) {
if (error instanceof ValidationError) {
console.log('Validation errors:', error.fieldErrors);
} else if (error instanceof CarrierNotEligibleError) {
console.log('Carrier not supported');
} else if (error instanceof CarrierRejectedError) {
// Carrier rejected a device-bound (link/desktop) auth
console.log('Carrier rejected:', error.details?.carrier_error, error.details?.stage);
} else if (error instanceof CarrierAppUnavailableError) {
// Desktop (QR): the scanning phone has no working carrier app; terminal, start a new QR
console.log('Carrier app unavailable; start a new QR flow');
} else if (error instanceof RateLimitError) {
console.log('Rate limited, retry after:', error.retryAfter);
} else if (error instanceof MagicalAuthError) {
console.log('API error:', error.code, error.message);
console.log('Request ID:', error.requestId);
}
}
The typed error classes are not exhaustive
The classes above cover the codes worth branching on today; the API can return codes that have no
class. specs/openapi.yaml currently documents TOKEN_ACQUISITION_FAILED, INVALID_PARAMETERS,
UNPROCESSABLE_ENTITY, UNEXPECTED_ERROR and COMPLETION_REDIRECT_URL_NOT_REGISTERED, none of
which map to a typed class. They arrive as a base MagicalAuthError carrying the raw code, so
always keep the instanceof MagicalAuthError fallback last and read error.code from it rather
than assuming the specific classes are total.
The edge can also answer 401 and 429 with a text/plain body rather than the JSON error
envelope. The client only parses JSON, so those surface as code: 'UNKNOWN_ERROR' with the status
preserved — branch on error.status for those two rather than on error.code.
Custom HTTP Client (BYOC)
import type { HttpClient } from '@glideidentity/glide-be-node-magical-auth';
const customHttpClient: HttpClient = {
async request(options) {
// Your custom implementation
const response = await myHttpLibrary.request({
method: options.method,
url: options.url,
headers: options.headers,
body: options.body,
});
return response;
},
};
const client = new MagicalAuthClient({
clientId: '...',
clientSecret: '...',
httpClient: customHttpClient,
});
Custom Logger (BYOL)
import type { Logger } from '@glideidentity/glide-be-node-magical-auth';
const customLogger: Logger = {
debug(message, meta) { console.debug(message, meta); },
info(message, meta) { console.info(message, meta); },
warn(message, meta) { console.warn(message, meta); },
error(message, meta) { console.error(message, meta); },
};
const client = new MagicalAuthClient({
clientId: '...',
clientSecret: '...',
logger: customLogger,
});
Built-in Console Logger
For local development and quick smoke tests, the SDK ships a default-silent console logger with PII sanitization and a [GlideMagicalAuth] prefix:
import { MagicalAuthClient, createLogger } from '@glideidentity/glide-be-node-magical-auth';
const client = new MagicalAuthClient({
clientId: process.env.GLIDE_CLIENT_ID!,
clientSecret: process.env.GLIDE_CLIENT_SECRET!,
logger: createLogger({ debug: true }),
});
Sample output:
[GlideMagicalAuth] Preparing auth { use_case: 'VerifyPhoneNumber' }
[GlideMagicalAuth] Refreshing access token
[GlideMagicalAuth] Auth prepared { strategy: 'ts43', session_key: 'a1b2c3d4e5f6a7b8' }
[GlideMagicalAuth] Phone number retrieved { phone: '+141***1234' }
Phone numbers, JWTs, and explicit session_key=… values are auto-masked; fields named phone_number, credential, token, password, secret, or fe_code are redacted to [REDACTED]. The default is silent (createLogger() with no args), so the SDK stays quiet in production unless you explicitly opt in. For Pino, Winston, or other structured loggers, prefer the BYOL pattern above.
Authentication Strategies
The Magical Auth backend selects one of three strategies per session, based on the carrier and the end user's device. Your application code branches on prepareResponse.authentication_strategy.
TS43
Direct credential request via the Digital Credentials API. Available in supported browsers and natively on Android via Credential Manager. Selected when the user's device exposes a compatible credential surface.
Link
OAuth-style redirect flow on mobile. The SDK returns a redirect URL; your application sends the user to it and the carrier completes authentication out-of-band.
Desktop
QR-code-based flow for desktop browsers. The SDK returns a single universal QR; the Glide mobile companion app detects the device at runtime and selects the appropriate strategy when the QR is scanned.
TypeScript Support
This SDK is written in TypeScript and provides full type definitions.
Recommended: Separate Type Imports
// Runtime imports
import { MagicalAuthClient } from '@glideidentity/glide-be-node-magical-auth';
// Type-only imports (clean separation)
import type {
PrepareRequest,
PrepareResponse,
VerifyPhoneNumberRequest,
VerifyPhoneNumberResponse,
StatusResponse,
UseCase,
AuthenticationStrategy,
} from '@glideidentity/glide-be-node-magical-auth/types';
Alternative: Import from Main Entry
import { MagicalAuthClient } from '@glideidentity/glide-be-node-magical-auth';
import type { PrepareRequest, PrepareResponse } from '@glideidentity/glide-be-node-magical-auth';
License
Distributed under the Apache License 2.0 — see LICENSE.