npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@shogun-sdk/accounts

v1.0.23

Published

Shogun with Turnkey: configs, encryption, authentication with Telegram/Turnkey OIDC, etc.

Readme

@shogun-sdk/accounts

TypeScript SDK for Turnkey wallet infrastructure - authentication, wallet creation, and transaction signing.

Quick Start

1. Install the Package

Choose your preferred package manager:

npm

npm install @shogun-sdk/accounts

pnpm

pnpm add @shogun-sdk/accounts

yarn

yarn add @shogun-sdk/accounts

2. Configure and Use

Set up Turnkey configuration and start creating wallets:

import { getTurnkeyConfig, createUserSubOrg } from '@shogun-sdk/accounts';

// Configure Turnkey
const config = getTurnkeyConfig(
  'https://api.turnkey.com',  // API base URL
  'your-organization-id',     // Your organization ID
  'your-rp-id'               // Relying Party ID for WebAuthn
);

// Create user sub-organization
const subOrg = await createUserSubOrg({
  config,
  email: '[email protected]',
  username: 'user123',
  passkey: {
    challenge: 'webauthn-challenge',
    attestation: attestationObject
  }
});

console.log('Created sub-org:', subOrg);

3. Explore All Features

Check the Usage Examples and API Reference below for authentication, wallet management, and advanced features.

Features

  • 🔐 Multi-Auth Support - Passkeys, OAuth, email-based authentication
  • 💼 Wallet Management - Create and manage Ethereum and Solana wallets
  • 🏢 Sub-Organizations - Isolated user environments
  • 🔑 API Key Management - Secure key generation and management
  • 📱 Telegram Integration - Built-in Telegram authentication
  • 🛡️ Security First - Industry-standard security practices
  • 📝 TypeScript Ready - Full type safety and IntelliSense

Usage Examples

User Authentication

OAuth Authentication

import { oauth } from '@shogun-sdk/accounts';

const authResponse = await oauth({
  credential: 'oidc-token',
  targetPublicKey: 'user-public-key',
  targetSubOrgId: 'sub-org-id',
  config
});

console.log('OAuth successful:', authResponse);

Passkey Authentication

import { createUserSubOrg } from '@shogun-sdk/accounts';

// Create user with passkey
const subOrg = await createUserSubOrg({
  config,
  email: '[email protected]',
  username: 'user123',
  passkey: {
    challenge: 'webauthn-challenge',
    attestation: attestationObject
  }
});

Wallet Operations

Get User Wallets

import { getWalletsWithAccounts } from '@shogun-sdk/accounts';

const wallets = await getWalletsWithAccounts(config, 'organization-id');
console.log('User wallets:', wallets);

// Example response:
// [
//   {
//     walletId: 'wallet-123',
//     accounts: [
//       { address: '0x...', curve: 'secp256k1', chainType: 'ethereum' },
//       { address: 'ABC...', curve: 'ed25519', chainType: 'solana' }
//     ]
//   }
// ]

Find Sub-Organization

import { getSubOrgIdByEmail, getSubOrgId } from '@shogun-sdk/accounts';

// Find by email
const subOrgId = await getSubOrgIdByEmail(config, '[email protected]');

// Find by various parameters
const subOrgById = await getSubOrgId(config, {
  email: '[email protected]',
  username: 'user123',
  publicKey: 'public-key-hex',
  oidcToken: 'oidc-token'
});

Client-Side Utilities

Local Storage with Expiration

import { setItemWithExpiry, getItemWithExpiry } from '@shogun-sdk/accounts';

// Store data with 1 hour expiration
setItemWithExpiry('userSession', { userId: '123', token: 'abc' }, 3600000);

// Retrieve data (returns null if expired)
const session = getItemWithExpiry('userSession');
if (session) {
  console.log('Valid session:', session);
} else {
  console.log('Session expired or not found');
}

Public Key Operations

import { getPublicKeyFromPrivateKeyHex } from '@shogun-sdk/accounts';

const publicKey = getPublicKeyFromPrivateKeyHex('private-key-hex');
console.log('Derived public key:', publicKey);

Integration Examples

React Integration

