@authspherejs/sdk
v1.1.3
Published
Secure OAuth2 SDK with PKCE for AuthSphere authentication
Maintainers
Readme
🌐 AuthSphere SDK
The ultimate TypeScript engine for secure, enterprise-grade authentication.
✨ Features
📺 Demo
🚀 Installation
Install the package via your favorite package manager:
# npm
npm install @authspherejs/sdk
# pnpm
pnpm add @authspherejs/sdk
# yarn
yarn add @authspherejs/sdk🛠️ Quick Start
1️⃣ Initialize the SDK
Initialize the client at the root of your application (e.g., in main.ts or App.tsx).
import AuthSphere from "@authspherejs/sdk";
AuthSphere.initAuth({
publicKey: "your_project_public_key",
redirectUri: "http://localhost:3000/callback",
baseUrl: "https://api.authsphere.dev", // Your AuthSphere backend URL
});2️⃣ Trigger Login
Redirect users to their preferred OAuth provider with a single function call.
// Support for 'google', 'github', 'discord'
const login = (provider: "google" | "github" | "discord") => {
AuthSphere.redirectToLogin(provider);
};3️⃣ Handle Callback
Create a route for your redirectUri (e.g., /callback) to process the exchange.
async function handleCallback() {
try {
const session = await AuthSphere.handleAuthCallback();
console.log("User signed in:", session.user);
window.location.href = "/dashboard";
} catch (error) {
console.error("Authentication failed:", error);
}
}4️⃣ Local Authentication & Identity Challenges
For apps requiring custom signup flows with email verification. The SDK handles the heavy lifting of state preservation across redirects.
// 1. Register User
await AuthSphere.register({
email: "[email protected]",
password: "Password123!",
username: "Madhav",
});
// 2. Login Attempt
try {
const session = await AuthSphere.loginLocal({ email, password });
// If verified, session is established immediately
} catch (err) {
if (err.error_code === "EMAIL_NOT_VERIFIED") {
// Navigator to your verification UI
// The 'sdk_request' preserves the original OIDC context
const { sdk_request } = err.metadata;
navigate(`/verify?email=${email}&sdk_request=${sdk_request}`);
}
}
// 3. Verify Challenge (OTP)
// On success, the SDK automatically resolves the pending login
await AuthSphere.verifyOTP({
email: "[email protected]",
otp: "123456",
sdk_request: "...", // Pass the ID from the login error meta
});📖 API Reference
initAuth(config: Config)
Initializes the SDK with your project settings.
redirectToLogin(provider: Provider)
Initiates the OAuth2 PKCE flow for the specified provider.
handleAuthCallback()
Exchanges the authorization code for a session token. Returns a Promise<Session>.
register(data: RegisterData)
Registers a new user and triggers the verification email.
loginLocal(data: LoginData)
Authenticates with email/password. Throws AuthError if verification is required.
verifyOTP(data: OTPData)
Verifies a 6-digit code. Can perform an automatic login if sdk_request is provided.
resendVerification(email: string)
Requests a new 6-digit verification code for the specified email.
isAuthenticated()
Checks if a valid session exists in storage.
getUser()
Returns the profile information of the currently logged-in user.
logout()
Clears the session data and terminates the user session.
🔧 Configuration Options
| Option | Type | Required | Description |
| :------------ | :--------- | :------: | :------------------------------------------------------ |
| publicKey | string | Yes | Your project's Identification Key from the dashboard. |
| redirectUri | string | Yes | The URI your app redirects back to after auth. |
| baseUrl | string | No | Your API server URL (Default: http://localhost:8000). |
| onAuthError | Function | No | Global hook for handling authentication errors. |
🛡️ Security Note
AuthSphere implements the Authorization Code Flow with PKCE, the gold standard for securing public clients (SPAs/Mobile Apps).
[!IMPORTANT] This flow ensures that even if an authorization code is intercepted, it cannot be exchanged for a token without the original client's cryptographically generated "code verifier".
📄 License
Distributed under the MIT License. See LICENSE for more information.
