CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-google-auth-library

Google APIs Authentication Client Library for Node.js providing OAuth2, JWT, and Application Default Credentials

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

crypto.mddocs/

Cryptographic Operations

Cryptographic utilities for signing, verification, and hashing operations. Provides both Node.js and browser-compatible implementations with automatic platform detection.

Capabilities

Crypto Factory

Factory functions for creating platform-appropriate crypto implementations.

/**
 * Create crypto implementation based on environment
 * Returns NodeCrypto for Node.js, BrowserCrypto for browsers
 */
function createCrypto(): Crypto;

/**
 * Check if browser crypto (Web Crypto API) is available
 * @returns true if window.crypto.subtle is available
 */
function hasBrowserCrypto(): boolean;

Usage Examples:

import { createCrypto, hasBrowserCrypto } from "google-auth-library";

// Create appropriate crypto implementation
const crypto = createCrypto();

// Check environment
if (hasBrowserCrypto()) {
  console.log('Running in browser with Web Crypto API');
} else {
  console.log('Running in Node.js with crypto module');
}

// Use crypto methods
const hash = await crypto.sha256DigestBase64('hello world');
const randomBytes = crypto.randomBytesBase64(32);

Crypto Interface

Main cryptographic interface providing hashing, signing, and encoding operations.

/**
 * Crypto interface providing cryptographic operations
 * Implemented by both NodeCrypto and BrowserCrypto
 */
interface Crypto {
  /** Decode base64 string to UTF-8 */
  decodeBase64StringUtf8(base64String: string): string;
  
  /** Encode UTF-8 string to base64 */
  encodeBase64StringUtf8(str: string): string;
  
  /** Create SHA-256 hash and return as base64 */
  sha256DigestBase64(str: string): Promise<string>;
  
  /** Generate random bytes and return as base64 */
  randomBytesBase64(count: number): string;
  
  /** Verify signature using public key */
  verify(pubkey: string, data: string, signature: string): Promise<boolean>;
  
  /** Sign data using private key */
  sign(privateKey: string, data: string): Promise<string>;
  
  /** Create hash instance for streaming operations */
  createHash(algorithm: string): Hash;
  
  /** Decode JWT payload without verification */
  decodeJwt(jwt: string): { header: any; payload: any; signature: string };
}

interface Hash {
  /** Update hash with data */
  update(data: string): Hash;
  
  /** Finalize hash and return digest */
  digest(encoding?: string): string;
}

Usage Examples:

import { createCrypto } from "google-auth-library";

const crypto = createCrypto();

// Hashing
const hash = await crypto.sha256DigestBase64('sensitive data');
console.log('SHA-256 hash:', hash);

// Base64 encoding/decoding
const encoded = crypto.encodeBase64StringUtf8('Hello, World!');
const decoded = crypto.decodeBase64StringUtf8(encoded);

// Random bytes generation
const randomData = crypto.randomBytesBase64(32); // 32 random bytes as base64

// Streaming hash
const hashStream = crypto.createHash('sha256');
hashStream.update('part 1');
hashStream.update('part 2');
const finalHash = hashStream.digest('base64');

// JWT decoding (header and payload only, no verification)
const jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...';
const { header, payload, signature } = crypto.decodeJwt(jwt);

Crypto Signer Interface

Interface for cryptographic signing operations.

/**
 * Interface for cryptographic signing
 */
interface CryptoSigner {
  /** Update signer with data */
  update(data: string): void;
  
  /** Sign accumulated data with private key */
  sign(key: string, outputFormat: string): string;
}

Digital Signature Operations

/**
 * Sign data using private key
 * @param privateKey - PEM-formatted private key
 * @param data - Data to sign
 * @returns Promise resolving to base64-encoded signature
 */
async function sign(privateKey: string, data: string): Promise<string>;

/**
 * Verify signature using public key
 * @param pubkey - PEM-formatted public key or certificate
 * @param data - Original data that was signed
 * @param signature - Base64-encoded signature to verify
 * @returns Promise resolving to true if signature is valid
 */
async function verify(pubkey: string, data: string, signature: string): Promise<boolean>;

Usage Examples:

import { createCrypto } from "google-auth-library";

const crypto = createCrypto();

// Sign data with private key
const privateKey = `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...
-----END PRIVATE KEY-----`;

const data = 'message to sign';
const signature = await crypto.sign(privateKey, data);

// Verify signature with public key
const publicKey = `-----BEGIN CERTIFICATE-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuGbXJXV...
-----END CERTIFICATE-----`;

const isValid = await crypto.verify(publicKey, data, signature);
console.log('Signature valid:', isValid);

AWS Request Signer

Utility for signing AWS requests when using AWS workload identity federation.

/**
 * AWS request signer for workload identity federation
 * Creates AWS Signature Version 4 signatures
 */
class AwsRequestSigner {
  constructor(options: AwsRequestSignerOptions);
  
  /** Get signed request headers */
  getRequestHeaders(
    host: string,
    canonicalUri: string,
    canonicalQuerystring: string,
    method: string,
    region: string,
    payload: string
  ): Promise<{ [key: string]: string }>;
}

interface AwsRequestSignerOptions {
  /** AWS access key ID */
  accessKeyId: string;
  /** AWS secret access key */
  secretAccessKey: string;
  /** AWS session token */
  sessionToken?: string;
  /** AWS service name */
  serviceName?: string;
}

interface AwsSecurityCredentials {
  /** AWS access key ID */
  accessKeyId: string;
  /** AWS secret access key */
  secretAccessKey: string;
  /** AWS session token */
  sessionToken?: string;
}

Platform-Specific Implementations

The library provides platform-specific crypto implementations:

Node.js Crypto

  • Uses Node.js built-in crypto module
  • Synchronous operations where possible
  • Full feature support

Browser Crypto

  • Uses Web Crypto API (window.crypto.subtle)
  • Asynchronous operations (returns Promises)
  • Limited to supported algorithms
/**
 * Node.js crypto implementation
 */
class NodeCrypto implements Crypto {
  // Implements all Crypto interface methods using Node.js crypto module
}

/**
 * Browser crypto implementation using Web Crypto API
 */
class BrowserCrypto implements Crypto {
  // Implements all Crypto interface methods using window.crypto.subtle
}

Certificate Operations

/**
 * Certificate storage and retrieval interface
 */
interface Certificates {
  [keyId: string]: string;
}

/**
 * Get Google's public certificates for ID token verification
 */
async function getFederatedSignonCerts(): Promise<Certificates>;

/**
 * Certificate subject token supplier for workload identity federation
 */
class CertificateSubjectTokenSupplier {
  constructor(options: CertificateSubjectTokenSupplierOptions);
  
  /** Get subject token from certificate */
  getSubjectToken(): Promise<string>;
}

interface CertificateSubjectTokenSupplierOptions {
  /** Certificate file path */
  certificateFilePath: string;
  /** Certificate password */
  certificatePassword?: string;
}

Utility Functions

/**
 * Format ECDSA signature for JWT use
 * @param signature - Raw ECDSA signature
 * @returns Formatted signature for JWT
 */
function formatEcdsa(signature: Buffer): string;

/**
 * Parse PEM-formatted key or certificate
 * @param pem - PEM string
 * @returns Parsed key data
 */
function parsePem(pem: string): { type: string; data: Buffer };

Error Handling

Common cryptographic operation errors:

  • Invalid key format: Private/public key is malformed or unsupported format
  • Signature verification failed: Signature doesn't match data and public key
  • Unsupported algorithm: Requested algorithm not supported in current environment
  • Certificate parsing error: Invalid certificate format
try {
  const crypto = createCrypto();
  const signature = await crypto.sign(privateKey, data);
} catch (error) {
  if (error.message.includes('Invalid key')) {
    console.error('Private key format is invalid or unsupported');
  } else if (error.message.includes('algorithm')) {
    console.error('Cryptographic algorithm not supported in this environment');
  }
}

try {
  const isValid = await crypto.verify(publicKey, data, signature);
} catch (error) {
  console.error('Signature verification failed:', error.message);
}

docs

adc.md

crypto.md

external-identity.md

index.md

oauth2.md

service-accounts.md

token-management.md

tile.json