Docs/Account SDK

Account SDK

Universal Developer

Account SDK

Overview

Account SDK provides user information, subscription status, and quota management capabilities for plugins that need to offer differentiated features based on user identity or subscription tier.

Introduction

Quick Start

EXAMPLE.TS
import { accountSDK, SubscriptionPlan } from '@talex-touch/utils'
import { useChannel } from '@talex-touch/utils/plugin/sdk'

accountSDK.setChannelSend(useChannel().send)

// Check if user is logged in
const isLoggedIn = await accountSDK.isLoggedIn()

// Get current subscription plan
const plan = await accountSDK.getPlan()

// Check if paid user
if (await accountSDK.isPaidUser()) {
  // Show premium features
}

Subscription Plans

Listed from the lowest tier to the highest; each includes everything in the ones before it.

PlanEnum ValueDescription
FreeSubscriptionPlan.FREEBasic features with quota limits
PlusSubscriptionPlan.PLUSMore quota, custom models, priority support
ProSubscriptionPlan.PROHigher quota, advanced analytics
TeamSubscriptionPlan.TEAMTeam collaboration, management
EnterpriseSubscriptionPlan.ENTERPRISEHighest quota, more team seats

SDK Reference

Get SDK Instance

Account calls work only in a plugin's pages; the Prelude script (index.js) cannot reach them. accountSDK is a singleton: give it the page's channel before using it.

EXAMPLE.TS
import { accountSDK } from '@talex-touch/utils'
import { useChannel } from '@talex-touch/utils/plugin/sdk'

accountSDK.setChannelSend(useChannel().send)
await accountSDK.getProfile()

A plugin uses these methods, opening the sign-in and account pages included, only after it declares account.read in manifest.json and the user grants it. Without the grant, usePluginAccount() calls reject with ACCOUNT_PERMISSION_DENIED and onDidChange never calls back; accountSDK reads its queries as "none", and its page openers reject. See Permission System.

EXAMPLE.JSON
{
  "permissions": {
    "required": ["account.read"]
  },
  "permissionReasons": {
    "account.read": "Shows your plan and the quota you have left"
  }
}

Note: accountSDK reads a failed call as "none": getProfile() returns null and isLoggedIn() returns false. To tell signing out from a failed call, or to hear when the sign-in changes, use usePluginAccount() below.


Following the Sign-in

usePluginAccount() is the account client for plugin pages. Its calls reject when they fail instead of reading as signed out, and onDidChange tells the plugin when the sign-in changes.

EXAMPLE.TS
import { usePluginAccount } from '@talex-touch/utils/plugin/sdk'

const account = usePluginAccount()

const stop = account.onDidChange((session) => {
  // The stored sign-in has not been checked in this run yet, so "signed out" may still turn signed in
  if (!session.isSettled)
    return
  renderUser(session.user) // null when signed out
})

// When the page unmounts
stop()
MethodReturnDescription
getProfile()UserProfile | nullThe signed-in account's profile, null when signed out
getSubscription()Subscription | nullSubscription
getUsage()UsageStats | nullUsage
getFeatures()FeatureFlag[]The plan's features: aiRequests and aiTokens carry their limit in value (-1 for unlimited); customModels, prioritySupport and apiAccess are on or off
getTeams()Team[]The organization the account belongs to, empty when there is none; the personal team is not listed
openUpgradePage(plan?)voidOpens the pricing page in the browser, with plan outlined when given
openBillingPage()voidOpens the team page, where the plan and activation codes are managed
openAccountSettings(), openProfileEditor()voidOpens the account page
requestLogin()booleanJoins the sign-in when the app is signed in or a sign-in is under way, and opens the sign-in page otherwise. true does not mean anyone is signed in yet; false means the page could not be opened
onDidChange(callback)() => voidCalls back once with the current state, then after every change; returns a function that stops it

The state onDidChange receives (AccountSessionState):

FieldTypeDescription
isSettledbooleanThe stored sign-in has been checked in this run. While false, signed out does not mean the account signed out
isSignedInbooleanSigned in
user{ id: string, name?: string } | nullThe signed-in account, null when signed out

