api.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 (
  33. !key.startsWith(`session/info/${sessionID}`) &&
  34. !key.startsWith(`session/message/${sessionID}/`)
  35. )
  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)
  162. return new Response("Error: Share ID is required", { status: 400 })
  163. const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
  164. return stub.fetch(request)
  165. }
  166. if (request.method === "GET" && method === "share_data") {
  167. const id = url.searchParams.get("id")
  168. console.log("share_data", id)
  169. if (!id)
  170. return new Response("Error: Share ID is required", { status: 400 })
  171. const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
  172. const data = await stub.getData()
  173. let info
  174. const messages: Record<string, any> = {}
  175. data.forEach((d) => {
  176. const [root, type, ...splits] = d.key.split("/")
  177. if (root !== "session") return
  178. if (type === "info") {
  179. info = d.content
  180. return
  181. }
  182. if (type === "message") {
  183. const [, messageID] = splits
  184. messages[messageID] = d.content
  185. }
  186. })
  187. return new Response(
  188. JSON.stringify({
  189. info,
  190. messages,
  191. }),
  192. {
  193. headers: { "Content-Type": "application/json" },
  194. },
  195. )
  196. }
  197. },
  198. }