-
Notifications
You must be signed in to change notification settings - Fork 1
feat(device): implement OAuth 2.0 Device Authorization Grant #166
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
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
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,13 @@ | ||
| # Changelog - `@aura-stack/device` | ||
|
|
||
| All notable changes to this project will be documented in this file. | ||
|
|
||
| The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). | ||
|
|
||
| --- | ||
|
|
||
| ## [Unreleased] | ||
|
|
||
| ### Added | ||
|
|
||
| ### Changed |
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,57 @@ | ||
| <div align="center"> | ||
|
|
||
| <h1><b>@aura-stack/device</b></h1> | ||
|
|
||
| **OAuth 2.0 Device Authorization Grant for the Aura Stack ecosystem** | ||
|
|
||
| [](https://www.npmjs.com/package/@aura-stack/device) | ||
| [](https://jsr.io/@aura-stack/device) | ||
| [](https://opensource.org/licenses/MIT) | ||
|
|
||
| [Official Docs](https://aura-stack-auth.vercel.app/docs) · [Core Package Docs](https://aura-stack-auth.vercel.app/docs/packages/core) | ||
|
|
||
| </div> | ||
|
|
||
| ## Quick start | ||
|
|
||
| ```ts | ||
| import { createDeviceClient } from "@aura-stack/device" | ||
|
|
||
| const client = createDeviceClient({ providers: ["github"] }) | ||
|
|
||
| const { userCode, verificationURI } = await client.authorize("github") | ||
| console.log(`Visit ${verificationURI} and enter ${userCode}`) | ||
|
|
||
| const session = await client.poll() | ||
| console.log(session.user) | ||
| ``` | ||
|
|
||
| Poll with explicit credentials: | ||
|
|
||
| ```ts | ||
| const session = await client.poll({ | ||
| providerId: "github", | ||
| deviceCode: "...", | ||
| timeout: 600_000, | ||
| }) | ||
| ``` | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| pnpm add @aura-stack/device | ||
| ``` | ||
|
|
||
| ## Documentation | ||
|
|
||
| Visit the [**official documentation website**](https://aura-stack-auth.vercel.app). | ||
|
|
||
| ## License | ||
|
|
||
| Licensed under the [MIT License](../../LICENSE). © [Aura Stack](https://github.com/aura-stack-ts) | ||
|
|
||
| --- | ||
|
|
||
| <p align="center"> | ||
| Made with ❤️ by <a href="https://github.com/aura-stack-ts">Aura Stack team</a> | ||
| </p> |
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,15 @@ | ||
| { | ||
| "name": "@aura-stack/device", | ||
| "version": "0.0.0", | ||
| "license": "MIT", | ||
| "tasks": { | ||
| "dev": "deno run --watch src/index.ts" | ||
| }, | ||
| "imports": { | ||
| "@/": "./src/" | ||
| }, | ||
| "publish": { | ||
| "include": ["src/**/*.ts", "src/**/*.tsx", "README.md", "CHANGELOG.md"] | ||
| }, | ||
| "exclude": ["dist", "node_modules"] | ||
| } |
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,62 @@ | ||
| { | ||
| "name": "@aura-stack/device", | ||
| "version": "0.0.0", | ||
| "private": false, | ||
| "type": "module", | ||
| "description": "OAuth 2.0 Device Authorization Grant for the Aura Stack ecosystem", | ||
| "scripts": { | ||
| "dev": "tsdown --watch", | ||
| "build": " tsdown", | ||
| "lint": "oxlint", | ||
| "lint:fix": "oxlint --fix", | ||
| "test": "vitest --run", | ||
| "test:watch": "vitest", | ||
| "test:coverage": "vitest --run --coverage", | ||
| "format": "oxfmt", | ||
| "format:check": "oxfmt --check", | ||
| "type-check": "tsc --noEmit", | ||
| "clean:cts": "if [ -d dist ]; then find dist -type f -name \"*.cts\" -delete; fi", | ||
| "prepublishOnly": "pnpm clean:cts && pnpm build && pnpm clean:cts" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/aura-stack-ts/auth" | ||
| }, | ||
| "sideEffects": false, | ||
| "files": [ | ||
| "dist" | ||
| ], | ||
| "exports": { | ||
| ".": { | ||
| "types": "./dist/index.d.ts", | ||
| "import": "./dist/index.js", | ||
| "require": "./dist/index.cjs" | ||
| }, | ||
| "./providers": { | ||
| "types": "./dist/providers/index.d.ts", | ||
| "import": "./dist/providers/index.js", | ||
| "require": "./dist/providers/index.cjs" | ||
| }, | ||
| "./providers/*": { | ||
| "types": "./dist/providers/*.d.ts", | ||
| "import": "./dist/providers/*.js", | ||
| "require": "./dist/providers/*.cjs" | ||
| } | ||
| }, | ||
| "keywords": [], | ||
| "author": "Aura Stack <aurastackjs@gmail.com> | Hernan Alvarado <halvaradop.dev@gmail.com>", | ||
| "homepage": "https://aura-stack-auth.vercel.app", | ||
| "bugs": { | ||
| "url": "https://github.com/aura-stack-ts/auth/issues" | ||
| }, | ||
| "license": "MIT", | ||
| "dependencies": { | ||
| "valibot": "catalog:valibot" | ||
| }, | ||
| "devDependencies": { | ||
| "@aura-stack/tsconfig": "workspace:*", | ||
| "@aura-stack/tsdown-config": "workspace:*" | ||
| }, | ||
| "peerDependencies": {}, | ||
| "packageManager": "pnpm@10.15.0" | ||
| } |
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,35 @@ | ||
| import type { User } from "@/@types/session.ts" | ||
| import type { LiteralUnion } from "@/@types/index.ts" | ||
| import type { BuiltInDeviceProvider } from "@/providers/index.ts" | ||
| import type { DeviceAuthorizationResponse, DeviceProviderCredentials, DeviceSession } from "@/@types/device.ts" | ||
|
|
||
| export interface DeviceClientOptions<DefaultUser extends User = User> { | ||
| providers: (BuiltInDeviceProvider | DeviceProviderCredentials<Record<string, unknown>, DefaultUser>)[] | ||
| } | ||
|
|
||
| export interface PollOptions { | ||
| /** Maximum time in milliseconds to wait for authorization. */ | ||
| timeout?: number | ||
| providerId?: LiteralUnion<BuiltInDeviceProvider> | ||
| deviceCode?: string | ||
| /** Minimum seconds between poll requests (overrides server interval). */ | ||
| interval?: number | ||
| } | ||
|
|
||
| export interface AuthInstance { | ||
| authorize(providerId: LiteralUnion<BuiltInDeviceProvider>): Promise<DeviceAuthorizationResponse> | ||
| poll(options?: PollOptions): Promise<DeviceSession> | ||
| } | ||
|
|
||
| export interface PendingDeviceAuth { | ||
| providerId: LiteralUnion<BuiltInDeviceProvider> | ||
| deviceCode: string | ||
| interval: number | ||
| expiresAt: number | ||
| } | ||
|
|
||
| export interface AppContext { | ||
| providers: Record<LiteralUnion<BuiltInDeviceProvider>, DeviceProviderCredentials<Record<string, unknown>>> | ||
| getPending?: () => PendingDeviceAuth | null | ||
| setPending?: (pending: PendingDeviceAuth | null) => void | ||
| } |
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,97 @@ | ||
| import type { User } from "@/@types/session.ts" | ||
|
|
||
| export type DeviceAuthorizationConfig = string | { url: string; params?: { scope?: string } } | ||
|
|
||
| export interface DeviceProviderConfig<Profile extends object = Record<string, any>, DefaultUser = User> { | ||
| /** | ||
| * Default OAuth scope when not specified on the device authorization endpoint params. | ||
| */ | ||
| scope?: string | ||
| /** | ||
| * A unique identifier for the device provider, used for logging and debugging purposes. | ||
| */ | ||
| id: string | ||
| /** | ||
| * A human-readable name for the device provider, which may be displayed to users during | ||
| * the authentication process. | ||
| */ | ||
| name: string | ||
| /** | ||
| * The configuration for the device authorization endpoint, which can be a URL string or | ||
| * an object containing the URL and optional parameters such as scope. | ||
| */ | ||
| deviceAuthorization: DeviceAuthorizationConfig | ||
| /** | ||
| * The configuration for the token endpoint, which can be a URL string or an object | ||
| * containing the URL and optional parameters. | ||
| */ | ||
| accessToken: string | { url: string } | ||
| /** | ||
| * The configuration for the user information endpoint, which can be a URL string or an object | ||
| * containing the URL and optional parameters. | ||
| */ | ||
| userInfo: string | { url: string } | ||
| /** | ||
| * An optional function that takes the user profile returned from the user information endpoint | ||
| * and transforms it into a DefaultUser object. This allows for customization of the user data | ||
| * structure based on the specific requirements of the application. | ||
| */ | ||
| profile?: (profile: Profile) => DefaultUser | Promise<DefaultUser> | ||
| } | ||
|
|
||
| export interface DeviceProviderCredentials< | ||
| Profile extends object = Record<string, any>, | ||
| DefaultUser extends User = User, | ||
| > extends DeviceProviderConfig<Profile, DefaultUser> { | ||
| clientId: string | ||
| } | ||
|
|
||
| /** | ||
| * Device Authorization Response as per RFC 8628 | ||
| * @see https://datatracker.ietf.org/doc/html/rfc8628#section-3.2 | ||
| * | ||
| * @example | ||
| * { | ||
| * "device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS", | ||
| * "user_code": "WDJB-MJHT", | ||
| * "verification_uri": "https://example.com/device", | ||
| * "verification_uri_complete": "https://example.com/device?user_code=WDJB-MJHT", | ||
| * "expires_in": 1800, | ||
| * "interval": 5 | ||
| * } | ||
| */ | ||
| export interface DeviceAuthorizationResponse { | ||
| /** | ||
| * The device verification code. | ||
| */ | ||
| deviceCode: string | ||
| /** | ||
| * The end-user verification code. | ||
| */ | ||
| userCode: string | ||
| /** | ||
| * The end-user verification URI on the authorization server. | ||
| */ | ||
| verificationURI: string | ||
| /** | ||
| * The end-user verification URI with the user code embedded, per the authorization server's instructions. | ||
| */ | ||
| verificationURIComplete?: string | ||
| /** | ||
| * The lifetime in seconds of the device code and the user code. | ||
| */ | ||
| expiresIn: number | ||
| /** | ||
| * The minimum amount of time in seconds that the client SHOULD wait between polling requests to the token endpoint. | ||
| */ | ||
| interval?: number | ||
| } | ||
|
|
||
| export interface DeviceSession<DefaultUser = User> { | ||
| accessToken: string | ||
| tokenType: string | ||
| expiresIn?: number | ||
| refreshToken?: string | ||
| scope?: string | ||
| user: DefaultUser | ||
| } |
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,12 @@ | ||
| export type * from "@/@types/device.ts" | ||
| export type * from "@/@types/config.ts" | ||
| export type * from "@/@types/session.ts" | ||
|
|
||
| /** Expands intersection types into a single flat object type for readable editor hints. */ | ||
| export type Prettify<T> = { [K in keyof T]: T[K] } | ||
|
|
||
| /** | ||
| * A string that must be one of the literals in `T`, or any other string (`U`). | ||
| * Useful for autocomplete on known keys while still allowing custom values. | ||
| */ | ||
| export type LiteralUnion<T extends U, U = string> = T | (U & Record<never, never>) |
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,11 @@ | ||
| export interface User { | ||
| sub: string | ||
| name?: string | null | ||
| image?: string | null | ||
| email?: string | null | ||
| } | ||
|
|
||
| export interface Session<DefaultUser = User> { | ||
| session: DefaultUser | ||
| expires: string | ||
| } |
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,67 @@ | ||
| import { safeParse } from "valibot" | ||
| import { fetcher } from "@/shared/fetcher.ts" | ||
| import { toHeaders, toFormBody } from "@/shared/fetcher.ts" | ||
| import { DeviceAuthError, DeviceOAuthError } from "@/shared/errors.ts" | ||
| import { getResolvedScope, getResolvedURL } from "@/shared/url.ts" | ||
| import { DEFAULT_POLL_INTERVAL_SECONDS } from "@/shared/constants.ts" | ||
| import { OAuthDeviceAuthorizationResponse } from "@/schemas.ts" | ||
| import type { BuiltInDeviceProvider } from "@/providers/index.ts" | ||
| import type { AppContext, DeviceAuthorizationResponse, LiteralUnion, PendingDeviceAuth } from "@/@types/index.ts" | ||
|
|
||
| export const authorize = (context: AppContext) => { | ||
| return async (providerId: LiteralUnion<BuiltInDeviceProvider>): Promise<DeviceAuthorizationResponse> => { | ||
| const deviceConfig = context.providers[providerId] | ||
| if (!deviceConfig) { | ||
| throw new DeviceAuthError("INVALID_PROVIDER", `Provider with id ${providerId} not found`) | ||
| } | ||
|
|
||
| const url = getResolvedURL(deviceConfig.deviceAuthorization) | ||
| const scope = getResolvedScope(deviceConfig.deviceAuthorization, deviceConfig.scope) | ||
| const bodyParams: Record<string, string> = { | ||
| client_id: deviceConfig.clientId, | ||
| } | ||
| if (scope) { | ||
| bodyParams.scope = scope | ||
| } | ||
|
|
||
| const response = await fetcher(url, { | ||
| method: "POST", | ||
| headers: toHeaders(), | ||
| body: toFormBody(bodyParams), | ||
| }) | ||
|
|
||
| const json = await response.json().catch(() => null) | ||
| if (!response.ok) { | ||
| const error = typeof json === "object" && json !== null && "error" in json ? String(json.error) : "server_error" | ||
| const description = | ||
| typeof json === "object" && json !== null && "error_description" in json | ||
| ? String(json.error_description) | ||
| : `Device authorization request failed (${response.status}).` | ||
| throw new DeviceOAuthError(error as DeviceOAuthError["error"], description) | ||
| } | ||
|
|
||
| const { success, output } = safeParse(OAuthDeviceAuthorizationResponse, json) | ||
| if (!success) { | ||
| throw new DeviceOAuthError("invalid_request", "Failed to parse device authorization response") | ||
| } | ||
|
|
||
| const interval = output.interval ?? DEFAULT_POLL_INTERVAL_SECONDS | ||
| const authorizationResponse: DeviceAuthorizationResponse = { | ||
| deviceCode: output.device_code, | ||
| userCode: output.user_code, | ||
| verificationURI: output.verification_uri, | ||
| verificationURIComplete: output.verification_uri_complete, | ||
| expiresIn: output.expires_in, | ||
| interval, | ||
| } | ||
|
|
||
| const pending: PendingDeviceAuth = { | ||
| providerId, | ||
| deviceCode: output.device_code, | ||
| interval, | ||
| expiresAt: Date.now() + output.expires_in * 1000, | ||
| } | ||
| context.setPending?.(pending) | ||
| return authorizationResponse | ||
| } | ||
| } | ||
Oops, something went wrong.
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.