The state carries no credential and no email, and a change to details it does not carry does not call back.


Auth Token & Device

What Tuff itself uses to reach the account service. Plugins receive neither the credential nor the device ID; in a plugin these return null.

EXAMPLE.TS
const token = await accountSDK.getAuthToken()
const deviceId = await accountSDK.getDeviceId()
MethodReturnDescription
getAuthToken()string | nullBearer auth token (null if unavailable)
getDeviceId()string | nullCurrent device id (null if unavailable)

User Information

getProfile()

Get complete user profile.

EXAMPLE.TS
const profile = await accountSDK.getProfile()
// {
//   id: 'user_xxx',
//   displayName: 'John Doe',
//   email: 'john@example.com',
//   avatarUrl: 'https://...',
//   emailVerified: true,
//   createdAt: 1702123456789,
//   twoFactorEnabled: false,
//   socialConnections: [...]
// }
ReturnTypeDescription
profileUserProfile | nullUser profile, null if not logged in

isLoggedIn()

Check if user is logged in.

EXAMPLE.TS
if (await accountSDK.isLoggedIn()) {
  // Logged in
}

getUserId()

Get user ID.

EXAMPLE.TS
const userId = await accountSDK.getUserId()
// 'user_xxx' or null

getDisplayName()

Get display name.

EXAMPLE.TS
const name = await accountSDK.getDisplayName()
// 'John Doe'

getEmail()

Get user email.

EXAMPLE.TS
const email = await accountSDK.getEmail()
// 'john@example.com'

getAvatarUrl()

Get avatar URL.

EXAMPLE.TS
const avatar = await accountSDK.getAvatarUrl()
// 'https://...'

Subscription Checks

getPlan()

Get current subscription plan.

EXAMPLE.TS
const plan = await accountSDK.getPlan()
// SubscriptionPlan.PRO

getSubscription()

Get full subscription details.

EXAMPLE.TS
const subscription = await accountSDK.getSubscription()
// {
//   id: 'sub_xxx',
//   plan: 'pro',
//   status: 'active',
//   billingCycle: 'monthly',
//   quota: { aiRequestsPerWeek: 2000, ... },
//   usage: { aiRequestsThisWeek: 123, ... },
//   currentPeriodEnd: 1704067200000,
//   autoRenew: true
// }

isPaidUser()

Check if user is a paid subscriber.

EXAMPLE.TS
if (await accountSDK.isPaidUser()) {
  // Show paid features
}

isProOrAbove()

Check if Pro tier or higher.

EXAMPLE.TS
if (await accountSDK.isProOrAbove()) {
  // Pro / Team / Enterprise
}

isPlusOrAbove()

Check if Plus tier or higher.

EXAMPLE.TS
if (await accountSDK.isPlusOrAbove()) {
  // Plus / Pro / Team / Enterprise
}

isTeamOrAbove()

Check if Team tier or higher.

EXAMPLE.TS
if (await accountSDK.isTeamOrAbove()) {
  // Team / Enterprise
}

isEnterprise()

Check if Enterprise tier.

EXAMPLE.TS
if (await accountSDK.isEnterprise()) {
  // Enterprise only
}

isTrialing()

Check if in trial period.

EXAMPLE.TS
if (await accountSDK.isTrialing()) {
  const days = await accountSDK.getTrialDaysRemaining()
  console.log(`Trial ends in ${days} days`)
}

getDaysRemaining()

Get days remaining in current billing period.

EXAMPLE.TS
const days = await accountSDK.getDaysRemaining()
// 28

Quota Checks

getQuota()

Get current plan quota limits. AI requests and tokens are counted per week, restarting on Monday at 00:00 UTC as Nexus does; -1 means unlimited. aiRequestsPerDay and aiTokensPerMonth are deprecated and carry the same weekly numbers.

EXAMPLE.TS
const quota = await accountSDK.getQuota()
// {
//   aiRequestsPerWeek: 500,
//   aiTokensPerWeek: 100000,
//   maxPlugins: 20,
//   maxStorageBytes: 1073741824,
//   customModelAccess: true,
//   apiAccess: true,
//   ...
// }

