api.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { DurableObject } from "cloudflare:workers"
  2. import { randomUUID } from "node:crypto"
  3. import { jwtVerify, createRemoteJWKSet } from "jose"
  4. import { createAppAuth } from "@octokit/auth-app"
  5. import { Resource } from "sst"
  6. type Env = {
  7. SYNC_SERVER: DurableObjectNamespace<SyncServer>
  8. Bucket: R2Bucket
  9. WEB_DOMAIN: string
  10. }
  11. export class SyncServer extends DurableObject<Env> {
  12. constructor(ctx: DurableObjectState, env: Env) {
  13. super(ctx, env)
  14. }
  15. async fetch() {
  16. console.log("SyncServer subscribe")
  17. const webSocketPair = new WebSocketPair()
  18. const [client, server] = Object.values(webSocketPair)
  19. this.ctx.acceptWebSocket(server)
  20. const data = await this.ctx.storage.list()
  21. Array.from(data.entries())
  22. .filter(([key, _]) => key.startsWith("session/"))
  23. .map(([key, content]) => server.send(JSON.stringify({ key, content })))
  24. return new Response(null, {
  25. status: 101,
  26. webSocket: client,
  27. })
  28. }
  29. async webSocketMessage(ws, message) {}
  30. async webSocketClose(ws, code, reason, wasClean) {
  31. ws.close(code, "Durable Object is closing WebSocket")
  32. }
  33. async publish(key: string, content: any) {
  34. const sessionID = await this.getSessionID()
  35. if (!key.startsWith(`session/info/${sessionID}`) && !key.startsWith(`session/message/${sessionID}/`))
  36. return new Response("Error: Invalid key", { status: 400 })
  37. // store message
  38. await this.env.Bucket.put(`share/${key}.json`, JSON.stringify(content), {
  39. httpMetadata: {
  40. contentType: "application/json",
  41. },
  42. })
  43. await this.ctx.storage.put(key, content)
  44. const clients = this.ctx.getWebSockets()
  45. console.log("SyncServer publish", key, "to", clients.length, "subscribers")
  46. for (const client of clients) {
  47. client.send(JSON.stringify({ key, content }))
  48. }
  49. }
  50. public async share(sessionID: string) {
  51. let secret = await this.getSecret()
  52. if (secret) return secret
  53. secret = randomUUID()
  54. await this.ctx.storage.put("secret", secret)
  55. await this.ctx.storage.put("sessionID", sessionID)
  56. return secret
  57. }
  58. public async getData() {
  59. const data = await this.ctx.storage.list()
  60. return Array.from(data.entries())
  61. .filter(([key, _]) => key.startsWith("session/"))
  62. .map(([key, content]) => ({ key, content }))
  63. }
  64. public async assertSecret(secret: string) {
  65. if (secret !== (await this.getSecret())) throw new Error("Invalid secret")
  66. }
  67. private async getSecret() {
  68. return this.ctx.storage.get<string>("secret")
  69. }
  70. private async getSessionID() {
  71. return this.ctx.storage.get<string>("sessionID")
  72. }
  73. async clear() {
  74. const sessionID = await this.getSessionID()
  75. const list = await this.env.Bucket.list({
  76. prefix: `session/message/${sessionID}/`,
  77. limit: 1000,
  78. })
  79. for (const item of list.objects) {
  80. await this.env.Bucket.delete(item.key)
  81. }
  82. await this.env.Bucket.delete(`session/info/${sessionID}`)
  83. await this.ctx.storage.deleteAll()
  84. }
  85. static shortName(id: string) {
  86. return id.substring(id.length - 8)
  87. }
  88. }
  89. export default {
  90. async fetch(request: Request, env: Env, ctx: ExecutionContext) {
  91. const url = new URL(request.url)
  92. const splits = url.pathname.split("/")
  93. const method = splits[1]
  94. if (request.method === "GET" && method === "") {
  95. return new Response("Hello, world!", {
  96. headers: { "Content-Type": "text/plain" },
  97. })
  98. }
  99. if (request.method === "POST" && method === "share_create") {
  100. const body = await request.json<any>()
  101. const sessionID = body.sessionID
  102. const short = SyncServer.shortName(sessionID)
  103. const id = env.SYNC_SERVER.idFromName(short)
  104. const stub = env.SYNC_SERVER.get(id)
  105. const secret = await stub.share(sessionID)
  106. return new Response(
  107. JSON.stringify({
  108. secret,
  109. url: `https://${env.WEB_DOMAIN}/s/${short}`,
  110. }),
  111. {
  112. headers: { "Content-Type": "application/json" },
  113. },
  114. )
  115. }
  116. if (request.method === "POST" && method === "share_delete") {
  117. const body = await request.json<any>()
  118. const sessionID = body.sessionID
  119. const secret = body.secret
  120. const id = env.SYNC_SERVER.idFromName(SyncServer.shortName(sessionID))
  121. const stub = env.SYNC_SERVER.get(id)
  122. await stub.assertSecret(secret)
  123. await stub.clear()
  124. return new Response(JSON.stringify({}), {
  125. headers: { "Content-Type": "application/json" },
  126. })
  127. }
  128. if (request.method === "POST" && method === "share_delete_admin") {
  129. const id = env.SYNC_SERVER.idFromName("oVF8Rsiv")
  130. const stub = env.SYNC_SERVER.get(id)
  131. await stub.clear()
  132. return new Response(JSON.stringify({}), {
  133. headers: { "Content-Type": "application/json" },
  134. })
  135. }
  136. if (request.method === "POST" && method === "share_sync") {
  137. const body = await request.json<{
  138. sessionID: string
  139. secret: string
  140. key: string
  141. content: any
  142. }>()
  143. const name = SyncServer.shortName(body.sessionID)
  144. const id = env.SYNC_SERVER.idFromName(name)
  145. const stub = env.SYNC_SERVER.get(id)
  146. await stub.assertSecret(body.secret)
  147. await stub.publish(body.key, body.content)
  148. return new Response(JSON.stringify({}), {
  149. headers: { "Content-Type": "application/json" },
  150. })
  151. }
  152. if (request.method === "GET" && method === "share_poll") {
  153. const upgradeHeader = request.headers.get("Upgrade")
  154. if (!upgradeHeader || upgradeHeader !== "websocket") {
  155. return new Response("Error: Upgrade header is required", {
  156. status: 426,
  157. })
  158. }
  159. const id = url.searchParams.get("id")
  160. console.log("share_poll", id)
  161. if (!id) return new Response("Error: Share ID is required", { status: 400 })
  162. const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
  163. return stub.fetch(request)
  164. }
  165. if (request.method === "GET" && method === "share_data") {
  166. const id = url.searchParams.get("id")
  167. console.log("share_data", id)
  168. if (!id) return new Response("Error: Share ID is required", { status: 400 })
  169. const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
  170. const data = await stub.getData()
  171. let info
  172. const messages: Record<string, any> = {}
  173. data.forEach((d) => {
  174. const [root, type, ...splits] = d.key.split("/")
  175. if (root !== "session") return
  176. if (type === "info") {
  177. info = d.content
  178. return
  179. }
  180. if (type === "message") {
  181. const [, messageID] = splits
  182. messages[messageID] = d.content
  183. }
  184. })
  185. return new Response(
  186. JSON.stringify({
  187. info,
  188. messages,
  189. }),
  190. {
  191. headers: { "Content-Type": "application/json" },
  192. },
  193. )
  194. }
  195. if (request.method === "POST" && method === "exchange_github_app_token") {
  196. const EXPECTED_AUDIENCE = "opencode-github-action"
  197. const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
  198. const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks`
  199. // get Authorization header
  200. const authHeader = request.headers.get("Authorization")
  201. const token = authHeader?.replace(/^Bearer /, "")
  202. if (!token)
  203. return new Response(JSON.stringify({ error: "Authorization header is required" }), {
  204. status: 401,
  205. headers: { "Content-Type": "application/json" },
  206. })
  207. // verify token
  208. const JWKS = createRemoteJWKSet(new URL(JWKS_URL))
  209. try {
  210. await jwtVerify(token, JWKS, {
  211. issuer: GITHUB_ISSUER,
  212. audience: EXPECTED_AUDIENCE,
  213. })
  214. } catch (err) {
  215. console.error("Token verification failed:", err)
  216. return new Response(JSON.stringify({ error: "Invalid or expired token" }), {
  217. status: 403,
  218. headers: { "Content-Type": "application/json" },
  219. })
  220. }
  221. // Create app token
  222. const auth = createAppAuth({
  223. appId: Resource.GITHUB_APP_ID.value,
  224. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  225. })
  226. const appAuthentication = await auth({ type: "app" })
  227. return new Response(JSON.stringify({ token: appAuthentication.token }), {
  228. headers: { "Content-Type": "application/json" },
  229. })
  230. }
  231. },
  232. }