Skip to content
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
28 changes: 28 additions & 0 deletions common/auth/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NodeOAuthClient } from '@atproto/oauth-client-node'
import type { Database } from '../db'
import { env } from '..//env'
import { SessionStore, StateStore } from './storage'

export const createClient = async (db: Database) => {
const publicUrl = env.PUBLIC_URL
const url = publicUrl || `http://127.0.0.1:${env.PORT}`
const enc = encodeURIComponent
return new NodeOAuthClient({
clientMetadata: {
client_name: 'AT Protocol Express App',
client_id: publicUrl
? `${url}/client-metadata.json`
: `http://localhost?redirect_uri=${enc(`${url}/oauth/callback`)}&scope=${enc('atproto transition:generic')}`,
client_uri: url,
redirect_uris: [`${url}/oauth/callback`],
scope: 'atproto transition:generic',
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
application_type: 'web',
token_endpoint_auth_method: 'none',
dpop_bound_access_tokens: true,
},
stateStore: new StateStore(db),
sessionStore: new SessionStore(db),
})
}
47 changes: 47 additions & 0 deletions common/auth/storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type {
NodeSavedSession,
NodeSavedSessionStore,
NodeSavedState,
NodeSavedStateStore,
} from '@atproto/oauth-client-node'
import type { Database } from '../db'

export class StateStore implements NodeSavedStateStore {
constructor(private db: Database) {}
async get(key: string): Promise<NodeSavedState | undefined> {
const result = await this.db.selectFrom('auth_state').selectAll().where('key', '=', key).executeTakeFirst()
if (!result) return
return JSON.parse(result.state) as NodeSavedState
}
async set(key: string, val: NodeSavedState) {
const state = JSON.stringify(val)
await this.db
.insertInto('auth_state')
.values({ key, state })
.onConflict((oc) => oc.doUpdateSet({ state }))
.execute()
}
async del(key: string) {
await this.db.deleteFrom('auth_state').where('key', '=', key).execute()
}
}

export class SessionStore implements NodeSavedSessionStore {
constructor(private db: Database) {}
async get(key: string): Promise<NodeSavedSession | undefined> {
const result = await this.db.selectFrom('auth_session').selectAll().where('key', '=', key).executeTakeFirst()
if (!result) return
return JSON.parse(result.session) as NodeSavedSession
}
async set(key: string, val: NodeSavedSession) {
const session = JSON.stringify(val)
await this.db
.insertInto('auth_session')
.values({ key, session })
.onConflict((oc) => oc.doUpdateSet({ session }))
.execute()
}
async del(key: string) {
await this.db.deleteFrom('auth_session').where('key', '=', key).execute()
}
}
94 changes: 94 additions & 0 deletions common/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import SqliteDb from 'better-sqlite3'
import {
Kysely,
Migrator,
SqliteDialect,
Migration,
MigrationProvider,
} from 'kysely'

// Types

export type DatabaseSchema = {
status: Status
auth_session: AuthSession
auth_state: AuthState
}

export type Status = {
uri: string
authorDid: string
status: string
createdAt: string
indexedAt: string
}

export type AuthSession = {
key: string
session: AuthSessionJson
}

export type AuthState = {
key: string
state: AuthStateJson
}

type AuthStateJson = string

type AuthSessionJson = string

// Migrations

const migrations: Record<string, Migration> = {}

const migrationProvider: MigrationProvider = {
async getMigrations() {
return migrations
},
}

migrations['001'] = {
async up(db: Kysely<unknown>) {
await db.schema
.createTable('status')
.addColumn('uri', 'varchar', (col) => col.primaryKey())
.addColumn('authorDid', 'varchar', (col) => col.notNull())
.addColumn('status', 'varchar', (col) => col.notNull())
.addColumn('createdAt', 'varchar', (col) => col.notNull())
.addColumn('indexedAt', 'varchar', (col) => col.notNull())
.execute()
await db.schema
.createTable('auth_session')
.addColumn('key', 'varchar', (col) => col.primaryKey())
.addColumn('session', 'varchar', (col) => col.notNull())
.execute()
await db.schema
.createTable('auth_state')
.addColumn('key', 'varchar', (col) => col.primaryKey())
.addColumn('state', 'varchar', (col) => col.notNull())
.execute()
},
async down(db: Kysely<unknown>) {
await db.schema.dropTable('auth_state').execute()
await db.schema.dropTable('auth_session').execute()
await db.schema.dropTable('status').execute()
},
}

// APIs

export const createDb = (location: string): Database => {
return new Kysely<DatabaseSchema>({
dialect: new SqliteDialect({
database: new SqliteDb(location),
}),
})
}

export const migrateToLatest = async (db: Database) => {
const migrator = new Migrator({ db, provider: migrationProvider })
const { error } = await migrator.migrateToLatest()
if (error) throw error
}

export type Database = Kysely<DatabaseSchema>
16 changes: 16 additions & 0 deletions common/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import dotenv from 'dotenv'
import { cleanEnv, host, port, str, testOnly } from 'envalid'

dotenv.config()

export const env = cleanEnv(process.env, {
NODE_ENV: str({
devDefault: testOnly('test'),
choices: ['development', 'production', 'test'],
}),
HOST: host({ devDefault: testOnly('localhost') }),
PORT: port({ devDefault: testOnly(3000) }),
PUBLIC_URL: str({}),
DB_PATH: str({ devDefault: ':memory:' }),
COOKIE_SECRET: str({ devDefault: '00000000000000000000000000000000' }),
})
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@
"lint": "next lint"
},
"dependencies": {
"@atproto/oauth-client-node": "^0.2.24",
"aes-js": "^3.1.2",
"better-sqlite3": "^11.10.0",
"d3": "^7.9.0",
"dotenv": "^16.5.0",
"envalid": "^8.0.0",
"js-cookie": "^3.0.5",
"kysely": "^0.28.2",
"next": "^15.3.1",
"react": "^19.1.0",
"react-dom": "^19.1.0",
Expand All @@ -24,8 +29,8 @@
"devDependencies": {
"@types/node": "^22.14.1",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"ts-node": "^10.9.2",
"typescript": "^5.8.3",
"@types/react-dom": "^19.1.2"
"typescript": "^5.8.3"
}
}
6 changes: 6 additions & 0 deletions pages/search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import Page from '@components/Page';
import { FormHeading } from '@root/system/typography/forms';
import Button from '@root/system/Button';

import Bluesky from '@system/svg/social/Bluesky';

import { InputLabel } from '@root/system/typography/forms';
import Input from '@root/system/Input';

Expand All @@ -22,6 +24,7 @@ function SearchTaxa(props) {
const [searchTerm, setSearchTerm] = useState('');
const [searchResults, setSearchResults] = useState([]);
const [resultsCount, setResultsCount] = useState(0);
const [loading, setLoading] = React.useState<boolean>(false);

const handleSearch = async () => {
if (!searchTerm.trim()) return;
Expand All @@ -43,6 +46,9 @@ function SearchTaxa(props) {
<div style={{ alignContent: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 24, paddingBottom: 24 }}>
<h1 className={styles.header}>unforsaken.earth</h1>
<InputLabel style={{ marginTop: 24 }} />
<Button visual loading={loading} style={{ marginTop: 16, width: '15%' }}>
<Bluesky height="16px" style={{ marginRight: 12, color: '#0A7AFF' }} /> Sign in with Bluesky
</Button>
<form
onSubmit={(e) => {
e.preventDefault();
Expand Down