auth.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import { z } from "zod"
  2. import { issuer } from "@openauthjs/openauth"
  3. import type { Theme } from "@openauthjs/openauth/ui/theme"
  4. import { createSubjects } from "@openauthjs/openauth/subject"
  5. import { THEME_OPENAUTH } from "@openauthjs/openauth/ui/theme"
  6. import { GithubProvider } from "@openauthjs/openauth/provider/github"
  7. import { GoogleOidcProvider } from "@openauthjs/openauth/provider/google"
  8. import { CloudflareStorage } from "@openauthjs/openauth/storage/cloudflare"
  9. import { Account } from "@opencode-ai/console-core/account.js"
  10. import { Workspace } from "@opencode-ai/console-core/workspace.js"
  11. import { Actor } from "@opencode-ai/console-core/actor.js"
  12. import { Resource } from "@opencode-ai/console-resource"
  13. import { User } from "@opencode-ai/console-core/user.js"
  14. import { and, Database, eq, isNull } from "@opencode-ai/console-core/drizzle/index.js"
  15. import { WorkspaceTable } from "@opencode-ai/console-core/schema/workspace.sql.js"
  16. import { UserTable } from "@opencode-ai/console-core/schema/user.sql.js"
  17. type Env = {
  18. AuthStorage: KVNamespace
  19. }
  20. export const subjects = createSubjects({
  21. account: z.object({
  22. accountID: z.string(),
  23. email: z.string(),
  24. }),
  25. user: z.object({
  26. userID: z.string(),
  27. workspaceID: z.string(),
  28. }),
  29. })
  30. const MY_THEME: Theme = {
  31. ...THEME_OPENAUTH,
  32. logo: "https://opencode.ai/favicon.svg",
  33. }
  34. export default {
  35. async fetch(request: Request, env: Env, ctx: ExecutionContext) {
  36. const result = await issuer({
  37. theme: MY_THEME,
  38. providers: {
  39. github: GithubProvider({
  40. clientID: Resource.GITHUB_CLIENT_ID_CONSOLE.value,
  41. clientSecret: Resource.GITHUB_CLIENT_SECRET_CONSOLE.value,
  42. scopes: ["read:user", "user:email"],
  43. }),
  44. google: GoogleOidcProvider({
  45. clientID: Resource.GOOGLE_CLIENT_ID.value,
  46. scopes: ["openid", "email"],
  47. }),
  48. // email: CodeProvider({
  49. // async request(req, state, form, error) {
  50. // console.log(state)
  51. // const params = new URLSearchParams()
  52. // if (error) {
  53. // params.set("error", error.type)
  54. // }
  55. // if (state.type === "start") {
  56. // return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/email?" + params.toString(), 302)
  57. // }
  58. //
  59. // if (state.type === "code") {
  60. // return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/code?" + params.toString(), 302)
  61. // }
  62. //
  63. // return new Response("ok")
  64. // },
  65. // async sendCode(claims, code) {
  66. // const email = z.string().email().parse(claims.email)
  67. // const cmd = new SendEmailCommand({
  68. // Destination: {
  69. // ToAddresses: [email],
  70. // },
  71. // FromEmailAddress: `SST <auth@${Resource.Email.sender}>`,
  72. // Content: {
  73. // Simple: {
  74. // Body: {
  75. // Html: {
  76. // Data: `Your pin code is <strong>${code}</strong>`,
  77. // },
  78. // Text: {
  79. // Data: `Your pin code is ${code}`,
  80. // },
  81. // },
  82. // Subject: {
  83. // Data: "SST Console Pin Code: " + code,
  84. // },
  85. // },
  86. // },
  87. // })
  88. // await ses.send(cmd)
  89. // },
  90. // }),
  91. },
  92. storage: CloudflareStorage({
  93. namespace: env.AuthStorage,
  94. }),
  95. subjects,
  96. async success(ctx, response) {
  97. console.log(response)
  98. let email: string | undefined
  99. if (response.provider === "github") {
  100. const emails = (await fetch("https://api.github.com/user/emails", {
  101. headers: {
  102. Authorization: `Bearer ${response.tokenset.access}`,
  103. "User-Agent": "opencode",
  104. Accept: "application/vnd.github+json",
  105. },
  106. }).then((x) => x.json())) as any
  107. email = emails.find((x: any) => x.primary && x.verified)?.email
  108. } else if (response.provider === "google") {
  109. if (!response.id.email_verified) throw new Error("Google email not verified")
  110. email = response.id.email as string
  111. } else throw new Error("Unsupported provider")
  112. if (!email) throw new Error("No email found")
  113. let accountID = await Account.fromEmail(email).then((x) => x?.id)
  114. if (!accountID) {
  115. console.log("creating account for", email)
  116. accountID = await Account.create({
  117. email: email!,
  118. })
  119. }
  120. await Actor.provide("account", { accountID, email }, async () => {
  121. await User.joinInvitedWorkspaces()
  122. const workspaces = await Database.transaction(async (tx) =>
  123. tx
  124. .select({ id: WorkspaceTable.id })
  125. .from(WorkspaceTable)
  126. .innerJoin(UserTable, eq(UserTable.workspaceID, WorkspaceTable.id))
  127. .where(
  128. and(
  129. eq(UserTable.accountID, accountID),
  130. isNull(UserTable.timeDeleted),
  131. isNull(WorkspaceTable.timeDeleted),
  132. ),
  133. ),
  134. )
  135. if (workspaces.length === 0) {
  136. await Workspace.create({ name: "Default" })
  137. }
  138. })
  139. return ctx.subject("account", accountID, { accountID, email })
  140. },
  141. }).fetch(request, env, ctx)
  142. return result
  143. },
  144. }