Skip to content
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

Add OAuth tests #2874

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions .changeset/witty-masks-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@atproto/oauth-provider": patch
---

Improve error message when invalid client id used during code exchange
3 changes: 1 addition & 2 deletions packages/api/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/** @type {import('jest').Config} */
module.exports = {
displayName: 'API',
transform: { '^.+\\.(t|j)s$': '@swc/jest' },
transformIgnorePatterns: [`<rootDir>/node_modules/(?!get-port)`],
transform: { '^.+\\.ts$': '@swc/jest' },
testTimeout: 60000,
setupFiles: ['<rootDir>/../../jest.setup.ts'],
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
Expand Down
1 change: 0 additions & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
},
"devDependencies": {
"@atproto/lex-cli": "workspace:^",
"get-port": "^6.1.2",
"jest": "^28.1.2",
"prettier": "^3.2.5",
"typescript": "^5.6.2"
Expand Down
14 changes: 7 additions & 7 deletions packages/api/tests/dispatcher.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AddressInfo } from 'node:net'
import assert from 'assert'
import getPort from 'get-port'
import {
AtpAgent,
AtpSessionEvent,
Expand Down Expand Up @@ -443,8 +443,8 @@ describe('AtpAgent', () => {

describe('App labelers header', () => {
it('adds the labelers header as expected', async () => {
const port = await getPort()
const server = await createHeaderEchoServer(port)
const server = await createHeaderEchoServer()
const port = (server.address() as AddressInfo).port
const agent = new AtpAgent({ service: `http://localhost:${port}` })
const agent2 = new AtpAgent({ service: `http://localhost:${port}` })

Expand All @@ -470,8 +470,8 @@ describe('AtpAgent', () => {

describe('configureLabelers', () => {
it('adds the labelers header as expected', async () => {
const port = await getPort()
const server = await createHeaderEchoServer(port)
const server = await createHeaderEchoServer()
const port = (server.address() as AddressInfo).port
const agent = new AtpAgent({ service: `http://localhost:${port}` })

agent.configureLabelers(['did:plc:test1'])
Expand All @@ -492,8 +492,8 @@ describe('AtpAgent', () => {

describe('configureProxy', () => {
it('adds the proxy header as expected', async () => {
const port = await getPort()
const server = await createHeaderEchoServer(port)
const server = await createHeaderEchoServer()
const port = (server.address() as AddressInfo).port
const agent = new AtpAgent({ service: `http://localhost:${port}` })

const res1 = await agent.com.atproto.server.describeServer()
Expand Down
36 changes: 18 additions & 18 deletions packages/api/tests/util/echo-server.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import http from 'node:http'
import { once } from 'node:events'
import { createServer } from 'node:http'

export async function createHeaderEchoServer(port: number) {
return new Promise<http.Server>((resolve) => {
const server = http.createServer()

server
.on('request', (request, response) => {
response.setHeader('content-type', 'application/json')
response.end(
JSON.stringify({
...request.headers,
did: 'did:web:fake.com',
availableUserDomains: [],
}),
)
})
.on('listening', () => resolve(server))
.listen(port)
export async function createHeaderEchoServer(port: number = 0) {
const server = createServer((req, res) => {
res.writeHead(200, undefined, { 'content-type': 'application/json' })
res.end(
JSON.stringify({
...req.headers,
did: 'did:web:fake.com',
availableUserDomains: [],
}),
)
})

server.listen(port)

await once(server, 'listening')

return server
}
2 changes: 1 addition & 1 deletion packages/bsky/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
module.exports = {
displayName: 'Bsky App View',
transform: { '^.+\\.(t|j)s$': '@swc/jest' },
transformIgnorePatterns: [`<rootDir>/node_modules/(?!get-port)`],
transformIgnorePatterns: ['/node_modules/.pnpm/(?!(get-port)@)'],
testTimeout: 60000,
setupFiles: ['<rootDir>/../../jest.setup.ts'],
}
2 changes: 1 addition & 1 deletion packages/identity/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
module.exports = {
displayName: 'Identity',
transform: { '^.+\\.(t|j)s$': '@swc/jest' },
transformIgnorePatterns: [`<rootDir>/node_modules/(?!get-port)`],
transformIgnorePatterns: ['/node_modules/.pnpm/(?!(get-port)@)'],
setupFiles: ['<rootDir>/../../jest.setup.ts'],
}
3 changes: 1 addition & 2 deletions packages/lexicon/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/** @type {import('jest').Config} */
module.exports = {
displayName: 'Lexicon',
transform: { '^.+\\.(t|j)s$': '@swc/jest' },
transformIgnorePatterns: [`<rootDir>/node_modules/(?!get-port)`],
transform: { '^.+\\.ts$': '@swc/jest' },
setupFiles: ['<rootDir>/../../jest.setup.ts'],
}
60 changes: 60 additions & 0 deletions packages/oauth/oauth-client-browser-example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"name": "@atproto/oauth-client-browser-example",
"version": "0.0.0",
"license": "MIT",
"description": "Example single page application app using ATPROTO OAuth",
"keywords": [
"example",
"spa",
"atproto",
"oauth",
"browser",
"client"
],
"homepage": "https://atproto.com",
"repository": {
"type": "git",
"url": "https://github.com/bluesky-social/atproto",
"directory": "packages/oauth/oauth-client-browser"
},
"type": "commonjs",
"exports": {
".": {
"default": "./dist/files.json"
}
},
"files": [
"dist"
],
"dependencies": {},
"devDependencies": {
"@atproto-labs/rollup-plugin-bundle-manifest": "workspace:*",
"@atproto/api": "workspace:*",
"@atproto/oauth-client": "workspace:*",
"@atproto/oauth-client-browser": "workspace:*",
"@atproto/oauth-types": "workspace:*",
"@atproto/xrpc": "workspace:*",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-html": "^1.0.4",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-replace": "^5.0.5",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
"@types/react": "^18.2.50",
"@types/react-dom": "^18.2.18",
"autoprefixer": "^10.4.17",
"postcss": "^8.4.33",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rollup": "^4.13.0",
"rollup-plugin-postcss": "^4.0.2",
"rollup-plugin-serve": "^1.1.1",
"tailwindcss": "^3.4.1",
"typescript": "^5.6.3"
},
"scripts": {
"build": "rollup --config rollup.config.js",
"dev": "rollup --config rollup.config.js --watch"
}
}
99 changes: 99 additions & 0 deletions packages/oauth/oauth-client-browser-example/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/* eslint-env node */

const { defineConfig } = require('rollup')

const {
default: manifest,
} = require('@atproto-labs/rollup-plugin-bundle-manifest')
const { default: commonjs } = require('@rollup/plugin-commonjs')
const { default: html, makeHtmlAttributes } = require('@rollup/plugin-html')
const { default: json } = require('@rollup/plugin-json')
const { default: nodeResolve } = require('@rollup/plugin-node-resolve')
const { default: replace } = require('@rollup/plugin-replace')
const { default: terser } = require('@rollup/plugin-terser')
const { default: typescript } = require('@rollup/plugin-typescript')
const postcss = ((m) => m.default || m)(require('rollup-plugin-postcss'))
const serve = ((m) => m.default || m)(require('rollup-plugin-serve'))

module.exports = defineConfig((commandLineArguments) => {
const NODE_ENV =
process.env['NODE_ENV'] ??
(commandLineArguments.watch ? 'development' : 'production')

const minify = NODE_ENV !== 'development'

return {
input: 'src/main.tsx',
output: {
manualChunks: undefined,
sourcemap: true,
file: 'dist/main.js',
format: 'iife',
},
plugins: [
nodeResolve({ preferBuiltins: false, browser: true }),
commonjs(),
json(),
postcss({ config: true, extract: true, minimize: false }),
typescript({
tsconfig: './tsconfig.build.json',
outputToFilesystem: true,
}),
replace({
preventAssignment: true,
values: { 'process.env.NODE_ENV': JSON.stringify(NODE_ENV) },
}),
html({
title: 'OAuth Client Example',
template: ({ attributes, files, meta, publicPath, title }) => `
<!DOCTYPE html>
<html${makeHtmlAttributes(attributes.html)}>
<head>
${meta
.map((attrs) => `<meta${makeHtmlAttributes(attrs)}>`)
.join('\n')}
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${title}</title>
${files.css
.map(
(asset) =>
`<link${makeHtmlAttributes({
...attributes.link,
rel: 'stylesheet',
href: `${publicPath}${asset.fileName}`,
})}>`,
)
.join('\n')}
</head>
<body class="bg-white dark:bg-slate-800">
<div id="root"></div>
${files.js
.map(
(asset) =>
`<script${makeHtmlAttributes({
...attributes.script,
src: `${publicPath}${asset.fileName}`,
})}></script>`,
)
.join('\n')}
</body>
</html>
`,
}),
minify && terser({}),
manifest({ name: 'files.json', data: true }),

commandLineArguments.watch &&
serve({
contentBase: 'dist',
port: 8080,
headers: { 'Cache-Control': 'no-store' },
}),
],
onwarn(warning, warn) {
// 'use client' directives are fine
if (warning.code === 'MODULE_LEVEL_DIRECTIVE') return
warn(warning)
},
}
})
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ export function OAuthSignInForm({
<fieldset className="rounded-md border border-solid border-slate-200 dark:border-slate-700 text-neutral-700 dark:text-neutral-100">
<div className="relative p-1 flex flex-wrap items-center justify-stretch">
<input
id="value"
name="value"
type="text"
className="relative m-0 block w-[1px] min-w-0 flex-auto px-3 py-[0.25rem] leading-[1.6] bg-transparent bg-clip-padding text-base text-inherit outline-none dark:placeholder:text-neutral-100"
Expand Down
14 changes: 14 additions & 0 deletions packages/oauth/oauth-client-browser-example/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const { searchParams } = new URL(window.location.href)

// Inserted during build
declare const process: { env: { NODE_ENV: string } }

export const ENV = searchParams.get('env') ?? process.env.NODE_ENV

export const PLC_DIRECTORY_URL: string | undefined =
searchParams.get('plc_directory_url') ??
(ENV === 'development' ? 'http://localhost:2582' : undefined)

export const HANDLE_RESOLVER_URL: string =
searchParams.get('handle_resolver') ??
(ENV === 'development' ? 'http://localhost:2584' : 'https://bsky.social')
29 changes: 29 additions & 0 deletions packages/oauth/oauth-client-browser-example/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import './index.css'

import React from 'react'
import ReactDOM from 'react-dom/client'

import App from './app'
import { AuthProvider } from './auth/auth-provider'
import { ENV, HANDLE_RESOLVER_URL, PLC_DIRECTORY_URL } from './constants'

const redirectURI = Object.assign(new URL(window.location.origin), {
hostname: '127.0.0.1',
search: new URLSearchParams({
env: ENV,
handle_resolver: HANDLE_RESOLVER_URL,
...(PLC_DIRECTORY_URL && { plc_directory_url: PLC_DIRECTORY_URL }),
}).toString(),
}).href

ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<AuthProvider
clientId={`http://localhost?redirect_uri=${encodeURIComponent(redirectURI)}&scope=atproto+transition%3Ageneric`}
plcDirectoryUrl={PLC_DIRECTORY_URL}
handleResolver={HANDLE_RESOLVER_URL}
>
<App />
</AuthProvider>
</React.StrictMode>,
)
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
content: ['./src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {},
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"extends": [
"../../../../tsconfig/browser.json",
"../../../../tsconfig/bundler.json"
"../../../tsconfig/browser.json",
"../../../tsconfig/bundler.json"
],
"compilerOptions": {
"rootDir": "./src",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../../tsconfig/node.json",
"compilerOptions": {
"rootDir": ".",
"noEmit": true
},
"include": ["./*.js", "./*.ts"],
"exclude": []
}
3 changes: 0 additions & 3 deletions packages/oauth/oauth-client-browser/example/package.json

This file was deleted.

Loading
Loading