api.ts 6.6 KB

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