auth.ts 4.5 KB

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