getUsage()

Get current usage statistics. AI usage covers the current week; aiRequestsToday, aiRequestsThisMonth and aiTokensThisMonth are deprecated and carry this week's numbers too.

EXAMPLE.TS
const usage = await accountSDK.getUsage()
// {
//   aiRequestsThisWeek: 123,
//   aiTokensThisWeek: 45678,
//   storageUsedBytes: 52428800,
//   pluginsInstalled: 8
// }

checkAiRequestQuota()

Check this week's AI request quota. When it runs out, resetAt is next Monday at 00:00 UTC.

EXAMPLE.TS
const result = await accountSDK.checkAiRequestQuota()
if (!result.allowed) {
  console.log(result.reason) // 'Weekly AI request limit reached'
  console.log(`Resets at: ${new Date(result.resetAt)}`)
} else {
  console.log(`Remaining: ${result.remaining}`)
}

checkAiTokenQuota(estimatedTokens)

Check this week's AI token quota.

EXAMPLE.TS
const result = await accountSDK.checkAiTokenQuota(1000)
if (!result.allowed) {
  // Quota exceeded
}
ParameterTypeDescription
estimatedTokensnumberEstimated tokens to consume (optional, default 0)

checkStorageQuota(additionalBytes)

Check storage quota.

EXAMPLE.TS
const result = await accountSDK.checkStorageQuota(1024 * 1024) // 1MB
if (!result.allowed) {
  console.log('Insufficient storage')
}

checkPluginQuota()

Check plugin installation quota.

EXAMPLE.TS
const result = await accountSDK.checkPluginQuota()
if (!result.allowed) {
  console.log('Plugin limit reached')
}

getUsagePercentage(type)

Get usage percentage for specific quota type.

EXAMPLE.TS
const aiUsage = await accountSDK.getUsagePercentage('aiRequests')
console.log(`AI usage: ${aiUsage.toFixed(1)}%`)

const storageUsage = await accountSDK.getUsagePercentage('storage')
if (storageUsage > 80) {
  console.warn('Storage running low')
}
ParameterTypeValues
typestring'aiRequests', 'aiTokens', 'storage', 'plugins'

Feature Access

hasApiAccess()

Check if user has API access.

EXAMPLE.TS
if (await accountSDK.hasApiAccess()) {
  // Allow API usage
}

hasCustomModelAccess()

Check if user can use custom models.

EXAMPLE.TS
if (await accountSDK.hasCustomModelAccess()) {
  // Show custom model options
}

hasPrioritySupport()

Check if user has priority support.

EXAMPLE.TS
if (await accountSDK.hasPrioritySupport()) {
  // Show priority support entry
}

hasAdvancedAnalytics()

Check if user has advanced analytics.

EXAMPLE.TS
if (await accountSDK.hasAdvancedAnalytics()) {
  // Show analytics dashboard
}

hasFeature(featureId)

Check if specific feature flag is enabled.

EXAMPLE.TS
if (await accountSDK.hasFeature('beta-ai-v2')) {
  // Enable beta feature
}

Team Management

getTeams()

Gets the organization the account belongs to, at most one; the personal team every account has is not listed. The account service reports no slug or creation time, so slug is the id and createdAt is 0.

EXAMPLE.TS
const teams = await accountSDK.getTeams()
// [
//   { id: 'team_xxx', name: 'Dev Team', slug: 'team_xxx', role: 'admin', memberCount: 5, createdAt: 0 }
// ]

isInTeam()

Check if user is in any team.

EXAMPLE.TS
if (await accountSDK.isInTeam()) {
  // Show team features
}

isTeamOwner(teamId?)

Check if user is team owner.

EXAMPLE.TS
if (await accountSDK.isTeamOwner()) {
  // User owns some team
}

if (await accountSDK.isTeamOwner('team_xxx')) {
  // User owns specific team
}

isTeamAdmin(teamId?)

Check if user is team admin (includes owner).

EXAMPLE.TS
if (await accountSDK.isTeamAdmin()) {
  // Show admin features
}

Upgrade & Billing

getUpgradeOptions()

