auth.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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-core/util/resource.js"
  13. type Env = {
  14. AuthStorage: KVNamespace
  15. }
  16. export const subjects = createSubjects({
  17. account: z.object({
  18. accountID: z.string(),
  19. email: z.string(),
  20. }),
  21. user: z.object({
  22. userID: z.string(),
  23. workspaceID: z.string(),
  24. }),
  25. })
  26. const MY_THEME: Theme = {
  27. ...THEME_OPENAUTH,
  28. logo: "https://opencode.ai/favicon.svg",
  29. }
  30. export default {
  31. async fetch(request: Request, env: Env, ctx: ExecutionContext) {
  32. return issuer({
  33. theme: MY_THEME,
  34. providers: {
  35. github: GithubProvider({
  36. clientID: Resource.GITHUB_CLIENT_ID_CONSOLE.value,
  37. clientSecret: Resource.GITHUB_CLIENT_SECRET_CONSOLE.value,
  38. scopes: ["read:user", "user:email"],
  39. }),
  40. google: GoogleOidcProvider({
  41. clientID: Resource.GOOGLE_CLIENT_ID.value,
  42. scopes: ["openid", "email"],
  43. }),
  44. // email: CodeProvider({
  45. // async request(req, state, form, error) {
  46. // console.log(state)
  47. // const params = new URLSearchParams()
  48. // if (error) {
  49. // params.set("error", error.type)
  50. // }
  51. // if (state.type === "start") {
  52. // return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/email?" + params.toString(), 302)
  53. // }
  54. //
  55. // if (state.type === "code") {
  56. // return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/code?" + params.toString(), 302)
  57. // }
  58. //
  59. // return new Response("ok")
  60. // },
  61. // async sendCode(claims, code) {
  62. // const email = z.string().email().parse(claims.email)
  63. // const cmd = new SendEmailCommand({
  64. // Destination: {
  65. // ToAddresses: [email],
  66. // },
  67. // FromEmailAddress: `SST <auth@${Resource.Email.sender}>`,
  68. // Content: {
  69. // Simple: {
  70. // Body: {
  71. // Html: {
  72. // Data: `Your pin code is <strong>${code}</strong>`,
  73. // },
  74. // Text: {
  75. // Data: `Your pin code is ${code}`,
  76. // },
  77. // },
  78. // Subject: {
  79. // Data: "SST Console Pin Code: " + code,
  80. // },
  81. // },
  82. // },
  83. // })
  84. // await ses.send(cmd)
  85. // },
  86. // }),
  87. },
  88. storage: CloudflareStorage({
  89. namespace: env.AuthStorage,
  90. }),
  91. subjects,
  92. async success(ctx, response) {
  93. console.log(response)
  94. let email: string | undefined
  95. if (response.provider === "github") {
  96. const userResponse = await fetch("https://api.github.com/user", {
  97. headers: {
  98. Authorization: `Bearer ${response.tokenset.access}`,
  99. "User-Agent": "opencode",
  100. Accept: "application/vnd.github+json",
  101. },
  102. })
  103. const user = (await userResponse.json()) as { email: string }
  104. email = user.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. },
  131. }