oauth.do 0.1.15 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 org.ai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,11 +1,59 @@
1
1
  # oauth.do
2
2
 
3
- OAuth authentication SDK and CLI for .do Platform.
3
+ [![npm version](https://img.shields.io/npm/v/oauth.do.svg)](https://www.npmjs.com/package/oauth.do)
4
+ [![license](https://img.shields.io/npm/l/oauth.do.svg)](https://github.com/dot-do/oauth.do/blob/main/LICENSE)
5
+ [![tests](https://img.shields.io/github/actions/workflow/status/dot-do/oauth.do/test.yml?label=tests)](https://github.com/dot-do/oauth.do/actions)
4
6
 
5
- ## Install
7
+ OAuth authentication SDK and CLI for the .do Platform, wrapping [WorkOS AuthKit](https://workos.com/authkit) with pre-configured defaults and multiple entry points for different environments.
8
+
9
+ **Why oauth.do?**
10
+ - Pre-configured AuthKit settings for .do Platform - works out of the box
11
+ - Multiple entry points: SDK, CLI, React components, Hono middleware
12
+ - Built-in secure token storage with OS keychain support
13
+ - GitHub Device Flow for CLI tools and headless environments
14
+
15
+ ```typescript
16
+ import { auth } from 'oauth.do'
17
+
18
+ const { user, token } = await auth()
19
+ console.log(`Hello, ${user.firstName}!`)
20
+ ```
21
+
22
+ ## Entry Points
23
+
24
+ oauth.do provides multiple entry points for different environments:
25
+
26
+ | Import | Environment | Description |
27
+ |--------|-------------|-------------|
28
+ | `oauth.do` | Universal | Core auth functions (browser, Workers, Node.js) |
29
+ | `oauth.do/node` | Node.js only | CLI helpers with keychain storage (uses `keytar`) |
30
+ | `oauth.do/react` | React | React components and hooks |
31
+ | `oauth.do/hono` | Hono/Workers | Cloudflare Workers middleware |
32
+ | `oauth.do/session` | Universal | Session management utilities |
33
+
34
+ **Important for Cloudflare Workers:** Import from the main `oauth.do` path or `oauth.do/hono`. The `/node` subpath uses native modules (`keytar`) that won't bundle for Workers.
35
+
36
+ ## Getting Started
37
+
38
+ ### Prerequisites
39
+
40
+ - Node.js 18.0.0 or higher
41
+ - WorkOS account (optional - for custom AuthKit configuration)
42
+
43
+ ### Installation
6
44
 
7
45
  ```bash
46
+ # npm
8
47
  npm install oauth.do
48
+
49
+ # pnpm
50
+ pnpm add oauth.do
51
+
52
+ # yarn
53
+ yarn add oauth.do
54
+
55
+ # bun
56
+ bun add oauth.do
9
57
  ```
10
58
 
11
59
  ## CLI
@@ -22,14 +70,11 @@ npx oauth.do status # Show auth status
22
70
  ## SDK
23
71
 
24
72
  ```typescript
25
- import { auth, login, logout, getToken, isAuthenticated } from 'oauth.do'
73
+ import { auth, logout, getToken, isAuthenticated } from 'oauth.do'
26
74
 
27
75
  // Check authentication
28
76
  const { user, token } = await auth()
29
77
 
30
- // Login
31
- const result = await login({ email: '...', password: '...' })
32
-
33
78
  // Logout
34
79
  await logout(token)
35
80
 
@@ -56,7 +101,7 @@ const url = buildAuthUrl({
56
101
  For building CLIs that need authentication:
57
102
 
58
103
  ```typescript
59
- import { ensureLoggedIn } from 'oauth.do'
104
+ import { ensureLoggedIn } from 'oauth.do/node'
60
105
 
61
106
  // Get token (prompts login if needed, auto-opens browser)
62
107
  const { token, isNewLogin } = await ensureLoggedIn()
@@ -79,12 +124,203 @@ console.log('Code:', auth.user_code)
79
124
  const tokens = await pollForTokens(auth.device_code, auth.interval, auth.expires_in)
80
125
  ```
81
126
 
127
+ ## GitHub Device Flow
128
+
129
+ For CLI tools and headless environments that need GitHub authentication without a browser callback.
130
+
131
+ ```typescript
132
+ import { startGitHubDeviceFlow, pollGitHubDeviceFlow, getGitHubUser } from 'oauth.do'
133
+
134
+ // Step 1: Start the device flow
135
+ const auth = await startGitHubDeviceFlow({
136
+ clientId: 'Ov23liABCDEFGHIJKLMN',
137
+ scope: 'user:email read:user' // optional, this is the default
138
+ })
139
+
140
+ console.log(`Visit ${auth.verificationUri} and enter code: ${auth.userCode}`)
141
+
142
+ // Step 2: Poll for token (blocks until user completes authorization)
143
+ const token = await pollGitHubDeviceFlow(auth.deviceCode, {
144
+ clientId: 'Ov23liABCDEFGHIJKLMN',
145
+ interval: auth.interval,
146
+ expiresIn: auth.expiresIn
147
+ })
148
+
149
+ // Step 3: Get user information
150
+ const user = await getGitHubUser(token.accessToken)
151
+ console.log(`Logged in as ${user.login} (ID: ${user.id})`)
152
+ ```
153
+
154
+ ### GitHub Device Flow API
155
+
156
+ #### `startGitHubDeviceFlow(options)`
157
+
158
+ Initiates the device authorization flow by requesting device and user codes.
159
+
160
+ | Option | Type | Required | Description |
161
+ |--------|------|----------|-------------|
162
+ | `clientId` | `string` | Yes | GitHub OAuth App client ID |
163
+ | `scope` | `string` | No | OAuth scopes (default: `'user:email read:user'`) |
164
+ | `fetch` | `typeof fetch` | No | Custom fetch implementation |
165
+
166
+ Returns `GitHubDeviceAuthResponse` with `deviceCode`, `userCode`, `verificationUri`, `expiresIn`, and `interval`.
167
+
168
+ #### `pollGitHubDeviceFlow(deviceCode, options)`
169
+
170
+ Polls GitHub's token endpoint until user completes authorization.
171
+
172
+ | Option | Type | Required | Description |
173
+ |--------|------|----------|-------------|
174
+ | `clientId` | `string` | Yes | GitHub OAuth App client ID |
175
+ | `interval` | `number` | No | Polling interval in seconds (default: 5) |
176
+ | `expiresIn` | `number` | No | Expiration time in seconds (default: 900) |
177
+ | `fetch` | `typeof fetch` | No | Custom fetch implementation |
178
+
179
+ Returns `GitHubTokenResponse` with `accessToken`, `tokenType`, and `scope`.
180
+
181
+ #### `getGitHubUser(accessToken, options?)`
182
+
183
+ Fetches the authenticated user's profile from GitHub API.
184
+
185
+ Returns `GitHubUser` with `id`, `login`, `email`, `name`, and `avatarUrl`.
186
+
187
+ ## duckdb-auth Binary
188
+
189
+ The `duckdb-auth` binary wraps DuckDB with automatic OAuth token injection for authenticated HTTP requests.
190
+
191
+ ```bash
192
+ # Run DuckDB with oauth.do authentication
193
+ duckdb-auth mydata.db
194
+
195
+ # Execute authenticated queries
196
+ duckdb-auth -c "SELECT * FROM read_json('https://api.example.com/protected/data')"
197
+ ```
198
+
199
+ **How it works:**
200
+
201
+ 1. Retrieves your OAuth token from `oauth.do token`
202
+ 2. Creates DuckDB HTTP secrets with your bearer token
203
+ 3. Launches DuckDB with authentication pre-configured
204
+
205
+ If you're not logged in, it will automatically start the login flow before launching DuckDB.
206
+
207
+ ## React Components
208
+
209
+ Pre-configured React components for authentication, wrapping WorkOS AuthKit widgets.
210
+
211
+ ```tsx
212
+ import { OAuthDoProvider, useAuth, SignInButton, SignOutButton } from 'oauth.do/react'
213
+
214
+ // Wrap your app with the provider
215
+ function App({ children }) {
216
+ return (
217
+ <OAuthDoProvider>
218
+ {children}
219
+ </OAuthDoProvider>
220
+ )
221
+ }
222
+
223
+ // Use the auth hook
224
+ function UserGreeting() {
225
+ const { user, isLoading } = useAuth()
226
+
227
+ if (isLoading) return <span>Loading...</span>
228
+ if (!user) return <SignInButton>Sign In</SignInButton>
229
+
230
+ return (
231
+ <div>
232
+ <span>Hello, {user.firstName}!</span>
233
+ <SignOutButton>Sign Out</SignOutButton>
234
+ </div>
235
+ )
236
+ }
237
+ ```
238
+
239
+ ### React Widgets
240
+
241
+ ```tsx
242
+ import { ApiKeys, UsersManagement, UserProfile, useAuth } from 'oauth.do/react'
243
+
244
+ function SettingsPage() {
245
+ const { user, getAccessToken } = useAuth()
246
+ if (!user) return <p>Please sign in</p>
247
+
248
+ return (
249
+ <div>
250
+ <h2>Profile</h2>
251
+ <UserProfile authToken={getAccessToken} />
252
+
253
+ <h2>API Keys</h2>
254
+ <ApiKeys authToken={getAccessToken} />
255
+
256
+ <h2>Team Members</h2>
257
+ <UsersManagement authToken={getAccessToken} />
258
+ </div>
259
+ )
260
+ }
261
+ ```
262
+
263
+ ## Hono Middleware
264
+
265
+ Lightweight JWT authentication middleware for Cloudflare Workers and Hono.
266
+
267
+ ```typescript
268
+ import { Hono } from 'hono'
269
+ import { auth, requireAuth, apiKey } from 'oauth.do/hono'
270
+
271
+ const app = new Hono()
272
+
273
+ // Add auth to all routes (populates c.var.user if authenticated)
274
+ app.use('*', auth())
275
+
276
+ // Public route - auth is optional
277
+ app.get('/api/public', (c) => {
278
+ const user = c.var.user
279
+ return c.json({ message: 'Hello', user: user?.email || 'anonymous' })
280
+ })
281
+
282
+ // Protected route - requires authentication
283
+ app.use('/api/protected/*', requireAuth())
284
+
285
+ app.get('/api/protected/data', (c) => {
286
+ return c.json({ secret: 'data', user: c.var.user })
287
+ })
288
+
289
+ // Role-based access
290
+ app.use('/api/admin/*', requireAuth({ roles: ['admin'] }))
291
+
292
+ // Permission-based access
293
+ app.use('/api/billing/*', requireAuth({ permissions: ['billing:read', 'billing:write'] }))
294
+ ```
295
+
296
+ ### API Key Authentication
297
+
298
+ ```typescript
299
+ import { apiKey, combined } from 'oauth.do/hono'
300
+
301
+ // API key only
302
+ app.use('/api/v1/*', apiKey({
303
+ verify: async (key, c) => {
304
+ const user = await verifyApiKeyInDatabase(key)
305
+ return user // Return AuthUser or null
306
+ }
307
+ }))
308
+
309
+ // Combined: JWT or API key
310
+ app.use('/api/*', combined({
311
+ auth: { cookieName: 'session' },
312
+ apiKey: {
313
+ verify: async (key) => verifyApiKey(key)
314
+ }
315
+ }))
316
+ ```
317
+
82
318
  ## Token Storage
83
319
 
84
320
  ```typescript
85
321
  import { createSecureStorage, KeychainTokenStorage } from 'oauth.do'
86
322
 
87
- // Auto-select best storage (keychain secure file)
323
+ // Auto-select best storage (keychain -> secure file)
88
324
  const storage = createSecureStorage()
89
325
 
90
326
  // Or use keychain directly
@@ -114,7 +350,7 @@ configure({
114
350
 
115
351
  ## Environment Variables
116
352
 
117
- - `DO_TOKEN` - Authentication token
353
+ - `ORG_AI_TOKEN` - Authentication token
118
354
  - `OAUTH_API_URL` - API base URL (default: `https://apis.do`)
119
355
  - `OAUTH_CLIENT_ID` - OAuth client ID
120
356
  - `OAUTH_AUTHKIT_DOMAIN` - AuthKit domain (default: `login.oauth.do`)
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # duckdb-auth - DuckDB with oauth.do authentication
4
+ #
5
+ # This wrapper script gets an OAuth token from oauth.do and
6
+ # configures DuckDB to use it for authenticated HTTP requests.
7
+ #
8
+ # Usage:
9
+ # duckdb-auth [duckdb-args...]
10
+ # duckdb-auth mydata.db
11
+ # duckdb-auth -c "SELECT * FROM read_json('https://api.example.com/data')"
12
+ #
13
+
14
+ set -e
15
+
16
+ # Colors for output
17
+ RED='\033[0;31m'
18
+ GREEN='\033[0;32m'
19
+ YELLOW='\033[1;33m'
20
+ NC='\033[0m' # No Color
21
+
22
+ # Check if oauth.do CLI is available
23
+ if ! command -v oauth.do &> /dev/null; then
24
+ echo -e "${RED}Error: oauth.do CLI not found${NC}"
25
+ echo "Install with: npm install -g oauth.do"
26
+ exit 1
27
+ fi
28
+
29
+ # Check if duckdb is available
30
+ if ! command -v duckdb &> /dev/null; then
31
+ echo -e "${RED}Error: duckdb CLI not found${NC}"
32
+ echo "Install from: https://duckdb.org/docs/installation/"
33
+ exit 1
34
+ fi
35
+
36
+ # Get OAuth token
37
+ TOKEN=$(oauth.do token 2>/dev/null || echo "")
38
+
39
+ if [ -z "$TOKEN" ]; then
40
+ echo -e "${YELLOW}Not logged in to oauth.do${NC}"
41
+ echo "Starting login flow..."
42
+ oauth.do login
43
+ TOKEN=$(oauth.do token 2>/dev/null || echo "")
44
+
45
+ if [ -z "$TOKEN" ]; then
46
+ echo -e "${RED}Failed to get token after login${NC}"
47
+ exit 1
48
+ fi
49
+ fi
50
+
51
+ echo -e "${GREEN}✓ Authenticated with oauth.do${NC}"
52
+
53
+ # Create init SQL to set up secrets
54
+ INIT_SQL="
55
+ -- oauth.do authentication setup
56
+ CREATE OR REPLACE SECRET oauth_do (
57
+ TYPE http,
58
+ BEARER_TOKEN '${TOKEN}'
59
+ );
60
+
61
+ -- Also create with extra headers for flexibility
62
+ CREATE OR REPLACE SECRET oauth_do_headers (
63
+ TYPE HTTP,
64
+ EXTRA_HTTP_HEADERS MAP {
65
+ 'Authorization': 'Bearer ${TOKEN}'
66
+ }
67
+ );
68
+ "
69
+
70
+ # Run DuckDB with init command
71
+ exec duckdb -cmd "$INIT_SQL" "$@"