import { useTurnkey } from '@turnkey/sdk-react';
import { getTurnkeyConfig } from '@shogun-sdk/accounts';

function WalletComponent() {
  const config = getTurnkeyConfig(
    process.env.REACT_APP_TURNKEY_API_URL!,
    process.env.REACT_APP_TURNKEY_ORG_ID!,
    process.env.REACT_APP_TURNKEY_RP_ID!
  );
  
  const { turnkey } = useTurnkey({ config });
  
  return (
    <div>
      <h2>Wallet Management</h2>
      {/* Your wallet UI here */}
    </div>
  );
}

Server-Side Integration

import { TurnkeyServerClient } from '@turnkey/sdk-server';
import { ApiKeyStamper } from '@turnkey/sdk-server';

const stamper = new ApiKeyStamper({
  apiPublicKey: process.env.TURNKEY_API_PUBLIC_KEY!,
  apiPrivateKey: process.env.TURNKEY_API_PRIVATE_KEY!,
});

const client = new TurnkeyServerClient({
  apiBaseUrl: 'https://api.turnkey.com',
  organizationId: process.env.TURNKEY_ORG_ID!,
  stamper,
});

// Use client for server-side operations
const wallets = await client.getWallets({
  organizationId: 'user-sub-org-id'
});

API Reference

Core Functions

getTurnkeyConfig(apiUrl, orgId, rpId)

Initialize Turnkey configuration.

Parameters:

  • apiUrl: Turnkey API base URL
  • orgId: Your organization ID
  • rpId: Relying Party ID for WebAuthn

Returns: Turnkey configuration object

createUserSubOrg(options)

Creates a new user sub-organization with optional authentication methods.

Parameters:

  • config: Turnkey configuration object
  • username?: Optional username
  • email?: User email address
  • passkey?: WebAuthn passkey configuration
  • oauth?: OAuth provider configuration
  • wallet?: Wallet configuration

Returns: Created sub-organization details

oauth(options)

Performs OAuth authentication flow.

Parameters:

  • credential: OIDC token
  • targetPublicKey: Target public key
  • targetSubOrgId: Sub-organization ID
  • config: Turnkey configuration

Returns: Authentication response

getWalletsWithAccounts(config, organizationId)

Retrieves all wallets and accounts for an organization.

Parameters:

  • config: Turnkey configuration
  • organizationId: Organization ID to query

Returns: Array of wallets with their accounts

getSubOrgId(config, param)

Finds sub-organization ID by various parameters.

Parameters:

  • config: Turnkey configuration
  • param: Search parameters (email, username, publicKey, or oidcToken)

Returns: Sub-organization ID or null

Authentication Methods

The SDK supports multiple authentication flows:

1. Passkeys (WebAuthn)

// Secure, passwordless authentication
const subOrg = await createUserSubOrg({
  config,
  email: '[email protected]',
  passkey: {
    challenge: 'challenge-string',
    attestation: attestationObject
  }
});

2. OAuth Providers

// Google, GitHub, and other OAuth providers
const authResult = await oauth({
  credential: 'google-oidc-token',
  targetPublicKey: 'user-public-key',
  targetSubOrgId: 'sub-org-id',
  config
});

3. Email Recovery

// Email-based account recovery
const recovery = await initiateEmailRecovery({
  email: '[email protected]',
  config
});

4. API Keys

// For programmatic access
const apiKey = await createApiKey({
  subOrgId: 'user-sub-org',
  keyName: 'my-api-key',
  config
});

Supported Wallet Types

Ethereum Wallets

// Secp256k1 curve, compatible with all EVM chains
const ethWallet = {
  curve: 'secp256k1',
  chainType: 'ethereum',
  address: '0x...' // Ethereum address format
};

Solana Wallets

// Ed25519 curve, native Solana support
const solWallet = {
  curve: 'ed25519', 
  chainType: 'solana',
  address: 'ABC...' // Base58 Solana address format
};

Error Handling

The SDK includes comprehensive error handling:

import { TurnkeyError } from '@shogun-sdk/accounts';

