Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
"@aura-stack/router": "^0.7.0",
"arktype": "^2.2.0",
"typebox": "^1.1.38",
"valibot": "^1.3.1",
"valibot": "catalog:valibot",
"zod": "catalog:zod-v4"
},
"devDependencies": {
Expand Down
13 changes: 13 additions & 0 deletions packages/device/CHANGELOG.md
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
57 changes: 57 additions & 0 deletions packages/device/README.md
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**

[![npm version](https://img.shields.io/npm/v/@aura-stack/device.svg)](https://www.npmjs.com/package/@aura-stack/device)
[![JSR version](https://jsr.io/badges/@aura-stack/device)](https://jsr.io/@aura-stack/device)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](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>
15 changes: 15 additions & 0 deletions packages/device/deno.json
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"]
}
62 changes: 62 additions & 0 deletions packages/device/package.json
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"
}
35 changes: 35 additions & 0 deletions packages/device/src/@types/config.ts
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
}
97 changes: 97 additions & 0 deletions packages/device/src/@types/device.ts
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
}
12 changes: 12 additions & 0 deletions packages/device/src/@types/index.ts
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>)
11 changes: 11 additions & 0 deletions packages/device/src/@types/session.ts
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
}
67 changes: 67 additions & 0 deletions packages/device/src/actions/authorize.ts
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")
Comment thread
halvaradop marked this conversation as resolved.
}

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
}
}
Loading
Loading