auth.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import type { KVNamespace } from "@cloudflare/workers-types"
  2. import { z } from "zod"
  3. import { issuer } from "@openauthjs/openauth"
  4. import type { Theme } from "@openauthjs/openauth/ui/theme"
  5. import { createSubjects } from "@openauthjs/openauth/subject"
  6. import { THEME_OPENAUTH } from "@openauthjs/openauth/ui/theme"
  7. import { GithubProvider } from "@openauthjs/openauth/provider/github"
  8. import { GoogleOidcProvider } from "@openauthjs/openauth/provider/google"
  9. import { CloudflareStorage } from "@openauthjs/openauth/storage/cloudflare"
  10. import { Account } from "@opencode-ai/console-core/account.js"
  11. import { Workspace } from "@opencode-ai/console-core/workspace.js"
  12. import { Actor } from "@opencode-ai/console-core/actor.js"
  13. import { Resource } from "@opencode-ai/console-resource"
  14. import { User } from "@opencode-ai/console-core/user.js"
  15. import { and, Database, eq, isNull, or } from "@opencode-ai/console-core/drizzle/index.js"
  16. import { WorkspaceTable } from "@opencode-ai/console-core/schema/workspace.sql.js"
  17. import { UserTable } from "@opencode-ai/console-core/schema/user.sql.js"
  18. import { AuthTable } from "@opencode-ai/console-core/schema/auth.sql.js"
  19. import { Identifier } from "@opencode-ai/console-core/identifier.js"
  20. type Env = {
  21. AuthStorage: KVNamespace
  22. }
  23. export const subjects = createSubjects({
  24. account: z.object({
  25. accountID: z.string(),
  26. email: z.string(),
  27. newAccount: z.boolean().optional(),
  28. }),
  29. user: z.object({
  30. userID: z.string(),
  31. workspaceID: z.string(),
  32. }),
  33. })
  34. const MY_THEME: Theme = {
  35. ...THEME_OPENAUTH,
  36. logo: "https://opencode.ai/favicon-v3.svg",
  37. }
  38. export default {
  39. async fetch(request: Request, env: Env, ctx: ExecutionContext) {
  40. const result = await issuer({
  41. theme: MY_THEME,
  42. providers: {
  43. github: GithubProvider({
  44. clientID: Resource.GITHUB_CLIENT_ID_CONSOLE.value,
  45. clientSecret: Resource.GITHUB_CLIENT_SECRET_CONSOLE.value,
  46. scopes: ["read:user", "user:email"],
  47. }),
  48. google: GoogleOidcProvider({
  49. clientID: Resource.GOOGLE_CLIENT_ID.value,
  50. scopes: ["openid", "email"],
  51. }),
  52. // email: CodeProvider({
  53. // async request(req, state, form, error) {
  54. // console.log(state)
  55. // const params = new URLSearchParams()
  56. // if (error) {
  57. // params.set("error", error.type)
  58. // }
  59. // if (state.type === "start") {
  60. // return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/email?" + params.toString(), 302)
  61. // }
  62. //
  63. // if (state.type === "code") {
  64. // return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/code?" + params.toString(), 302)
  65. // }
  66. //
  67. // return new Response("ok")
  68. // },
  69. // async sendCode(claims, code) {
  70. // const email = z.string().email().parse(claims.email)
  71. // const cmd = new SendEmailCommand({
  72. // Destination: {
  73. // ToAddresses: [email],
  74. // },
  75. // FromEmailAddress: `SST <auth@${Resource.Email.sender}>`,
  76. // Content: {
  77. // Simple: {
  78. // Body: {
  79. // Html: {
  80. // Data: `Your pin code is <strong>${code}</strong>`,
  81. // },
  82. // Text: {
  83. // Data: `Your pin code is ${code}`,
  84. // },
  85. // },
  86. // Subject: {
  87. // Data: "SST Console Pin Code: " + code,
  88. // },
  89. // },
  90. // },
  91. // })
  92. // await ses.send(cmd)
  93. // },
  94. // }),
  95. },
  96. storage: CloudflareStorage({
  97. // @ts-ignore
  98. namespace: env.AuthStorage,
  99. }),
  100. subjects,
  101. async success(ctx, response) {
  102. console.log(response)
  103. let subject: string | undefined
  104. let email: string | undefined
  105. if (response.provider === "github") {
  106. const emails = (await fetch("https://api.github.com/user/emails", {
  107. headers: {
  108. Authorization: `Bearer ${response.tokenset.access}`,
  109. "User-Agent": "opencode",
  110. Accept: "application/vnd.github+json",
  111. },
  112. }).then((x) => x.json())) as any
  113. const user = (await fetch("https://api.github.com/user", {
  114. headers: {
  115. Authorization: `Bearer ${response.tokenset.access}`,
  116. "User-Agent": "opencode",
  117. Accept: "application/vnd.github+json",
  118. },
  119. }).then((x) => x.json())) as any
  120. subject = user.id.toString()
  121. const primaryEmail = emails.find((x: any) => x.primary)
  122. if (!primaryEmail) throw new Error("No primary email found for GitHub user")
  123. if (!primaryEmail.verified) throw new Error("Primary email for GitHub user not verified")
  124. email = primaryEmail.email
  125. } else if (response.provider === "google") {
  126. if (!response.id.email_verified) throw new Error("Google email not verified")
  127. subject = response.id.sub as string
  128. email = response.id.email as string
  129. } else throw new Error("Unsupported provider")
  130. if (!email) throw new Error("No email found")
  131. if (!subject) throw new Error("No subject found")
  132. if (Resource.App.stage !== "production" && !email.endsWith("@anoma.ly")) {
  133. throw new Error("Invalid email")
  134. }
  135. // Get account
  136. let newAccount = false
  137. const accountID = await (async () => {
  138. const matches = await Database.use(async (tx) =>
  139. tx
  140. .select({
  141. provider: AuthTable.provider,
  142. accountID: AuthTable.accountID,
  143. })
  144. .from(AuthTable)
  145. .where(
  146. or(
  147. and(eq(AuthTable.provider, response.provider), eq(AuthTable.subject, subject)),
  148. and(eq(AuthTable.provider, "email"), eq(AuthTable.subject, email)),
  149. ),
  150. ),
  151. )
  152. const idByProvider = matches.find((x) => x.provider === response.provider)?.accountID
  153. const idByEmail = matches.find((x) => x.provider === "email")?.accountID
  154. if (idByProvider && idByEmail) return idByProvider
  155. // create account if not found
  156. let accountID = idByProvider ?? idByEmail
  157. if (!accountID) {
  158. console.log("creating account for", email)
  159. accountID = await Account.create({})
  160. newAccount = true
  161. }
  162. await Database.use(async (tx) =>
  163. tx
  164. .insert(AuthTable)
  165. .values([
  166. {
  167. id: Identifier.create("auth"),
  168. accountID,
  169. provider: response.provider,
  170. subject,
  171. },
  172. {
  173. id: Identifier.create("auth"),
  174. accountID,
  175. provider: "email",
  176. subject: email,
  177. },
  178. ])
  179. .onDuplicateKeyUpdate({
  180. set: {
  181. timeDeleted: null,
  182. },
  183. }),
  184. )
  185. return accountID
  186. })()
  187. // Get workspace
  188. await Actor.provide("account", { accountID, email }, async () => {
  189. await User.joinInvitedWorkspaces()
  190. const workspaces = await Database.use((tx) =>
  191. tx
  192. .select({ id: WorkspaceTable.id })
  193. .from(WorkspaceTable)
  194. .innerJoin(UserTable, eq(UserTable.workspaceID, WorkspaceTable.id))
  195. .where(
  196. and(
  197. eq(UserTable.accountID, accountID),
  198. isNull(UserTable.timeDeleted),
  199. isNull(WorkspaceTable.timeDeleted),
  200. ),
  201. ),
  202. )
  203. if (workspaces.length === 0) {
  204. await Workspace.create({ name: "Default" })
  205. }
  206. })
  207. return ctx.subject("account", accountID, { accountID, email, newAccount })
  208. },
  209. }).fetch(request, env, ctx)
  210. return result
  211. },
  212. }