try {
  const result = await createUserSubOrg({
    config,
    email: '[email protected]'
  });
} catch (error) {
  if (error instanceof TurnkeyError) {
    console.error('Turnkey error:', error.message);
    console.error('Error code:', error.code);
  } else {
    console.error('Unexpected error:', error);
  }
}

Security Best Practices

1. API Key Protection

// ❌ Never expose API keys in client-side code
const apiKey = 'your-api-key'; // DON'T DO THIS

// ✅ Use environment variables on server-side
const apiKey = process.env.TURNKEY_API_PRIVATE_KEY;

2. Private Key Security

// ✅ Private keys are managed by Turnkey infrastructure
// You never handle raw private keys directly
const wallets = await getWalletsWithAccounts(config, orgId);

3. Session Management

// ✅ Use appropriate session timeouts
setItemWithExpiry('session', data, 2 * 60 * 60 * 1000); // 2 hours

4. HTTPS Only

// ✅ Always use HTTPS in production
const config = getTurnkeyConfig(
  'https://api.turnkey.com', // Never use HTTP
  orgId,
  rpId
);

TypeScript Support

The SDK is fully typed with comprehensive TypeScript definitions:

import type { 
  ITurnkeyConfig, 
  Wallet, 
  Attestation, 
  OauthProviderParams,
  SubOrgParams,
  AuthResult
} from '@shogun-sdk/accounts';

interface CustomWalletConfig extends SubOrgParams {
  customField: string;
}

const createCustomWallet = async (config: CustomWalletConfig): Promise<AuthResult> => {
  // Your implementation with full type safety
};

Environment Variables

Client-Side (.env.local for Next.js)

NEXT_PUBLIC_TURNKEY_API_URL=https://api.turnkey.com
NEXT_PUBLIC_TURNKEY_ORG_ID=your-organization-id
NEXT_PUBLIC_TURNKEY_RP_ID=your-app-domain.com

Server-Side (.env)

TURNKEY_API_URL=https://api.turnkey.com
TURNKEY_ORG_ID=your-organization-id
TURNKEY_API_PUBLIC_KEY=your-api-public-key
TURNKEY_API_PRIVATE_KEY=your-api-private-key

Example Configuration

// Client-side configuration
const clientConfig = getTurnkeyConfig(
  process.env.NEXT_PUBLIC_TURNKEY_API_URL!,
  process.env.NEXT_PUBLIC_TURNKEY_ORG_ID!,
  process.env.NEXT_PUBLIC_TURNKEY_RP_ID!
);

// Server-side configuration  
const serverConfig = getTurnkeyConfig(
  process.env.TURNKEY_API_URL!,
  process.env.TURNKEY_ORG_ID!,
  process.env.TURNKEY_RP_ID!
);

Common Use Cases

1. User Onboarding with Passkey

async function onboardUser(email: string, username: string) {
  try {
    const subOrg = await createUserSubOrg({
      config,
      email,
      username,
      passkey: {
        challenge: generateChallenge(),
        attestation: await getPasskeyAttestation()
      }
    });
    
    console.log('User onboarded:', subOrg);
    return subOrg;
  } catch (error) {
    console.error('Onboarding failed:', error);
    throw error;
  }
}

2. Social Login Integration

async function handleGoogleLogin(googleToken: string) {
  try {
    const authResult = await oauth({
      credential: googleToken,
      targetPublicKey: await derivePublicKey(),
      targetSubOrgId: await findUserSubOrg(),
      config
    });
    
    return authResult;
  } catch (error) {
    console.error('Google login failed:', error);
    throw error;
  }
}

3. Wallet Recovery

async function recoverWallet(email: string) {
  try {
    const subOrgId = await getSubOrgIdByEmail(config, email);
    if (!subOrgId) {
      throw new Error('User not found');
    }
    
    const wallets = await getWalletsWithAccounts(config, subOrgId);
    return wallets;
  } catch (error) {
    console.error('Wallet recovery failed:', error);
    throw error;
  }
}

Support

Requirements

  • Turnkey Account: Visit Turnkey to create an account
  • Organization Setup: Configure your organization in Turnkey dashboard
  • HTTPS Environment: Required for WebAuthn/passkey functionality

License

ISC