···11-PRIVATE_KEY_1={"kty":"EC","d":"8rx-D2vaik7FgRUaMeK_M8yZQ57J5NFs4MP6300_gek","use":"sig","crv":"P-256","kid":"44J2ZYr_4O3wp1B8GSRPvHMb7Cf506Nss3ISOplRx9I","x":"f9RLs9sqKyL38dPKsQaX-P_qTHVnNRCXuzkjbPvh7Ls","y":"ZnH5GuTAl5TTb-hZzsVgf1kUl4OB6qCS0PmM4_SPXvw","alg":"ES256"}
22-PRIVATE_KEY_2={"kty":"EC","d":"5Rk8UuCz-chUX_OZ4WgB7lb3OELn-xlGEedk4P-qY_M","use":"sig","crv":"P-256","kid":"kzDrzoJdNtK3bfTiuJYQZSk_Z7nsZqEpzqYSqHVBN_Q","x":"WuMNQ3slMhmvUJze-q4pxmC_Xqu5MkpkD3eSh1dPDBs","y":"0CS96lObk2UWnRbbrhQQDbduyZ_A4zKZtwSQTfqVkcU","alg":"ES256"}
33-PRIVATE_KEY_3={"kty":"EC","d":"GvpzAoGaHCG3OFe8qqi8FRs3WShGvS8OAOhjcN2vyuQ","use":"sig","crv":"P-256","kid":"y0HFLgCqOSwfbRJdO48dM8prLrLrT-qxNs_UrdvrbNQ","x":"VJ13t663tWZa67wUNQw26iU9iatIg4ZIklNKOrqMiYw","y":"Fqyc7qiOfwaYDXO259G8T66Wg2Kf_WLEjyi0ZenX2pI","alg":"ES256"}
44-NODE_ENV=development # Options: development, production
55-PORT=3000 # The port your server will listen on
66-HOST=localhost # Hostname for the server
77-PUBLIC_URL= # Set when deployed publicly, e.g. "https://mysite.com". Informs OAuth client id.
88-DB_PATH=:memory: # The SQLite database path. Leave as ":memory:" to use a temporary in-memory database.
99-# Secrets
1010-# Must set this in production. May be generated with `openssl rand -base64 33`=undefined
1111-# COOKIE_SECRET=""
···11+import { Ctx, EnvWithCtx } from "@/ctx";
22+import { db } from "@/db";
33+import { Agent, lexicons } from "@atproto/api";
44+import { NodeOAuthClient, Session } from "@atproto/oauth-client-node";
55+import { tealSession } from "@teal/db/schema";
66+import { eq } from "drizzle-orm";
77+import { Context } from "hono";
88+import { getCookie } from "hono/cookie";
99+1010+interface UserSession {
1111+ did: string;
1212+ /// The session JWT from ATProto
1313+ session: Session;
1414+}
1515+1616+interface UserInfo {
1717+ did: string;
1818+ handle: string;
1919+}
2020+2121+export async function getSessionAgent(
2222+ c: Context<EnvWithCtx>,
2323+ did: string,
2424+): Promise<Agent> {
2525+ const session = await getSession(c);
2626+ const auth = c.get("auth");
2727+ try {
2828+ const session = await auth.restore(did);
2929+ if (session) {
3030+ return new Agent(session);
3131+ }
3232+ throw new Error("Failed to restore session");
3333+ } catch (e) {
3434+ console.error(e);
3535+ throw new Error("Failed to restore session" + e);
3636+ }
3737+}
3838+3939+export async function getUserInfo(
4040+ c: Context<EnvWithCtx>,
4141+ did: string,
4242+): Promise<UserInfo> {
4343+ // init session agent
4444+ const agent = await getSessionAgent(c, did);
4545+ // fetch from ATProto
4646+ const res = await agent.app.bsky.actor.getProfile({
4747+ actor: did,
4848+ });
4949+ if (res.success) {
5050+ return {
5151+ did,
5252+ handle: res.data.handle,
5353+ email: res.data.email,
5454+ };
5555+ } else {
5656+ throw new Error("Failed to fetch user info");
5757+ }
5858+}
5959+6060+/**
6161+ * Get the auth session from the request cookie or Authorization header
6262+ */
6363+export async function getAuthSession(c: Context<EnvWithCtx>): Promise<Session> {
6464+ let authSession = getCookie(c, "authSession");
6565+ if (!authSession) {
6666+ authSession = c.req.header("Authorization");
6767+ }
6868+ if (!authSession) {
6969+ throw new Error("No auth session found");
7070+ } else {
7171+ // get the DID from the session
7272+ const did = await db
7373+ .select()
7474+ .from(tealSession)
7575+ .where(eq(tealSession.key, authSession))
7676+ .limit(1)
7777+ .all()
7878+ .then((result) => result[0]?.session);
7979+ if (!did) {
8080+ throw new Error("No DID found in session");
8181+ }
8282+ return getATPAuthSession(c, did);
8383+ }
8484+}
8585+8686+export async function getSession(c: Context<EnvWithCtx>): Promise<Session> {
8787+ let authSession = getCookie(c, "authSession");
8888+ if (!authSession) {
8989+ authSession = c.req.header("Authorization");
9090+ }
9191+ if (!authSession) {
9292+ throw new Error("No auth session found");
9393+ } else {
9494+ // get the DID from the session
9595+ const did = await db
9696+ .select()
9797+ .from(tealSession)
9898+ .where(eq(tealSession.key, authSession))
9999+ .limit(1)
100100+ .all()
101101+ .then((result) => result[0]?.session);
102102+ if (!did) {
103103+ throw new Error("No DID found in session");
104104+ }
105105+ return getATPAuthSession(c, did);
106106+ }
107107+}
108108+109109+// get the auth session from cookie or Authorization header
110110+export async function getATPAuthSession(
111111+ c: Context<EnvWithCtx>,
112112+ did: string,
113113+): Promise<Session> {
114114+ let auth: NodeOAuthClient = c.get("auth");
115115+ const jwt = await auth.sessionGetter.get(did);
116116+ if (jwt) {
117117+ return jwt;
118118+ }
119119+ throw new Error("No auth session found");
120120+}
+2
apps/aqua/src/lib/env.ts
···33import process from "node:process";
4455dotenv.config();
66+// in case our .env file is in the root folder
77+dotenv.config({ path: "./../../.env" });
6879export const env = cleanEnv(process.env, {
810 NODE_ENV: str({
···11+ALTER TABLE `status` RENAME COLUMN "authorDid" TO "author_did";--> statement-breakpoint
22+ALTER TABLE `status` RENAME COLUMN "createdAt" TO "created_at";--> statement-breakpoint
33+ALTER TABLE `status` RENAME COLUMN "indexedAt" TO "indexed_at";
+1
packages/db/.drizzle/0002_moaning_roulette.sql
···11+ALTER TABLE `auth_session` RENAME TO `atp_session`;
+12
packages/db/.drizzle/0003_sharp_medusa.sql
···11+CREATE TABLE `teal_session` (
22+ `key` text PRIMARY KEY NOT NULL,
33+ `session` text NOT NULL,
44+ `provider` text NOT NULL
55+);
66+--> statement-breakpoint
77+CREATE TABLE `teal_user` (
88+ `did` text PRIMARY KEY NOT NULL,
99+ `handle` text NOT NULL,
1010+ `email` text NOT NULL,
1111+ `created_at` text NOT NULL
1212+);
···11{
22+ "$schema": "https://json.schemastore.org/tsconfig",
23 "compilerOptions": {
33- /* Visit https://aka.ms/tsconfig to read more about this file */
44-55- /* Projects */
66- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
77- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
88- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
99- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
1010- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
1111- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
1212-1313- /* Language and Environment */
1414- "target": "ES2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
1515- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
1616- // "jsx": "preserve", /* Specify what JSX code is generated. */
1717- // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
1818- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
1919- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
2020- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
2121- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
2222- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
2323- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
2424- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
2525- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
2626-2727- /* Modules */
2828- "module": "ES2022" /* Specify what module code is generated. */,
2929- // "rootDir": "./", /* Specify the root folder within your source files. */
3030- "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
3131- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
3232- //"paths": {} /* Specify a set of entries that re-map imports to additional lookup locations. */,
3333- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
3434- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
3535- // "types": [] /* Specify type package names to be included without being referenced in a source file. */,
3636- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
3737- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
3838- // "resolveJsonModule": true, /* Enable importing .json files. */
3939- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
4040-4141- /* JavaScript Support */
4242- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
4343- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
4444- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
4545-4646- /* Emit */
4747- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
4848- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
4949- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
5050- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
5151- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
5252- // "outDir": "./", /* Specify an output folder for all emitted files. */
5353- // "removeComments": true, /* Disable emitting comments. */
5454- // "noEmit": true, /* Disable emitting files from a compilation. */
5555- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
5656- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
5757- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
5858- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
5959- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
6060- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
6161- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
6262- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
6363- // "newLine": "crlf", /* Set the newline character for emitting files. */
6464- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
6565- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
6666- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
6767- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
6868- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
6969- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
7070-7171- /* Interop Constraints */
7272- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
7373- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
7474- "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
7575- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
7676- "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
7777-7878- /* Type Checking */
7979- "strict": true /* Enable all strict type-checking options. */,
8080- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
8181- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
8282- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
8383- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
8484- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
8585- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
8686- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
8787- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
8888- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
8989- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
9090- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
9191- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
9292- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
9393- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
9494- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
9595- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
9696- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
9797- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
9898-9999- /* Completeness */
100100- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
101101- "skipLibCheck": true /* Skip type checking all .d.ts files. */
44+ "target": "ES2021",
55+ "module": "ESNext",
66+ "moduleResolution": "node",
77+ "esModuleInterop": true,
88+ "forceConsistentCasingInFileNames": true,
99+ "composite": true,
1010+ "declarationMap": true,
1111+ "strict": true,
1212+ "skipLibCheck": true
10213 }
10314}