Get available upgrade options. They carry no price: Tuff is free during its Pioneer period, and the price fields stay unset until Nexus publishes a price.

EXAMPLE.TS
const options = accountSDK.getUpgradeOptions()
// [
//   { plan: 'plus', name: 'Plus', features: ['500 AI requests/week', ...] },
//   { plan: 'pro', name: 'Pro', recommended: true, ... },
//   { plan: 'team', name: 'Team', ... }
// ]

getPlanComparison()

Get plan comparison table.

EXAMPLE.TS
const comparison = accountSDK.getPlanComparison()
// [
//   { feature: 'AI Requests/Week', free: 50, plus: 500, pro: 2000, ... },
//   { feature: 'Custom Models', free: false, plus: true, ... }
// ]

openUpgradePage(plan?)

Opens the pricing page in the browser. Given a plan, the pricing page outlines that plan's card.

EXAMPLE.TS
await accountSDK.openUpgradePage() // Open the pricing page
await accountSDK.openUpgradePage(SubscriptionPlan.PLUS) // Open the pricing page with Plus outlined

openBillingPage()

Opens the team page, where the plan and activation codes are managed.

EXAMPLE.TS
await accountSDK.openBillingPage()

Account Actions

requestLogin()

Asks the user to sign in. When the app is already signed in, or a sign-in is already under way, no new page opens and that sign-in is joined; otherwise the sign-in page opens in the browser. All of those return true, possibly before anyone has signed in; false means the page could not be opened. The result arrives through usePluginAccount().onDidChange.

EXAMPLE.TS
await accountSDK.requestLogin()
// Once the user signs in in the browser, onDidChange receives isSignedIn: true

logout()

Logout current user. Only Tuff itself can call it; in a plugin it rejects.

EXAMPLE.TS
await accountSDK.logout()

openAccountSettings()

Opens the account page, which holds the settings and the profile.

EXAMPLE.TS
await accountSDK.openAccountSettings()

Technical Notes

  • Account SDK reads login state, subscription plan, and quota from the unified account service.
  • Client-side helpers consolidate permission and quota checks to avoid scattered logic.

Best Practices

1. Premium Feature Gating

EXAMPLE.TS
async function showPremiumFeature() {
  if (!await accountSDK.isPaidUser()) {
    // Show upgrade prompt
    const options = accountSDK.getUpgradeOptions()
    showUpgradeDialog(options)
    return
  }

  // Show premium feature
}

2. Quota Pre-check

EXAMPLE.TS
async function beforeAiRequest(estimatedTokens: number) {
  const quotaCheck = await accountSDK.checkAiTokenQuota(estimatedTokens)

  if (!quotaCheck.allowed) {
    throw new Error(`Quota exceeded: ${quotaCheck.reason}`)
  }

  // Proceed with request
}

3. Team Feature Adaptation

EXAMPLE.TS
async function initTeamFeatures() {
  if (!await accountSDK.isTeamOrAbove()) {
    return // Not team tier, skip
  }

  const teams = await accountSDK.getTeams()

  for (const team of teams) {
    if (team.role === 'owner' || team.role === 'admin') {
      // Show admin features
    }
  }
}

Type Definitions

EXAMPLE.TS
enum SubscriptionPlan {
  FREE = 'free',
  PLUS = 'plus',
  PRO = 'pro',
  TEAM = 'team',
  ENTERPRISE = 'enterprise',
}

interface UserProfile {
  id: string
  displayName: string
  username?: string
  email: string
  emailVerified: boolean
  avatarUrl?: string
  createdAt: number
  twoFactorEnabled: boolean
  socialConnections: SocialConnection[]
}

interface Subscription {
  id: string
  plan: SubscriptionPlan
  status: SubscriptionStatus
  quota: PlanQuota
  usage: UsageStats
  currentPeriodEnd: number
  autoRenew: boolean
}

interface QuotaCheckResult {
  allowed: boolean
  reason?: string
  remaining?: number
  resetAt?: number
}

interface AccountSessionState {
  isSettled: boolean
  isSignedIn: boolean
  user: { id: string, name?: string } | null
}