-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add OAuth Device Flow login command #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,8 +3,6 @@ name: CI | |
| on: | ||
| pull_request: | ||
| branches: [main] | ||
| push: | ||
| branches: [main] | ||
|
|
||
| jobs: | ||
| check: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| import type { ReplIO } from "./io.js"; | ||
|
|
||
| const AUTH0_DOMAIN = "https://auth.storage.tigrisdata.io"; | ||
| const AUTH0_CLIENT_ID = "FKXunmhaaBZOYXjNYLIU8Fi2jIqpT7DR"; | ||
| const AUTH0_AUDIENCE = "https://tigris-os-api"; | ||
| const AUTH0_SCOPES = "openid profile email offline_access"; | ||
| const CLAIMS_NAMESPACE = "https://tigris"; | ||
| const DEFAULT_POLL_INTERVAL = 5; | ||
|
|
||
| interface DeviceCodeResponse { | ||
| device_code: string; | ||
| user_code: string; | ||
| verification_uri: string; | ||
| verification_uri_complete: string; | ||
| expires_in: number; | ||
| interval: number; | ||
| } | ||
|
|
||
| interface TokenResponse { | ||
| access_token: string; | ||
| refresh_token?: string; | ||
| id_token?: string; | ||
| expires_in: number; | ||
| token_type: string; | ||
| } | ||
|
|
||
| export interface Organization { | ||
| id: string; | ||
| name: string; | ||
| } | ||
|
|
||
| export interface LoginResult { | ||
| accessToken: string; | ||
| refreshToken?: string; | ||
| email: string; | ||
| organizations: Organization[]; | ||
| } | ||
|
|
||
| /** | ||
| * Start the OAuth Device Authorization Flow. | ||
| * Returns device code info for display to the user. | ||
| */ | ||
| async function requestDeviceCode(): Promise<DeviceCodeResponse> { | ||
| const response = await fetch(`${AUTH0_DOMAIN}/oauth/device/code`, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/x-www-form-urlencoded" }, | ||
| body: new URLSearchParams({ | ||
| client_id: AUTH0_CLIENT_ID, | ||
| audience: AUTH0_AUDIENCE, | ||
| scope: AUTH0_SCOPES, | ||
| }), | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| const text = await response.text(); | ||
| throw new Error(`Device code request failed: ${text}`); | ||
| } | ||
|
|
||
| return response.json() as Promise<DeviceCodeResponse>; | ||
| } | ||
|
|
||
| /** | ||
| * Poll the token endpoint until the user authorizes or the code expires. | ||
| */ | ||
| async function pollForToken(deviceCode: string, interval: number): Promise<TokenResponse> { | ||
| let pollInterval = Math.max(interval, DEFAULT_POLL_INTERVAL) * 1000; | ||
|
|
||
| for (;;) { | ||
| await new Promise((resolve) => setTimeout(resolve, pollInterval)); | ||
|
|
||
| const response = await fetch(`${AUTH0_DOMAIN}/oauth/token`, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/x-www-form-urlencoded" }, | ||
| body: new URLSearchParams({ | ||
| client_id: AUTH0_CLIENT_ID, | ||
| device_code: deviceCode, | ||
| grant_type: "urn:ietf:params:oauth:grant-type:device_code", | ||
| }), | ||
| }); | ||
|
|
||
| const data = (await response.json()) as TokenResponse & { error?: string }; | ||
|
|
||
| if (data.error === "authorization_pending") { | ||
| continue; | ||
| } | ||
| if (data.error === "slow_down") { | ||
| pollInterval += 5000; // RFC 8628 §3.5: permanently increase by 5s | ||
| continue; | ||
| } | ||
| if (data.error) { | ||
| throw new Error(`Authorization failed: ${data.error}`); | ||
| } | ||
|
|
||
| return data; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Extract email from ID token (base64-decode the payload, no verification needed). | ||
| */ | ||
| function extractEmail(idToken: string): string { | ||
| const parts = idToken.split("."); | ||
| if (parts.length !== 3 || !parts[1]) { | ||
| return "unknown"; | ||
| } | ||
|
|
||
| try { | ||
| // Handle base64url encoding | ||
| const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/"); | ||
| const payload = JSON.parse(atob(base64)); | ||
| return payload.email ?? payload.name ?? "unknown"; | ||
| } catch { | ||
| return "unknown"; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Fetch organizations from the userinfo endpoint. | ||
| */ | ||
| async function fetchOrganizations(accessToken: string): Promise<Organization[]> { | ||
| const response = await fetch(`${AUTH0_DOMAIN}/userinfo`, { | ||
| headers: { Authorization: `Bearer ${accessToken}` }, | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| return []; | ||
| } | ||
|
|
||
| const data = (await response.json()) as Record<string, unknown>; | ||
| const claims = data[CLAIMS_NAMESPACE] as { ns?: Organization[] } | undefined; | ||
|
|
||
| return claims?.ns ?? []; | ||
| } | ||
|
|
||
| /** | ||
| * Run the full device authorization flow. | ||
| * Shows URL + code, waits for auth, fetches orgs. | ||
| */ | ||
| export async function deviceLogin(io: ReplIO): Promise<LoginResult> { | ||
| io.write("Logging in to Tigris...\n"); | ||
|
|
||
| const deviceCode = await requestDeviceCode(); | ||
|
|
||
| io.write(`\nOpen this URL in your browser:\n`); | ||
| io.write(` ${deviceCode.verification_uri_complete}\n\n`); | ||
| io.write(`Or go to ${deviceCode.verification_uri} and enter code: ${deviceCode.user_code}\n\n`); | ||
| io.write("Waiting for authorization..."); | ||
|
|
||
| const tokens = await pollForToken(deviceCode.device_code, deviceCode.interval); | ||
|
|
||
| io.write(" done!\n\n"); | ||
|
|
||
| const email = tokens.id_token ? extractEmail(tokens.id_token) : "unknown"; | ||
| io.write(`Logged in as ${email}\n`); | ||
|
|
||
| const organizations = await fetchOrganizations(tokens.access_token); | ||
|
|
||
| return { | ||
| accessToken: tokens.access_token, | ||
| ...(tokens.refresh_token !== undefined && { refreshToken: tokens.refresh_token }), | ||
| email, | ||
| organizations, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,4 @@ | ||
| export type { LoginResult, Organization } from "./auth.js"; | ||
| export { deviceLogin } from "./auth.js"; | ||
| export type { ReplIO } from "./io.js"; | ||
| export { ReplSession } from "./session.js"; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.