{"_id":"@autolabz/oauth-app-sdk","name":"@autolabz/oauth-app-sdk","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@autolabz/oauth-app-sdk","version":"1.0.0","private":false,"description":"AutoLab OAuth App SDK - client_credentials flow for backend applications","type":"module","main":"dist/index.js","module":"dist/index.js","types":"dist/index.d.ts","publishConfig":{"access":"public"},"sideEffects":false,"exports":{".":{"import":"./dist/index.js","require":"./dist/index.js","types":"./dist/index.d.ts"}},"scripts":{"build":"tsc -p tsconfig.json","prepare":"npm run build"},"keywords":["oauth2","client_credentials","authentication","sdk","backend"],"author":{"name":"AutoLab Team"},"license":"MIT","dependencies":{"axios":"^1.7.7"},"devDependencies":{"typescript":"^5.6.3"},"_id":"@autolabz/oauth-app-sdk@1.0.0","gitHead":"d66ca4e4f5ed9c7cc6fa54b9e5269a83f1da733b","_nodeVersion":"20.19.5","_npmVersion":"10.8.2","dist":{"integrity":"sha512-CkXjp5VTUW3Wll2o78l0jMeUm0xvZakSAeqj/KTaRRvrU/+Gqlee75Rjx/qWcLj+wDgxk/qZ2PNNBDiD1m2Lpw==","shasum":"87b11e7404dce5a238329c7c4b55933ded402e2f","tarball":"https://registry.npmjs.org/@autolabz/oauth-app-sdk/-/oauth-app-sdk-1.0.0.tgz","fileCount":10,"unpackedSize":14119,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIBPXhzZ1SOHMimdEIGPcYz3IQIzxE/f5hb3PjnP/m4VMAiBxRZl+5NnlmtNCgMv1sVe7eKobcmfzpiDaFCLesaD7Xg=="}]},"_npmUser":{"name":"autolabz","email":"mzhh@mzhh.xyz"},"directories":{},"maintainers":[{"name":"autolabz","email":"mzhh@mzhh.xyz"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/oauth-app-sdk_1.0.0_1761964393605_0.6929158656065286"},"_hasShrinkwrap":false}},"time":{"created":"2025-11-01T02:33:13.538Z","1.0.0":"2025-11-01T02:33:13.806Z","modified":"2025-11-01T02:33:14.117Z"},"maintainers":[{"name":"autolabz","email":"mzhh@mzhh.xyz"}],"description":"AutoLab OAuth App SDK - client_credentials flow for backend applications","keywords":["oauth2","client_credentials","authentication","sdk","backend"],"author":{"name":"AutoLab Team"},"license":"MIT","readme":"# @autolabz/oauth-app-sdk\n\nOAuth2 **client_credentials** flow SDK for backend applications.\n\nThis SDK enables your backend services to authenticate with AutoLab using the OAuth2 `client_credentials` grant type, allowing them to access protected APIs on behalf of themselves (not a user).\n\n## Features\n\n- ✅ OAuth2 client_credentials flow implementation\n- ✅ Automatic token caching and refresh\n- ✅ AuthBridge adapter for seamless integration with other AutoLab SDKs\n- ✅ TypeScript support with full type definitions\n- ✅ Lightweight and zero dependencies (except axios)\n\n## Installation\n\n```bash\nnpm install @autolabz/oauth-app-sdk\n```\n\n## Usage\n\n### Basic Usage\n\n```typescript\nimport { OAuthAppClient } from '@autolabz/oauth-app-sdk';\n\n// Create an OAuth app client\nconst appClient = new OAuthAppClient({\n  clientId: 'your-client-id',\n  clientSecret: 'cs_live_...', // Get this when creating the OAuth2 app\n  authServiceUrl: 'https://your-auth-service.com/api'\n});\n\n// Get an access token (automatically cached and refreshed)\nconst accessToken = await appClient.getAccessToken();\n\n// Use the token in your API requests\nconst response = await fetch('https://your-api.com/resource', {\n  headers: {\n    'Authorization': `Bearer ${accessToken}`\n  }\n});\n```\n\n### Integration with Other AutoLab SDKs\n\nThe SDK provides an `AuthBridge` adapter that works seamlessly with other AutoLab SDKs:\n\n```typescript\nimport { OAuthAppClient, createAuthBridge } from '@autolabz/oauth-app-sdk';\nimport { createPointsClient } from '@autolabz/points-sdk';\nimport { createDataClient } from '@autolabz/data-sdk';\n\n// 1. Create the OAuth app client\nconst appClient = new OAuthAppClient({\n  clientId: 'your-client-id',\n  clientSecret: 'cs_live_...',\n  authServiceUrl: 'https://your-auth-service.com/api'\n});\n\n// 2. Create an AuthBridge\nconst authBridge = createAuthBridge(appClient, {\n  onUnauthorized: () => {\n    console.error('Authentication failed! Check your credentials.');\n  }\n});\n\n// 3. Use the bridge with other SDKs\nconst pointsClient = createPointsClient({\n  baseURL: 'https://your-points-service.com',\n  auth: authBridge\n});\n\nconst dataClient = createDataClient({\n  baseURL: 'https://your-data-service.com',\n  auth: authBridge\n});\n\n// 4. Make API calls (authentication is handled automatically)\nconst balance = await pointsClient.getMyBalance();\nconst data = await dataClient.query({ table: 'users' });\n```\n\n## API Reference\n\n### `OAuthAppClient`\n\nMain client class for OAuth2 client_credentials flow.\n\n#### Constructor\n\n```typescript\nnew OAuthAppClient(config: OAuthAppClientConfig)\n```\n\n**Parameters:**\n- `config.clientId` (string, required): Your OAuth2 application's client ID\n- `config.clientSecret` (string, required): Your OAuth2 application's client secret\n- `config.authServiceUrl` (string, required): Base URL of the auth service (e.g., `https://your-domain.com/api`)\n\n#### Methods\n\n##### `getAccessToken(): Promise<string | null>`\n\nGet an access token. Automatically caches and refreshes tokens as needed.\n\nReturns the cached token if it's still valid (with 10% buffer), otherwise fetches a new one.\n\n##### `fetchNewToken(): Promise<string>`\n\nExplicitly fetch a new access token from the auth service.\n\n##### `getClientId(): string`\n\nGet the client ID.\n\n##### `clearCache(): void`\n\nClear the cached token. Useful for testing or forcing a refresh.\n\n---\n\n### `createAuthBridge`\n\nCreate an AuthBridge adapter for use with other AutoLab SDKs.\n\n```typescript\ncreateAuthBridge(\n  client: OAuthAppClient,\n  options?: CreateAuthBridgeOptions\n): AuthBridge\n```\n\n**Parameters:**\n- `client` (OAuthAppClient, required): An instance of OAuthAppClient\n- `options.onUnauthorized` (function, optional): Callback function called when authentication fails\n\n**Returns:** `AuthBridge` object compatible with other AutoLab SDKs\n\n---\n\n## How It Works\n\n1. **Token Request**: When you call `getAccessToken()`, the SDK sends a POST request to `/oauth/token` with `grant_type=client_credentials`.\n\n2. **Token Caching**: The SDK caches the access token and its expiration time.\n\n3. **Automatic Refresh**: Before the token expires (with a 10% buffer), the SDK automatically fetches a new token.\n\n4. **AuthBridge**: The bridge adapter wraps the client to provide a consistent interface for other AutoLab SDKs.\n\n## Requirements\n\n- An OAuth2 application created in AutoLab with `authMode: 'OAUTH2'`\n- Node.js 14 or higher\n- TypeScript 4.5+ (if using TypeScript)\n\n## Getting Your Credentials\n\n1. Log in to the AutoLab Admin Portal\n2. Navigate to **OAuth Applications**\n3. Create a new application with **OAuth2** mode\n4. Copy the `clientId` and `clientSecret` (the secret is only shown once!)\n5. Configure your allowed scopes and redirect URIs\n\n## Security Best Practices\n\n⚠️ **Important**: Your `clientSecret` is sensitive and should be kept secure!\n\n- ❌ **Never** commit your client secret to version control\n- ❌ **Never** expose your client secret in client-side code\n- ✅ Store credentials in environment variables or a secure vault\n- ✅ Use different credentials for development and production\n- ✅ Rotate your client secret regularly\n\n## Environment Variables\n\nWe recommend storing your credentials as environment variables:\n\n```bash\nOAUTH_CLIENT_ID=your-client-id\nOAUTH_CLIENT_SECRET=cs_live_...\nAUTH_SERVICE_URL=https://your-auth-service.com/api\n```\n\nThen in your code:\n\n```typescript\nconst appClient = new OAuthAppClient({\n  clientId: process.env.OAUTH_CLIENT_ID!,\n  clientSecret: process.env.OAUTH_CLIENT_SECRET!,\n  authServiceUrl: process.env.AUTH_SERVICE_URL!\n});\n```\n\n## License\n\nMIT\n\n## Support\n\nFor issues and questions, please contact the AutoLab team or open an issue in the repository.\n\n\n","readmeFilename":"README.md","_rev":"1-14219057a8c17bab7c1c2fb2544052af"}