···1-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"}
2-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"}
3-PRIVATE_KEY_3={"kty":"EC","d":"GvpzAoGaHCG3OFe8qqi8FRs3WShGvS8OAOhjcN2vyuQ","use":"sig","crv":"P-256","kid":"y0HFLgCqOSwfbRJdO48dM8prLrLrT-qxNs_UrdvrbNQ","x":"VJ13t663tWZa67wUNQw26iU9iatIg4ZIklNKOrqMiYw","y":"Fqyc7qiOfwaYDXO259G8T66Wg2Kf_WLEjyi0ZenX2pI","alg":"ES256"}
4-NODE_ENV=development # Options: development, production
5-PORT=3000 # The port your server will listen on
6-HOST=localhost # Hostname for the server
7-PUBLIC_URL= # Set when deployed publicly, e.g. "https://mysite.com". Informs OAuth client id.
8-DB_PATH=:memory: # The SQLite database path. Leave as ":memory:" to use a temporary in-memory database.
9-# Secrets
10-# Must set this in production. May be generated with `openssl rand -base64 33`=undefined
11-# COOKIE_SECRET=""
···1+import { Ctx, EnvWithCtx } from "@/ctx";
2+import { db } from "@/db";
3+import { Agent, lexicons } from "@atproto/api";
4+import { NodeOAuthClient, Session } from "@atproto/oauth-client-node";
5+import { tealSession } from "@teal/db/schema";
6+import { eq } from "drizzle-orm";
7+import { Context } from "hono";
8+import { getCookie } from "hono/cookie";
9+10+interface UserSession {
11+ did: string;
12+ /// The session JWT from ATProto
13+ session: Session;
14+}
15+16+interface UserInfo {
17+ did: string;
18+ handle: string;
19+}
20+21+export async function getSessionAgent(
22+ c: Context<EnvWithCtx>,
23+ did: string,
24+): Promise<Agent> {
25+ const session = await getSession(c);
26+ const auth = c.get("auth");
27+ try {
28+ const session = await auth.restore(did);
29+ if (session) {
30+ return new Agent(session);
31+ }
32+ throw new Error("Failed to restore session");
33+ } catch (e) {
34+ console.error(e);
35+ throw new Error("Failed to restore session" + e);
36+ }
37+}
38+39+export async function getUserInfo(
40+ c: Context<EnvWithCtx>,
41+ did: string,
42+): Promise<UserInfo> {
43+ // init session agent
44+ const agent = await getSessionAgent(c, did);
45+ // fetch from ATProto
46+ const res = await agent.app.bsky.actor.getProfile({
47+ actor: did,
48+ });
49+ if (res.success) {
50+ return {
51+ did,
52+ handle: res.data.handle,
53+ email: res.data.email,
54+ };
55+ } else {
56+ throw new Error("Failed to fetch user info");
57+ }
58+}
59+60+/**
61+ * Get the auth session from the request cookie or Authorization header
62+ */
63+export async function getAuthSession(c: Context<EnvWithCtx>): Promise<Session> {
64+ let authSession = getCookie(c, "authSession");
65+ if (!authSession) {
66+ authSession = c.req.header("Authorization");
67+ }
68+ if (!authSession) {
69+ throw new Error("No auth session found");
70+ } else {
71+ // get the DID from the session
72+ const did = await db
73+ .select()
74+ .from(tealSession)
75+ .where(eq(tealSession.key, authSession))
76+ .limit(1)
77+ .all()
78+ .then((result) => result[0]?.session);
79+ if (!did) {
80+ throw new Error("No DID found in session");
81+ }
82+ return getATPAuthSession(c, did);
83+ }
84+}
85+86+export async function getSession(c: Context<EnvWithCtx>): Promise<Session> {
87+ let authSession = getCookie(c, "authSession");
88+ if (!authSession) {
89+ authSession = c.req.header("Authorization");
90+ }
91+ if (!authSession) {
92+ throw new Error("No auth session found");
93+ } else {
94+ // get the DID from the session
95+ const did = await db
96+ .select()
97+ .from(tealSession)
98+ .where(eq(tealSession.key, authSession))
99+ .limit(1)
100+ .all()
101+ .then((result) => result[0]?.session);
102+ if (!did) {
103+ throw new Error("No DID found in session");
104+ }
105+ return getATPAuthSession(c, did);
106+ }
107+}
108+109+// get the auth session from cookie or Authorization header
110+export async function getATPAuthSession(
111+ c: Context<EnvWithCtx>,
112+ did: string,
113+): Promise<Session> {
114+ let auth: NodeOAuthClient = c.get("auth");
115+ const jwt = await auth.sessionGetter.get(did);
116+ if (jwt) {
117+ return jwt;
118+ }
119+ throw new Error("No auth session found");
120+}
+2
apps/aqua/src/lib/env.ts
···3import process from "node:process";
45dotenv.config();
0067export const env = cleanEnv(process.env, {
8 NODE_ENV: str({
···3import process from "node:process";
45dotenv.config();
6+// in case our .env file is in the root folder
7+dotenv.config({ path: "./../../.env" });
89export const env = cleanEnv(process.env, {
10 NODE_ENV: str({
···1+ALTER TABLE `status` RENAME COLUMN "authorDid" TO "author_did";--> statement-breakpoint
2+ALTER TABLE `status` RENAME COLUMN "createdAt" TO "created_at";--> statement-breakpoint
3+ALTER TABLE `status` RENAME COLUMN "indexedAt" TO "indexed_at";
+1
packages/db/.drizzle/0002_moaning_roulette.sql
···0
···1+ALTER TABLE `auth_session` RENAME TO `atp_session`;
+12
packages/db/.drizzle/0003_sharp_medusa.sql
···000000000000
···1+CREATE TABLE `teal_session` (
2+ `key` text PRIMARY KEY NOT NULL,
3+ `session` text NOT NULL,
4+ `provider` text NOT NULL
5+);
6+--> statement-breakpoint
7+CREATE TABLE `teal_user` (
8+ `did` text PRIMARY KEY NOT NULL,
9+ `handle` text NOT NULL,
10+ `email` text NOT NULL,
11+ `created_at` text NOT NULL
12+);
···1{
02 "compilerOptions": {
3- /* Visit https://aka.ms/tsconfig to read more about this file */
4-5- /* Projects */
6- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12-13- /* Language and Environment */
14- "target": "ES2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16- // "jsx": "preserve", /* Specify what JSX code is generated. */
17- // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26-27- /* Modules */
28- "module": "ES2022" /* Specify what module code is generated. */,
29- // "rootDir": "./", /* Specify the root folder within your source files. */
30- "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
31- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32- //"paths": {} /* Specify a set of entries that re-map imports to additional lookup locations. */,
33- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35- // "types": [] /* Specify type package names to be included without being referenced in a source file. */,
36- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38- // "resolveJsonModule": true, /* Enable importing .json files. */
39- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
40-41- /* JavaScript Support */
42- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
43- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
44- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
45-46- /* Emit */
47- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
48- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
49- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
50- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
51- // "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. */
52- // "outDir": "./", /* Specify an output folder for all emitted files. */
53- // "removeComments": true, /* Disable emitting comments. */
54- // "noEmit": true, /* Disable emitting files from a compilation. */
55- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
56- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
57- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
58- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
59- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
61- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
62- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
63- // "newLine": "crlf", /* Set the newline character for emitting files. */
64- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
65- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
66- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
67- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
68- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
69- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
70-71- /* Interop Constraints */
72- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
73- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
74- "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
75- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
76- "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
77-78- /* Type Checking */
79- "strict": true /* Enable all strict type-checking options. */,
80- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
81- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
82- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
83- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
84- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
85- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
86- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
87- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
88- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
89- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
90- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
91- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
92- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
93- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
94- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
95- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
96- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
97- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
98-99- /* Completeness */
100- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
101- "skipLibCheck": true /* Skip type checking all .d.ts files. */
102 }
103}