@glideidentity/glide-be-node-magical-auth

中文文档
3.2.0发布于 2026/10/09Apache-2.0TypeScriptESM + CJS零依赖近 30 天下载 3788

Glide Magical Auth SDK for Node.js - Phone number authentication without SMS/OTP

原始使用文档
文档目录18 节
  1. Features
  2. Installation
  3. Requirements
  4. Quick Start
  5. API Reference
  6. MagicalAuthClient
  7. Error Handling
  8. Custom HTTP Client (BYOC)
  9. Custom Logger (BYOL)
  10. Built-in Console Logger
  11. Authentication Strategies
  12. TS43
  13. Link
  14. Desktop
  15. TypeScript Support
  16. Recommended: Separate Type Imports
  17. Alternative: Import from Main Entry
  18. License

@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)
OptionTypeRequiredDefaultDescription
clientIdstringYes-OAuth2 client ID
clientSecretstringYes-OAuth2 client secret
baseUrlstringNohttps://api.glideidentity.appAPI base URL
httpClientHttpClientNoNative fetchCustom HTTP client
loggerLoggerNoNo-opCustom logger
timeoutnumberNo30000Request 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
FieldTypeDescription
parent_session_idstringParent session for the desktop QR flow — set it on the companion/child prepare.
themeThemeUI theme forwarded verbatim to every touchpoint. "dark" / "light", or any custom identifier (max 32 chars).
link_typeLinkTypeOverrides link dispatch (app_clip, app_link, headless, web_link). Link strategy only.
network_originNetworkOriginThe 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_passthroughRecord<string, unknown>Opaque JSON forwarded to the branded companion app. Object only, ≤16 KB.
completion_redirect_urlstringWhere 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_hoursnumberSIM swap query window in hours. See below.
biometricbooleanOpt 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 MALFORMED before decoding.
  • The other codes (VerificationRecordErrorCode) are MALFORMED, DISALLOWED_HEADER, UNKNOWN_KEY, BAD_SIGNATURE, WRONG_ISSUER, WRONG_AUDIENCE (aud must equal the expected audience, default your client ID), EXPIRED, NOT_YET_VALID, NONCE_MISMATCH, ORIGIN_MISMATCH, UNSUPPORTED_VERSION and REVOKED_KEY. Every failure throws VerificationRecordError with status 0.
  • Claims that break the v1 contract fail with MALFORMED: ver must be the string "1.0" (otherwise UNSUPPORTED_VERSION), verified a boolean, jti, nonce and sub (tel:+E164) non-empty strings, nbf equal to iat, use_case exactly VerifyPhoneNumber, origin (canonical device origin, UNKNOWN on Link) and biometric_verification strings, exp 1 to 60 s after iat, and sign_offs an array of entries with non-empty role, signer and status (unavailable with a reason, or present with format and token), exactly one of them a carrier entry signed carrier:<id>. Optional strategy (TS_43, LINK, DESKTOP__TS_43, DESKTOP__LINK, DESKTOP), phone_number_details, carrier ({id, name, mvno}), sim_swap and device_swap are accepted when present; a wrong JSON type, a carrier without a non-empty string id, or a carrier.id that does not match the carrier sign-off signer (carrier:<id>), is MALFORMED. Record sim_swap / device_swap carry age_band {from, to} in hours (-1 unknown) and omit checked_at — iat is the authoritative check time.
  • Keys come only from <baseUrl>/.well-known/us/jwks.json (it carries both regions' record keys), cached per Cache-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 default maxAuditAgeSeconds); a record whose key has since been unpublished fails UNKNOWN_KEY, even with allowExpired.
  • Set expectedAudience to the record audience you configured in the developer portal (empty checks your client ID). To pin the device origin, set expectedOrigin (a list): the record's canonical origin must equal one entry exactly, else ORIGIN_MISMATCH; Link records carry UNKNOWN, so leave UNKNOWN out of the list to reject them.
  • To audit a stored record after exp, set allowExpired: true; iat must still be within maxAuditAgeSeconds (90 days by default) and revoked kids (revokedKids plus the built-in list) are always rejected. issuer overrides the expected iss (default: the base URL).
  • In v1 claims.sign_offs holds one carrier entry with status unavailable; signOffResults reports it as unavailable, and a present sign-off would be reported unverified, never trusted.
  • Integer claims follow JSON.parse, so 1.0 is 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
FieldTypeDescription
checkedbooleanWhether the check completed. When false, read reason and ignore the rest.
risk_levelRiskLevelRISK_LEVEL_HIGH | RISK_LEVEL_MEDIUM | RISK_LEVEL_LOW | RISK_LEVEL_UNKNOWN.
age_bandstringWhen 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_namestringThe carrier that performed the check.
checked_atstringWhen the check ran, RFC3339. Kept as a string — the SDK passes the wire value through without parsing.
swappedbooleanWhether 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_hoursnumberThe window this answer actually describes.
reasonSimSwapFailureReasonOnly 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.

ValueMeaning
VERIFIEDThe device performed biometric verification.
FAILEDThe device attempted it and reported a failure.
NOT_ENROLLEDNo biometric is enrolled on the device.
UNSUPPORTEDBiometric was requested but no usable result came back.
NOT_REQUESTEDNothing 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.

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.

// 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.

版本与发布记录

@glideidentity/glide-be-node-magical-auth 共发布 3 个版本,首次发布于 2026/05/18;过去 12 个月发布了 3 个版本。

版本发布日期距今
3.2.0latest2026/10/091 个月前
3.0.02026/06/085 个月前
2.0.02026/05/185 个月前

关于 @glideidentity/glide-be-node-magical-auth 的常见问题

@glideidentity/glide-be-node-magical-auth 是什么?

Glide Magical Auth SDK for Node.js - Phone number authentication without SMS/OTP

如何安装 @glideidentity/glide-be-node-magical-auth?

在项目目录运行 npm install @glideidentity/glide-be-node-magical-auth,或使用 pnpm add / yarn add / bun add。

@glideidentity/glide-be-node-magical-auth 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@glideidentity/glide-be-node-magical-auth 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@glideidentity/glide-be-node-magical-auth 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@glideidentity/glide-be-node-magical-auth 可以商用吗?

@glideidentity/glide-be-node-magical-auth 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@glideidentity/glide-be-node-magical-auth 的下载量有多少?

根据 npm 官方下载统计,@glideidentity/glide-be-node-magical-auth 在 2026/10/17 – 2026/11/15 这 30 天内被下载 3,788 次,日均约 126 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@glideidentity/glide-be-node-magical-auth 还在维护吗?

最新版本 3.2.0 发布于 2026/10/09(1 个月前);至今共发布 3 个版本,其中过去 12 个月发布了 3 个;首次发布于 2026/05/18。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。