oauth.do 0.1.14 → 0.2.0

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,45 @@
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
+ ## Getting Started
23
+
24
+ ### Prerequisites
25
+
26
+ - Node.js 18.0.0 or higher
27
+ - WorkOS account (optional - for custom AuthKit configuration)
28
+
29
+ ### Installation
6
30
 
7
31
  ```bash
32
+ # npm
8
33
  npm install oauth.do
34
+
35
+ # pnpm
36
+ pnpm add oauth.do
37
+
38
+ # yarn
39
+ yarn add oauth.do
40
+
41
+ # bun
42
+ bun add oauth.do
9
43
  ```
10
44
 
11
45
  ## CLI
@@ -56,7 +90,7 @@ const url = buildAuthUrl({
56
90
  For building CLIs that need authentication:
57
91
 
58
92
  ```typescript
59
- import { ensureLoggedIn } from 'oauth.do'
93
+ import { ensureLoggedIn } from 'oauth.do/node'
60
94
 
61
95
  // Get token (prompts login if needed, auto-opens browser)
62
96
  const { token, isNewLogin } = await ensureLoggedIn()
@@ -79,12 +113,203 @@ console.log('Code:', auth.user_code)
79
113
  const tokens = await pollForTokens(auth.device_code, auth.interval, auth.expires_in)
80
114
  ```
81
115
 
116
+ ## GitHub Device Flow
117
+
118
+ For CLI tools and headless environments that need GitHub authentication without a browser callback.
119
+
120
+ ```typescript
121
+ import { startGitHubDeviceFlow, pollGitHubDeviceFlow, getGitHubUser } from 'oauth.do'
122
+
123
+ // Step 1: Start the device flow
124
+ const auth = await startGitHubDeviceFlow({
125
+ clientId: 'Ov23liABCDEFGHIJKLMN',
126
+ scope: 'user:email read:user' // optional, this is the default
127
+ })
128
+
129
+ console.log(`Visit ${auth.verificationUri} and enter code: ${auth.userCode}`)
130
+
131
+ // Step 2: Poll for token (blocks until user completes authorization)
132
+ const token = await pollGitHubDeviceFlow(auth.deviceCode, {
133
+ clientId: 'Ov23liABCDEFGHIJKLMN',
134
+ interval: auth.interval,
135
+ expiresIn: auth.expiresIn
136
+ })
137
+
138
+ // Step 3: Get user information
139
+ const user = await getGitHubUser(token.accessToken)
140
+ console.log(`Logged in as ${user.login} (ID: ${user.id})`)
141
+ ```
142
+
143
+ ### GitHub Device Flow API
144
+
145
+ #### `startGitHubDeviceFlow(options)`
146
+
147
+ Initiates the device authorization flow by requesting device and user codes.
148
+
149
+ | Option | Type | Required | Description |
150
+ |--------|------|----------|-------------|
151
+ | `clientId` | `string` | Yes | GitHub OAuth App client ID |
152
+ | `scope` | `string` | No | OAuth scopes (default: `'user:email read:user'`) |
153
+ | `fetch` | `typeof fetch` | No | Custom fetch implementation |
154
+
155
+ Returns `GitHubDeviceAuthResponse` with `deviceCode`, `userCode`, `verificationUri`, `expiresIn`, and `interval`.
156
+
157
+ #### `pollGitHubDeviceFlow(deviceCode, options)`
158
+
159
+ Polls GitHub's token endpoint until user completes authorization.
160
+
161
+ | Option | Type | Required | Description |
162
+ |--------|------|----------|-------------|
163
+ | `clientId` | `string` | Yes | GitHub OAuth App client ID |
164
+ | `interval` | `number` | No | Polling interval in seconds (default: 5) |
165
+ | `expiresIn` | `number` | No | Expiration time in seconds (default: 900) |
166
+ | `fetch` | `typeof fetch` | No | Custom fetch implementation |
167
+
168
+ Returns `GitHubTokenResponse` with `accessToken`, `tokenType`, and `scope`.
169
+
170
+ #### `getGitHubUser(accessToken, options?)`
171
+
172
+ Fetches the authenticated user's profile from GitHub API.
173
+
174
+ Returns `GitHubUser` with `id`, `login`, `email`, `name`, and `avatarUrl`.
175
+
176
+ ## duckdb-auth Binary
177
+
178
+ The `duckdb-auth` binary wraps DuckDB with automatic OAuth token injection for authenticated HTTP requests.
179
+
180
+ ```bash
181
+ # Run DuckDB with oauth.do authentication
182
+ duckdb-auth mydata.db
183
+
184
+ # Execute authenticated queries
185
+ duckdb-auth -c "SELECT * FROM read_json('https://api.example.com/protected/data')"
186
+ ```
187
+
188
+ **How it works:**
189
+
190
+ 1. Retrieves your OAuth token from `oauth.do token`
191
+ 2. Creates DuckDB HTTP secrets with your bearer token
192
+ 3. Launches DuckDB with authentication pre-configured
193
+
194
+ If you're not logged in, it will automatically start the login flow before launching DuckDB.
195
+
196
+ ## React Components
197
+
198
+ Pre-configured React components for authentication, wrapping WorkOS AuthKit widgets.
199
+
200
+ ```tsx
201
+ import { OAuthDoProvider, useAuth, SignInButton, SignOutButton } from 'oauth.do/react'
202
+
203
+ // Wrap your app with the provider
204
+ function App({ children }) {
205
+ return (
206
+ <OAuthDoProvider>
207
+ {children}
208
+ </OAuthDoProvider>
209
+ )
210
+ }
211
+
212
+ // Use the auth hook
213
+ function UserGreeting() {
214
+ const { user, isLoading } = useAuth()
215
+
216
+ if (isLoading) return <span>Loading...</span>
217
+ if (!user) return <SignInButton>Sign In</SignInButton>
218
+
219
+ return (
220
+ <div>
221
+ <span>Hello, {user.firstName}!</span>
222
+ <SignOutButton>Sign Out</SignOutButton>
223
+ </div>
224
+ )
225
+ }
226
+ ```
227
+
228
+ ### React Widgets
229
+
230
+ ```tsx
231
+ import { ApiKeys, UsersManagement, UserProfile, useAuth } from 'oauth.do/react'
232
+
233
+ function SettingsPage() {
234
+ const { user, getAccessToken } = useAuth()
235
+ if (!user) return <p>Please sign in</p>
236
+
237
+ return (
238
+ <div>
239
+ <h2>Profile</h2>
240
+ <UserProfile authToken={getAccessToken} />
241
+
242
+ <h2>API Keys</h2>
243
+ <ApiKeys authToken={getAccessToken} />
244
+
245
+ <h2>Team Members</h2>
246
+ <UsersManagement authToken={getAccessToken} />
247
+ </div>
248
+ )
249
+ }
250
+ ```
251
+
252
+ ## Hono Middleware
253
+
254
+ Lightweight JWT authentication middleware for Cloudflare Workers and Hono.
255
+
256
+ ```typescript
257
+ import { Hono } from 'hono'
258
+ import { auth, requireAuth, apiKey } from 'oauth.do/hono'
259
+
260
+ const app = new Hono()
261
+
262
+ // Add auth to all routes (populates c.var.user if authenticated)
263
+ app.use('*', auth())
264
+
265
+ // Public route - auth is optional
266
+ app.get('/api/public', (c) => {
267
+ const user = c.var.user
268
+ return c.json({ message: 'Hello', user: user?.email || 'anonymous' })
269
+ })
270
+
271
+ // Protected route - requires authentication
272
+ app.use('/api/protected/*', requireAuth())
273
+
274
+ app.get('/api/protected/data', (c) => {
275
+ return c.json({ secret: 'data', user: c.var.user })
276
+ })
277
+
278
+ // Role-based access
279
+ app.use('/api/admin/*', requireAuth({ roles: ['admin'] }))
280
+
281
+ // Permission-based access
282
+ app.use('/api/billing/*', requireAuth({ permissions: ['billing:read', 'billing:write'] }))
283
+ ```
284
+
285
+ ### API Key Authentication
286
+
287
+ ```typescript
288
+ import { apiKey, combined } from 'oauth.do/hono'
289
+
290
+ // API key only
291
+ app.use('/api/v1/*', apiKey({
292
+ verify: async (key, c) => {
293
+ const user = await verifyApiKeyInDatabase(key)
294
+ return user // Return AuthUser or null
295
+ }
296
+ }))
297
+
298
+ // Combined: JWT or API key
299
+ app.use('/api/*', combined({
300
+ auth: { cookieName: 'session' },
301
+ apiKey: {
302
+ verify: async (key) => verifyApiKey(key)
303
+ }
304
+ }))
305
+ ```
306
+
82
307
  ## Token Storage
83
308
 
84
309
  ```typescript
85
- import { createSecureStorage, KeychainTokenStorage } from 'oauth.do'
310
+ import { createSecureStorage, KeychainTokenStorage } from 'oauth.do/node'
86
311
 
87
- // Auto-select best storage (keychain secure file)
312
+ // Auto-select best storage (keychain -> secure file)
88
313
  const storage = createSecureStorage()
89
314
 
90
315
  // Or use keychain directly
@@ -114,7 +339,7 @@ configure({
114
339
 
115
340
  ## Environment Variables
116
341
 
117
- - `DO_TOKEN` - Authentication token
342
+ - `ORG_AI_TOKEN` - Authentication token
118
343
  - `OAUTH_API_URL` - API base URL (default: `https://apis.do`)
119
344
  - `OAUTH_CLIENT_ID` - OAuth client ID
120
345
  - `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" "$@"