auth.ts 5.1 KB

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