rxdb-server 17.1.0 → 17.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +4 -0
  3. package/dist/cjs/plugins/adapter-express/index.js +10 -1
  4. package/dist/cjs/plugins/adapter-express/index.js.map +1 -1
  5. package/dist/cjs/plugins/client-rest/index.js +12 -7
  6. package/dist/cjs/plugins/client-rest/index.js.map +1 -1
  7. package/dist/cjs/plugins/replication-server/index.js +1 -1
  8. package/dist/cjs/plugins/replication-server/index.js.map +1 -1
  9. package/dist/cjs/plugins/server/endpoint-replication.js +9 -2
  10. package/dist/cjs/plugins/server/endpoint-replication.js.map +1 -1
  11. package/dist/cjs/plugins/server/endpoint-rest.js +58 -9
  12. package/dist/cjs/plugins/server/endpoint-rest.js.map +1 -1
  13. package/dist/cjs/plugins/server/helper.js +44 -7
  14. package/dist/cjs/plugins/server/helper.js.map +1 -1
  15. package/dist/cjs/plugins/server/index.js +12 -0
  16. package/dist/cjs/plugins/server/index.js.map +1 -1
  17. package/dist/cjs/plugins/server/performance-test.js +276 -0
  18. package/dist/cjs/plugins/server/performance-test.js.map +1 -0
  19. package/dist/esm/plugins/adapter-express/index.js +10 -1
  20. package/dist/esm/plugins/adapter-express/index.js.map +1 -1
  21. package/dist/esm/plugins/client-rest/index.js +12 -7
  22. package/dist/esm/plugins/client-rest/index.js.map +1 -1
  23. package/dist/esm/plugins/replication-server/index.js +1 -1
  24. package/dist/esm/plugins/replication-server/index.js.map +1 -1
  25. package/dist/esm/plugins/server/endpoint-replication.js +10 -3
  26. package/dist/esm/plugins/server/endpoint-replication.js.map +1 -1
  27. package/dist/esm/plugins/server/endpoint-rest.js +59 -10
  28. package/dist/esm/plugins/server/endpoint-rest.js.map +1 -1
  29. package/dist/esm/plugins/server/helper.js +43 -7
  30. package/dist/esm/plugins/server/helper.js.map +1 -1
  31. package/dist/esm/plugins/server/index.js +1 -0
  32. package/dist/esm/plugins/server/index.js.map +1 -1
  33. package/dist/esm/plugins/server/performance-test.js +271 -0
  34. package/dist/esm/plugins/server/performance-test.js.map +1 -0
  35. package/dist/types/plugins/server/helper.d.ts +11 -1
  36. package/dist/types/plugins/server/index.d.ts +1 -0
  37. package/dist/types/plugins/server/performance-test.d.ts +43 -0
  38. package/orga/changelog/README.md +18 -0
  39. package/orga/changelog/fix-cors-wildcard-with-credentials.md +1 -0
  40. package/orga/changelog/fix-false-conflicts-missing-server-only-field.md +1 -0
  41. package/orga/changelog/fix-replication-pull-url-encode-checkpoint.md +1 -0
  42. package/orga/changelog/fix-replication-push-new-doc-server-only-fields-strip.md +1 -0
  43. package/orga/changelog/fix-replication-push-new-doc-server-only-fields.md +1 -0
  44. package/orga/changelog/fix-replication-push-server-only-fields-insert.md +1 -0
  45. package/orga/changelog/fix-rest-client-missing-await.md +1 -0
  46. package/orga/changelog/fix-rest-client-observe-query-url-encode-base64.md +1 -0
  47. package/orga/changelog/fix-rest-delete-server-only-fields-validator.md +1 -0
  48. package/orga/changelog/fix-rest-query-observe-regex-rejection.md +1 -0
  49. package/orga/changelog/fix-rest-set-change-validator-new-doc.md +1 -0
  50. package/orga/changelog/fix-rest-set-document-ownership-check.md +1 -0
  51. package/orga/changelog/fix-rest-set-server-only-fields-insert.md +1 -0
  52. package/orga/changelog/fix-rest-set-server-only-fields-overwrite.md +1 -0
  53. package/package.json +7 -40
@@ -9,8 +9,17 @@ export var RxServerAdapterExpress = {
9
9
  return app;
10
10
  },
11
11
  setCors(serverApp, path, cors) {
12
+ /**
13
+ * Per the CORS spec, `Access-Control-Allow-Origin: *` cannot be combined
14
+ * with `Access-Control-Allow-Credentials: true` - browsers reject such
15
+ * responses on credentialed requests. When the caller opted into the
16
+ * '*' default, reflect the request origin back instead (via `origin: true`),
17
+ * which keeps the "allow from anywhere" semantics while staying compatible
18
+ * with credentials.
19
+ */
20
+ var originOption = cors === '*' ? true : cors;
12
21
  serverApp.use('/' + path + '/*splat', expressCors({
13
- origin: cors,
22
+ origin: originOption,
14
23
  // some legacy browsers (IE11, various SmartTVs) choke on 204
15
24
  optionsSuccessStatus: 200,
16
25
  credentials: true
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["express","expressCors","ensureNotFalsy","getFromMapOrThrow","HTTP_SERVER_BY_EXPRESS","WeakMap","RxServerAdapterExpress","create","app","use","json","setCors","serverApp","path","cors","origin","optionsSuccessStatus","credentials","getRequestBody","req","body","getRequestHeaders","headers","getRequestQuery","query","onRequestClose","fn","on","setResponseHeader","res","k","v","setHeader","responseWrite","data","write","endResponseJson","endResponse","end","closeConnection","response","code","message","error","status","set","JSON","stringify","setSSEHeaders","writeHead","flushHeaders","get","handler","post","all","listen","port","hostname","httpServer","Promise","rej","ret","close","err","setImmediate","emit","closeAllConnections"],"sources":["../../../../src/plugins/adapter-express/index.ts"],"sourcesContent":["import type { RxServerAdapter } from '../server/types';\nimport type { Express } from 'express';\nimport express, { Request, Response } from 'express';\nimport {\n Server as HttpServer\n} from 'http';\nimport expressCors from 'cors';\nimport { ensureNotFalsy, getFromMapOrThrow } from 'rxdb/plugins/core';\n\nexport const HTTP_SERVER_BY_EXPRESS = new WeakMap<Express, HttpServer>();\n\nexport const RxServerAdapterExpress: RxServerAdapter<Express, Request, Response> = {\n async create() {\n const app = express();\n app.use(express.json());\n return app;\n },\n setCors(serverApp, path, cors) {\n serverApp.use('/' + path + '/*splat', expressCors({\n origin: cors,\n // some legacy browsers (IE11, various SmartTVs) choke on 204\n optionsSuccessStatus: 200,\n credentials: true\n }));\n },\n\n getRequestBody(req: Request) {\n return req.body;\n },\n getRequestHeaders(req: Request) {\n return req.headers as any;\n },\n getRequestQuery(req: Request) {\n return req.query;\n },\n onRequestClose(req: Request, fn) {\n req.on('close', () => {\n fn();\n });\n },\n\n setResponseHeader(res: Response, k: string, v: string) {\n res.setHeader(k, v);\n },\n responseWrite(res: Response, data: string) {\n res.write(data);\n },\n endResponseJson(res: Response, data: any) {\n res.json(data);\n },\n endResponse(res: Response) {\n res.end();\n },\n async closeConnection(response: Response, code: number, message: string) {\n const responseWrite = {\n code,\n error: true,\n message\n };\n response.status(code);\n response.set(\"Connection\", \"close\");\n await response.write(JSON.stringify(responseWrite));\n response.end();\n },\n setSSEHeaders(res: Response) {\n res.writeHead(200, {\n /**\n * Use exact these headers to make is less likely\n * for people to have problems.\n * @link https://www.youtube.com/watch?v=0PcMuYGJPzM\n */\n 'Content-Type': 'text/event-stream; charset=utf-8',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache',\n\n /**\n * @link https://github.com/pubkey/rxdb-server/pull/58\n */\n 'access-control-allow-credentials': 'true',\n\n /**\n * Required for nginx\n * @link https://stackoverflow.com/q/61029079/3443137\n */\n 'X-Accel-Buffering': 'no'\n });\n res.flushHeaders();\n },\n\n get(serverApp, path, handler) {\n serverApp.get(path, handler);\n },\n post(serverApp, path, handler) {\n serverApp.post(path, handler);\n },\n all(serverApp, path, handler) {\n serverApp.all(path, handler);\n },\n async listen(serverApp, port, hostname) {\n const httpServer: HttpServer = await new Promise((res, rej) => {\n const ret = ensureNotFalsy(serverApp).listen(port, hostname, () => {\n res(ret);\n });\n });\n HTTP_SERVER_BY_EXPRESS.set(serverApp, httpServer);\n },\n async close(serverApp) {\n const httpServer = getFromMapOrThrow(HTTP_SERVER_BY_EXPRESS, serverApp);\n await new Promise<void>((res, rej) => {\n httpServer.close((err) => {\n if (err) { rej(err); } else { res(); }\n });\n /**\n * By default it will await all ongoing connections\n * before it closes. So we have to close it directly.\n * @link https://stackoverflow.com/a/36830072/3443137\n */\n setImmediate(() => httpServer.emit('close'));\n });\n },\n async closeAllConnections(serverApp) {\n const httpServer = HTTP_SERVER_BY_EXPRESS.get(serverApp);\n if (httpServer) {\n await httpServer.closeAllConnections();\n }\n }\n};\n"],"mappings":"AAEA,OAAOA,OAAO,MAA6B,SAAS;AAIpD,OAAOC,WAAW,MAAM,MAAM;AAC9B,SAASC,cAAc,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;EACD,MAAMG,MAAMA,CAAC3C,SAAS,EAAE4C,IAAI,EAAEC,QAAQ,EAAE;IACpC,IAAMC,UAAsB,GAAG,MAAM,IAAIC,OAAO,CAAC,CAAC9B,GAAG,EAAE+B,GAAG,KAAK;MAC3D,IAAMC,GAAG,GAAG3D,cAAc,CAACU,SAAS,CAAC,CAAC2C,MAAM,CAACC,IAAI,EAAEC,QAAQ,EAAE,MAAM;QAC/D5B,GAAG,CAACgC,GAAG,CAAC;MACZ,CAAC,CAAC;IACN,CAAC,CAAC;IACFzD,sBAAsB,CAACyC,GAAG,CAACjC,SAAS,EAAE8C,UAAU,CAAC;EACrD,CAAC;EACD,MAAMI,KAAKA,CAAClD,SAAS,EAAE;IACnB,IAAM8C,UAAU,GAAGvD,iBAAiB,CAACC,sBAAsB,EAAEQ,SAAS,CAAC;IACvE,MAAM,IAAI+C,OAAO,CAAO,CAAC9B,GAAG,EAAE+B,GAAG,KAAK;MAClCF,UAAU,CAACI,KAAK,CAAEC,GAAG,IAAK;QACtB,IAAIA,GAAG,EAAE;UAAEH,GAAG,CAACG,GAAG,CAAC;QAAE,CAAC,MAAM;UAAElC,GAAG,CAAC,CAAC;QAAE;MACzC,CAAC,CAAC;MACF;AACZ;AACA;AACA;AACA;MACYmC,YAAY,CAAC,MAAMN,UAAU,CAACO,IAAI,CAAC,OAAO,CAAC,CAAC;IAChD,CAAC,CAAC;EACN,CAAC;EACD,MAAMC,mBAAmBA,CAACtD,SAAS,EAAE;IACjC,IAAM8C,UAAU,GAAGtD,sBAAsB,CAAC+C,GAAG,CAACvC,SAAS,CAAC;IACxD,IAAI8C,UAAU,EAAE;MACZ,MAAMA,UAAU,CAACQ,mBAAmB,CAAC,CAAC;IAC1C;EACJ;AACJ,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["express","expressCors","ensureNotFalsy","getFromMapOrThrow","HTTP_SERVER_BY_EXPRESS","WeakMap","RxServerAdapterExpress","create","app","use","json","setCors","serverApp","path","cors","originOption","origin","optionsSuccessStatus","credentials","getRequestBody","req","body","getRequestHeaders","headers","getRequestQuery","query","onRequestClose","fn","on","setResponseHeader","res","k","v","setHeader","responseWrite","data","write","endResponseJson","endResponse","end","closeConnection","response","code","message","error","status","set","JSON","stringify","setSSEHeaders","writeHead","flushHeaders","get","handler","post","all","listen","port","hostname","httpServer","Promise","rej","ret","close","err","setImmediate","emit","closeAllConnections"],"sources":["../../../../src/plugins/adapter-express/index.ts"],"sourcesContent":["import type { RxServerAdapter } from '../server/types';\nimport type { Express } from 'express';\nimport express, { Request, Response } from 'express';\nimport {\n Server as HttpServer\n} from 'http';\nimport expressCors from 'cors';\nimport { ensureNotFalsy, getFromMapOrThrow } from 'rxdb/plugins/core';\n\nexport const HTTP_SERVER_BY_EXPRESS = new WeakMap<Express, HttpServer>();\n\nexport const RxServerAdapterExpress: RxServerAdapter<Express, Request, Response> = {\n async create() {\n const app = express();\n app.use(express.json());\n return app;\n },\n setCors(serverApp, path, cors) {\n /**\n * Per the CORS spec, `Access-Control-Allow-Origin: *` cannot be combined\n * with `Access-Control-Allow-Credentials: true` - browsers reject such\n * responses on credentialed requests. When the caller opted into the\n * '*' default, reflect the request origin back instead (via `origin: true`),\n * which keeps the \"allow from anywhere\" semantics while staying compatible\n * with credentials.\n */\n const originOption: expressCors.CorsOptions['origin'] = cors === '*' ? true : cors;\n serverApp.use('/' + path + '/*splat', expressCors({\n origin: originOption,\n // some legacy browsers (IE11, various SmartTVs) choke on 204\n optionsSuccessStatus: 200,\n credentials: true\n }));\n },\n\n getRequestBody(req: Request) {\n return req.body;\n },\n getRequestHeaders(req: Request) {\n return req.headers as any;\n },\n getRequestQuery(req: Request) {\n return req.query;\n },\n onRequestClose(req: Request, fn) {\n req.on('close', () => {\n fn();\n });\n },\n\n setResponseHeader(res: Response, k: string, v: string) {\n res.setHeader(k, v);\n },\n responseWrite(res: Response, data: string) {\n res.write(data);\n },\n endResponseJson(res: Response, data: any) {\n res.json(data);\n },\n endResponse(res: Response) {\n res.end();\n },\n async closeConnection(response: Response, code: number, message: string) {\n const responseWrite = {\n code,\n error: true,\n message\n };\n response.status(code);\n response.set(\"Connection\", \"close\");\n await response.write(JSON.stringify(responseWrite));\n response.end();\n },\n setSSEHeaders(res: Response) {\n res.writeHead(200, {\n /**\n * Use exact these headers to make is less likely\n * for people to have problems.\n * @link https://www.youtube.com/watch?v=0PcMuYGJPzM\n */\n 'Content-Type': 'text/event-stream; charset=utf-8',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache',\n\n /**\n * @link https://github.com/pubkey/rxdb-server/pull/58\n */\n 'access-control-allow-credentials': 'true',\n\n /**\n * Required for nginx\n * @link https://stackoverflow.com/q/61029079/3443137\n */\n 'X-Accel-Buffering': 'no'\n });\n res.flushHeaders();\n },\n\n get(serverApp, path, handler) {\n serverApp.get(path, handler);\n },\n post(serverApp, path, handler) {\n serverApp.post(path, handler);\n },\n all(serverApp, path, handler) {\n serverApp.all(path, handler);\n },\n async listen(serverApp, port, hostname) {\n const httpServer: HttpServer = await new Promise((res, rej) => {\n const ret = ensureNotFalsy(serverApp).listen(port, hostname, () => {\n res(ret);\n });\n });\n HTTP_SERVER_BY_EXPRESS.set(serverApp, httpServer);\n },\n async close(serverApp) {\n const httpServer = getFromMapOrThrow(HTTP_SERVER_BY_EXPRESS, serverApp);\n await new Promise<void>((res, rej) => {\n httpServer.close((err) => {\n if (err) { rej(err); } else { res(); }\n });\n /**\n * By default it will await all ongoing connections\n * before it closes. So we have to close it directly.\n * @link https://stackoverflow.com/a/36830072/3443137\n */\n setImmediate(() => httpServer.emit('close'));\n });\n },\n async closeAllConnections(serverApp) {\n const httpServer = HTTP_SERVER_BY_EXPRESS.get(serverApp);\n if (httpServer) {\n await httpServer.closeAllConnections();\n }\n }\n};\n"],"mappings":"AAEA,OAAOA,OAAO,MAA6B,SAAS;AAIpD,OAAOC,WAAW,MAAM,MAAM;AAC9B,SAASC,cAAc,EAAEC,iBAAiB,QAAQ,mBAAmB;AA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};
25
25
  _proto.observeQuery = function observeQuery(query) {
26
26
  var result = new Subject();
27
- var queryAsBase64 = btoa(JSON.stringify(query));
27
+ // Standard base64 uses '+' and '/'; both are URL-reserved and a raw
28
+ // '+' in the query string is decoded as a space by the server's
29
+ // URL parser. Without encoding, the server's atob() then rejects
30
+ // the corrupted string with "Invalid character" and the SSE
31
+ // connection silently never delivers any document.
32
+ var queryAsBase64 = encodeURIComponent(btoa(JSON.stringify(query)));
28
33
  var eventSource = new this.eventSource(this.endpointUrl + '/query/observe?query=' + queryAsBase64, {
29
34
  withCredentials: true,
30
35
  /**
@@ -41,18 +46,18 @@ export var RxRestClient = /*#__PURE__*/function () {
41
46
  };
42
47
  return result.asObservable();
43
48
  };
44
- _proto.get = function get(ids) {
45
- var response = postRequest(this.endpointUrl + '/get', ids, this.headers);
49
+ _proto.get = async function get(ids) {
50
+ var response = await postRequest(this.endpointUrl + '/get', ids, this.headers);
46
51
  this.handleError(response);
47
52
  return response;
48
53
  };
49
- _proto.set = function set(docs) {
50
- var response = postRequest(this.endpointUrl + '/set', docs, this.headers);
54
+ _proto.set = async function set(docs) {
55
+ var response = await postRequest(this.endpointUrl + '/set', docs, this.headers);
51
56
  this.handleError(response);
52
57
  return response;
53
58
  };
54
- _proto.delete = function _delete(ids) {
55
- var response = postRequest(this.endpointUrl + '/delete', ids, this.headers);
59
+ _proto.delete = async function _delete(ids) {
60
+ var response = await postRequest(this.endpointUrl + '/delete', ids, this.headers);
56
61
  this.handleError(response);
57
62
  return response;
58
63
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["postRequest","Subject","EventSource","customFetchWithFixedHeaders","RxRestClient","endpointUrl","headers","eventSource","_proto","prototype","setHeaders","handleError","response","error","Error","JSON","stringify","query","observeQuery","result","queryAsBase64","btoa","withCredentials","fetch","onmessage","event","eventData","parse","data","next","asObservable","get","ids","set","docs","delete","createRestClient"],"sources":["../../../../src/plugins/client-rest/index.ts"],"sourcesContent":["import { ById, MangoQuery } from 'rxdb/plugins/core';\nimport { postRequest } from './utils.ts';\nimport { Observable, Subject } from 'rxjs';\nimport { EventSource } from 'eventsource';\nimport { customFetchWithFixedHeaders } from '../../utils.ts';\n\nexport class RxRestClient<RxDocType> {\n constructor(\n public readonly endpointUrl: string,\n public headers: ById<string> = {},\n public readonly eventSource: typeof EventSource | any = EventSource\n ) { }\n\n setHeaders(headers: ById<string>) {\n this.headers = headers;\n }\n\n handleError(response: any) {\n if (response.error) {\n throw new Error('Server returned an error ' + JSON.stringify(response));\n }\n }\n\n async query(query: MangoQuery<RxDocType>): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/query',\n query,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n observeQuery(query: MangoQuery<RxDocType>): Observable<RxDocType[]> {\n const result = new Subject<RxDocType[]>;\n const queryAsBase64 = btoa(JSON.stringify(query));\n const eventSource: EventSource = new this.eventSource(\n this.endpointUrl + '/query/observe?query=' + queryAsBase64,\n {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n fetch: customFetchWithFixedHeaders(this.headers)\n }\n );\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n result.next(eventData);\n };\n return result.asObservable();\n }\n\n get(ids: string[]): Promise<{ documents: RxDocType[] }> {\n const response = postRequest(\n this.endpointUrl + '/get',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n set(docs: RxDocType[]) {\n const response = postRequest(\n this.endpointUrl + '/set',\n docs,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n delete(ids: string[]) {\n const response = postRequest(\n this.endpointUrl + '/delete',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n}\n\nexport function createRestClient<RxDocType>(\n endpointUrl: string,\n headers: ById<string>,\n eventSource: typeof EventSource | any = EventSource\n) {\n\n return new RxRestClient<RxDocType>(\n end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W,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAA,OAAAR,YAAA;AAAA;AAGL,OAAO,SAASgC,gBAAgBA,CAC5B/B,WAAmB,EACnBC,OAAqB,EACrBC,WAAqC,GAAGL,WAAW,EACrD;EAEE,OAAO,IAAIE,YAAY,CACnBC,WAAW,EACXC,OAAO,EACPC,WACJ,CAAC;AACL;AAGA,cAAc,YAAY","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["postRequest","Subject","EventSource","customFetchWithFixedHeaders","RxRestClient","endpointUrl","headers","eventSource","_proto","prototype","setHeaders","handleError","response","error","Error","JSON","stringify","query","observeQuery","result","queryAsBase64","encodeURIComponent","btoa","withCredentials","fetch","onmessage","event","eventData","parse","data","next","asObservable","get","ids","set","docs","delete","createRestClient"],"sources":["../../../../src/plugins/client-rest/index.ts"],"sourcesContent":["import { ById, MangoQuery } from 'rxdb/plugins/core';\nimport { postRequest } from './utils.ts';\nimport { Observable, Subject } from 'rxjs';\nimport { EventSource } from 'eventsource';\nimport { customFetchWithFixedHeaders } from '../../utils.ts';\n\nexport class RxRestClient<RxDocType> {\n constructor(\n public readonly endpointUrl: string,\n public headers: ById<string> = {},\n public readonly eventSource: typeof EventSource | any = EventSource\n ) { }\n\n setHeaders(headers: ById<string>) {\n this.headers = headers;\n }\n\n handleError(response: any) {\n if (response.error) {\n throw new Error('Server returned an error ' + JSON.stringify(response));\n }\n }\n\n async query(query: MangoQuery<RxDocType>): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/query',\n query,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n observeQuery(query: MangoQuery<RxDocType>): Observable<RxDocType[]> {\n const result = new Subject<RxDocType[]>;\n // Standard base64 uses '+' and '/'; both are URL-reserved and a raw\n // '+' in the query string is decoded as a space by the server's\n // URL parser. Without encoding, the server's atob() then rejects\n // the corrupted string with \"Invalid character\" and the SSE\n // connection silently never delivers any document.\n const queryAsBase64 = encodeURIComponent(btoa(JSON.stringify(query)));\n const eventSource: EventSource = new this.eventSource(\n this.endpointUrl + '/query/observe?query=' + queryAsBase64,\n {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n fetch: customFetchWithFixedHeaders(this.headers)\n }\n );\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n result.next(eventData);\n };\n return result.asObservable();\n }\n\n async get(ids: string[]): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/get',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n async set(docs: RxDocType[]) {\n const response = await postRequest(\n this.endpointUrl + '/set',\n docs,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n async delete(ids: string[]) {\n const response = await postRequest(\n this.endpointUrl + '/delete',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n}\n\nexport function createRestClient<RxDocType>(\n endpointUrl: string,\n headers: ById<string>,\n eventSource: typeof EventSource | any = EventSource\n) {\n\n return new RxRestClient<RxDocType>(\n endpointUrl,\n headers,\n eventSource\n );\n}\n\n\nexport * from './utils.ts';\n"],"mappings":"AACA,SAASA,WAAW,QAAQ,YAAY;AACxC,SAAqBC,OAAO,QAAQ,MAAM;AAC1C,SAASC,WAAW,QAAQ,aAAa;AACzC,SAASC,2BAA2B,QAAQ,gBAAgB;AAE5D,WAAaC,YAAY;EACrB,SAAAA,aACoBC,WAAmB,EAC5BC,OAAqB,GAAG,CAAC,CAAC,EACjBC,WAAqC,GAAGL,WAAW,EACrE;IAAA,KAHkBG,WAAmB,GAAnBA,WAAmB;IAAA,KAC5BC,OAAqB,GAArBA,OAAqB;IAAA,KACZC,WAAqC,GAArCA,WAAqC;EACrD;EAAC,IAAAC,MAAA,GAAAJ,YAAA,CAAAK,SAAA;EAAAD,MAAA,CAELE,UAAU,GAAV,SAAAA,UAAU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,CAACY,YAAY,CAAC,CAAC;EAChC,CAAC;EAAAvB,MAAA,CAEKwB,GAAG,GAAT,eAAMA,GAAGA,CAACC,GAAa,EAAuC;IAC1D,IAAMrB,QAAQ,GAAG,MAAMZ,WAAW,CAC9B,IAAI,CAACK,WAAW,GAAG,MAAM,EACzB4B,GAAG,EACH,IAAI,CAAC3B,OACT,CAAC;IACD,IAAI,CAACK,WAAW,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAAJ,MAAA,CAEK0B,GAAG,GAAT,eAAMA,GAAGA,CAACC,IAAiB,EAAE;IACzB,IAAMvB,QAAQ,GAAG,MAAMZ,WAAW,CAC9B,IAAI,CAACK,WAAW,GAAG,MAAM,EACzB8B,IAAI,EACJ,IAAI,CAAC7B,OACT,CAAC;IACD,IAAI,CAACK,WAAW,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAAJ,MAAA,CAEK4B,MAAM,GAAZ,eAAMA,OAAMA,CAACH,GAAa,EAAE;IACxB,IAAMrB,QAAQ,GAAG,MAAMZ,WAAW,CAC9B,IAAI,CAACK,WAAW,GAAG,SAAS,EAC5B4B,GAAG,EACH,IAAI,CAAC3B,OACT,CAAC;IACD,IAAI,CAACK,WAAW,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAA,OAAAR,YAAA;AAAA;AAGL,OAAO,SAASiC,gBAAgBA,CAC5BhC,WAAmB,EACnBC,OAAqB,EACrBC,WAAqC,GAAGL,WAAW,EACrD;EAEE,OAAO,IAAIE,YAAY,CACnBC,WAAW,EACXC,OAAO,EACPC,WACJ,CAAC;AACL;AAGA,cAAc,YAAY","ignoreList":[]}
@@ -56,7 +56,7 @@ export function replicateServer(options) {
56
56
  async handler(checkpointOrNull, batchSize) {
57
57
  var lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;
58
58
  var id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';
59
- var url = options.url + ("/pull?lwt=" + lwt + "&id=" + id + "&limit=" + batchSize);
59
+ var url = options.url + ("/pull?lwt=" + lwt + "&id=" + encodeURIComponent(id) + "&limit=" + batchSize);
60
60
  var response = await fetch(url, {
61
61
  method: 'GET',
62
62
  credentials: 'include',
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["ensureNotFalsy","flatClone","promiseWait","addRxPlugin","newRxError","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","Subject","parseResponse","EventSource","customFetchWithFixedHeaders","RxServerReplicationState","_RxReplicationState","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","headers","_this","call","outdatedClient$","unauthorized$","forbidden$","onCancel","complete","_inheritsLoose","_proto","prototype","setHeaders","replicateServer","options","name","args","waitForLeadership","pullStream$","replicationPrimitivesPull","handler","checkpointOrNull","batchSize","lwt","id","url","response","fetch","method","credentials","Object","assign","replicationState","data","documents","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","changeRows","body","JSON","stringify","conflictsArray","startBefore","start","bind","useEventSource","eventSource","refreshEventSource","withCredentials","onerror","err","code","next","close","then","onopen","x","onmessage","event","eventData","parse"],"sources":["../../../../src/plugins/replication-server/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n flatClone,\n promiseWait,\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationPullStreamItem,\n ById,\n addRxPlugin,\n newRxError,\n WithDeletedAndAttachments\n} from 'rxdb/plugins/core';\nimport { RxDBLeaderElectionPlugin } from 'rxdb/plugins/leader-election';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from 'rxdb/plugins/replication';\n\nimport { Subject } from 'rxjs';\nimport type {\n RxServerCheckpoint,\n ServerSyncOptions\n} from './types.ts';\nimport { parseResponse } from './helpers.ts';\nimport { EventSource } from 'eventsource';\nimport { customFetchWithFixedHeaders } from '../../utils.ts';\n\nexport * from './types.ts';\n\nexport class RxServerReplicationState<RxDocType> extends RxReplicationState<RxDocType, RxServerCheckpoint> {\n public readonly outdatedClient$ = new Subject<void>();\n public readonly unauthorized$ = new Subject<void>();\n public readonly forbidden$ = new Subject<void>();\n\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection<RxDocType, unknown, unknown, unknown>,\n public readonly pull?: ReplicationPullOptions<RxDocType, RxServerCheckpoint>,\n public readonly push?: ReplicationPushOptions<RxDocType>,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true,\n public headers: ById<string> = {}\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n this.onCancel.push(() => {\n this.outdatedClient$.complete();\n this.unauthorized$.complete();\n this.forbidden$.complete();\n });\n }\n\n setHeaders(headers: ById<string>): void {\n this.headers = flatClone(headers);\n }\n}\n\nexport function replicateServer<RxDocType>(\n options: ServerSyncOptions<RxDocType>\n): RxServerReplicationState<RxDocType> {\n\n if (!options.pull && !options.push) {\n throw newRxError('UT3', {\n collection: options.collection.name,\n args: {\n replicationIdentifier: options.replicationIdentifier\n }\n });\n }\n\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, RxServerCheckpoint>> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, RxServerCheckpoint> | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(checkpointOrNull, batchSize) {\n const lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;\n const id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';\n const url = options.url + `/pull?lwt=${lwt}&id=${id}&limit=${batchSize}`;\n const response = await fetch(url, {\n method: 'GET',\n credentials: 'include',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n });\n const data = await parseResponse(replicationState, response);\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions<RxDocType> | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(changeRows) {\n const response = await fetch(options.url + '/push', {\n method: 'POST',\n credentials: 'include',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await parseResponse(replicationState, response);\n return conflictsArray;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxServerReplicationState<RxDocType>(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart,\n options.headers\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = async () => {\n const useEventSource: typeof EventSource = options.eventSource ? options.eventSource : EventSource;\n let eventSource: EventSource;\n const refreshEventSource = () => {\n eventSource = new useEventSource(options.url + '/pullStream', {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n fetch: customFetchWithFixedHeaders(replicationState.headers)\n });\n // TODO check for 426 errors and handle them\n eventSource.onerror = (err) => {\n if (err.code === 401) {\n replicationState.unauthorized$.next();\n eventSource.close();\n promiseWait(replicationState.retryTime).then(() => refreshEventSource());\n } else {\n pullStream$.next('RESYNC');\n }\n };\n eventSource.onopen = (x) => {\n pullStream$.next('RESYNC');\n }\n eventSource.onmessage = event => {\n const eventData: { documents: WithDeletedAndAttachments<RxDocType>[]; checkpoint: RxServerCheckpoint; } = JSON.parse(event.data);\n pullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n };\n }\n refreshEventSource();\n\n replicationState.onCancel.push(() => eventSource && eventSource.close());\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA,SACIA,cAAc,EACdC,SAAS,EACTC,WAAW,EAMXC,WAAW,EACXC,UAAU,QAEP,mBAAmB;AAC1B,SAASC,wBAAwB,QAAQ,8BAA8B;AACvE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,0BAA0B;AAEjC,SAASC,OAAO,QAAQ,MAAM;AAK9B,SAASC,aAAa,QAAQ,cAAc;AAC5C,SAASC,WAAW,QAAQ,aAAa;AACzC,SAASC,2BAA2B,QAAQ,gBAAgB;AAE5D,cAAc,YAAY;AAE1B,WAAaC,wBAAwB,0BAAAC,mBAAA;EAKjC,SAAAD,yBACoBE,qBAA6B,EAC7BC,UAA8D,EAC9DC,IAA4D,EAC5DC,IAAwC,EACxCC,IAAa,GAAG,IAAI,EAC7BC,SAAiB,GAAG,IAAI,GAAG,CAAC,EAC5BC,SAAkB,GAAG,IAAI,EACzBC,OAAqB,GAAG,CAAC,CAAC,EACnC;IAAA,IAAAC,KAAA;IACEA,KAAA,GAAAT,mBAAA,CAAAU,IAAA,OACIT,qBAAqB,EACrBC,UAAU,EACV,UAAU,EACVC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;IAACE,KAAA,CAvBUE,eAAe,GAAG,IAAIhB,OAAO,CAAO,CAAC;IAAAc,KAAA,CACrCG,aAAa,GAAG,IAAIjB,OAAO,CAAO,CAAC;IAAAc,KAAA,CACnCI,UAAU,GAAG,IAAIlB,OAAO,CAAO,CAAC;IAAAc,KAAA,CAG5BR,qBAA6B,GAA7BA,qBAA6B;IAAAQ,KAAA,CAC7BP,U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,IAAIA,WAAW,CAACO,KAAK,CAAC,CAAC,CAAC;MACxE,OAAOX,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA1D,4BAA4B,CAAC2B,OAAO,CAACG,iBAAiB,EAAEe,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["ensureNotFalsy","flatClone","promiseWait","addRxPlugin","newRxError","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","Subject","parseResponse","EventSource","customFetchWithFixedHeaders","RxServerReplicationState","_RxReplicationState","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","headers","_this","call","outdatedClient$","unauthorized$","forbidden$","onCancel","complete","_inheritsLoose","_proto","prototype","setHeaders","replicateServer","options","name","args","waitForLeadership","pullStream$","replicationPrimitivesPull","handler","checkpointOrNull","batchSize","lwt","id","url","encodeURIComponent","response","fetch","method","credentials","Object","assign","replicationState","data","documents","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","changeRows","body","JSON","stringify","conflictsArray","startBefore","start","bind","useEventSource","eventSource","refreshEventSource","withCredentials","onerror","err","code","next","close","then","onopen","x","onmessage","event","eventData","parse"],"sources":["../../../../src/plugins/replication-server/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n flatClone,\n promiseWait,\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationPullStreamItem,\n ById,\n addRxPlugin,\n newRxError,\n WithDeletedAndAttachments\n} from 'rxdb/plugins/core';\nimport { RxDBLeaderElectionPlugin } from 'rxdb/plugins/leader-election';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from 'rxdb/plugins/replication';\n\nimport { Subject } from 'rxjs';\nimport type {\n RxServerCheckpoint,\n ServerSyncOptions\n} from './types.ts';\nimport { parseResponse } from './helpers.ts';\nimport { EventSource } from 'eventsource';\nimport { customFetchWithFixedHeaders } from '../../utils.ts';\n\nexport * from './types.ts';\n\nexport class RxServerReplicationState<RxDocType> extends RxReplicationState<RxDocType, RxServerCheckpoint> {\n public readonly outdatedClient$ = new Subject<void>();\n public readonly unauthorized$ = new Subject<void>();\n public readonly forbidden$ = new Subject<void>();\n\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection<RxDocType, unknown, unknown, unknown>,\n public readonly pull?: ReplicationPullOptions<RxDocType, RxServerCheckpoint>,\n public readonly push?: ReplicationPushOptions<RxDocType>,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true,\n public headers: ById<string> = {}\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n this.onCancel.push(() => {\n this.outdatedClient$.complete();\n this.unauthorized$.complete();\n this.forbidden$.complete();\n });\n }\n\n setHeaders(headers: ById<string>): void {\n this.headers = flatClone(headers);\n }\n}\n\nexport function replicateServer<RxDocType>(\n options: ServerSyncOptions<RxDocType>\n): RxServerReplicationState<RxDocType> {\n\n if (!options.pull && !options.push) {\n throw newRxError('UT3', {\n collection: options.collection.name,\n args: {\n replicationIdentifier: options.replicationIdentifier\n }\n });\n }\n\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, RxServerCheckpoint>> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, RxServerCheckpoint> | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(checkpointOrNull, batchSize) {\n const lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;\n const id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';\n const url = options.url + `/pull?lwt=${lwt}&id=${encodeURIComponent(id)}&limit=${batchSize}`;\n const response = await fetch(url, {\n method: 'GET',\n credentials: 'include',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n });\n const data = await parseResponse(replicationState, response);\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions<RxDocType> | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(changeRows) {\n const response = await fetch(options.url + '/push', {\n method: 'POST',\n credentials: 'include',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await parseResponse(replicationState, response);\n return conflictsArray;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxServerReplicationState<RxDocType>(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart,\n options.headers\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = async () => {\n const useEventSource: typeof EventSource = options.eventSource ? options.eventSource : EventSource;\n let eventSource: EventSource;\n const refreshEventSource = () => {\n eventSource = new useEventSource(options.url + '/pullStream', {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n fetch: customFetchWithFixedHeaders(replicationState.headers)\n });\n // TODO check for 426 errors and handle them\n eventSource.onerror = (err) => {\n if (err.code === 401) {\n replicationState.unauthorized$.next();\n eventSource.close();\n promiseWait(replicationState.retryTime).then(() => refreshEventSource());\n } else {\n pullStream$.next('RESYNC');\n }\n };\n eventSource.onopen = (x) => {\n pullStream$.next('RESYNC');\n }\n eventSource.onmessage = event => {\n const eventData: { documents: WithDeletedAndAttachments<RxDocType>[]; checkpoint: RxServerCheckpoint; } = JSON.parse(event.data);\n pullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n };\n }\n refreshEventSource();\n\n replicationState.onCancel.push(() => eventSource && eventSource.close());\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA,SACIA,cAAc,EACdC,SAAS,EACTC,WAAW,EAMXC,WAAW,EACXC,UAAU,QAEP,mBAAmB;AAC1B,SAASC,wBAAwB,QAAQ,8BAA8B;AACvE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,0BAA0B;AAEjC,SAASC,OAAO,QAAQ,MAAM;AAK9B,SAASC,aAAa,QAAQ,cAAc;AAC5C,SAASC,WAAW,QAAQ,aAAa;AACzC,SAASC,2BAA2B,QAAQ,gBAAgB;AAE5D,cAAc,YAAY;AAE1B,WAAaC,wBAAwB,0BAAAC,mBAAA;EAKjC,SAAAD,yBACoBE,qBAA6B,EAC7BC,UAA8D,EAC9DC,IAA4D,EAC5DC,IAAwC,EACxCC,IAAa,GAAG,IAAI,EAC7BC,SAAiB,GAAG,IAAI,GAAG,CAAC,EAC5BC,SAAkB,GAAG,IAAI,EACzBC,OAAqB,GAAG,CAAC,CAAC,EACnC;IAAA,IAAAC,KAAA;IACEA,KAAA,GAAAT,mBAAA,CAAAU,IAAA,OACIT,qBAAqB,EACrBC,UAAU,EACV,UAAU,EACVC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;IAACE,KAAA,CAvBUE,eAAe,GAAG,IAAIhB,OAAO,CAAO,CAAC;IAAAc,KAAA,CACrCG,aAAa,GAAG,IAAIjB,OAAO,CAAO,CAAC;IAAAc,KAAA,CACnCI,UAAU,GAAG,IAAIlB,OAAO,CAAO,CAAC;IAAAc,KAAA,CAG5BR,qBAA6B,GAA7BA,qBAA6B;IAA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1B,QAAQ,CAACV,IAAI,CAAC,MAAMqD,WAAW,IAAIA,WAAW,CAACO,KAAK,CAAC,CAAC,CAAC;MACxE,OAAOX,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA3D,4BAA4B,CAAC2B,OAAO,CAACG,iBAAiB,EAAEgB,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]}
@@ -2,7 +2,7 @@ import { prepareQuery, getChangedDocumentsSinceQuery } from 'rxdb/plugins/core';
2
2
  import { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';
3
3
  import { filter, mergeMap } from 'rxjs';
4
4
  import { ensureNotFalsy, lastOfArray } from 'rxdb/plugins/utils';
5
- import { docContainsServerOnlyFields, doesContainRegexQuerySelector, getAuthDataByRequest, getDocAllowedMatcher, mergeServerDocumentFieldsMonad, removeServerOnlyFieldsMonad, setCors } from "./helper.js";
5
+ import { docContainsServerOnlyFields, doesContainRegexQuerySelector, getAuthDataByRequest, getDocAllowedMatcher, mergeServerDocumentFieldsMonad, removeServerOnlyFieldsMonad, setCors, stripServerOnlyFieldsMonad } from "./helper.js";
6
6
  export var RxServerReplicationEndpoint = function RxServerReplicationEndpoint(server, name, collection, queryModifier, changeValidator, serverOnlyFields, cors) {
7
7
  this.type = 'replication';
8
8
  this.server = server;
@@ -30,6 +30,7 @@ export var RxServerReplicationEndpoint = function RxServerReplicationEndpoint(se
30
30
  };
31
31
  var removeServerOnlyFields = removeServerOnlyFieldsMonad(this.serverOnlyFields);
32
32
  var mergeServerDocumentFields = mergeServerDocumentFieldsMonad(this.serverOnlyFields);
33
+ var stripServerOnlyFields = stripServerOnlyFieldsMonad(this.serverOnlyFields);
33
34
  this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pull', async (req, res) => {
34
35
  var authData = await getAuthDataByRequest(this.server, req, res);
35
36
  if (!authData) {
@@ -100,8 +101,14 @@ export var RxServerReplicationEndpoint = function RxServerReplicationEndpoint(se
100
101
  hasInvalidChange = true;
101
102
  }
102
103
  var serverDoc = currentStateDocs.get(id);
104
+ // When the document does not yet exist on the server, strip
105
+ // server-only fields from the new document state so a client
106
+ // cannot populate them on insert. Updates of existing docs
107
+ // are already protected because mergeServerDocumentFields
108
+ // overwrites those fields with the stored server value.
109
+ var newDocumentState = serverDoc ? mergeServerDocumentFields(row.newDocumentState, serverDoc) : stripServerOnlyFields(row.newDocumentState);
103
110
  return {
104
- newDocumentState: mergeServerDocumentFields(row.newDocumentState, serverDoc),
111
+ newDocumentState,
105
112
  assumedMasterState: mergeServerDocumentFields(row.assumedMasterState, serverDoc)
106
113
  };
107
114
  });
@@ -111,7 +118,7 @@ export var RxServerReplicationEndpoint = function RxServerReplicationEndpoint(se
111
118
  }
112
119
  var conflicts = await replicationHandler.masterWrite(useRows);
113
120
  adapter.setResponseHeader(res, 'Content-Type', 'application/json');
114
- adapter.endResponseJson(res, conflicts);
121
+ adapter.endResponseJson(res, conflicts.map(c => removeServerOnlyFields(c)));
115
122
  });
116
123
  this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pullStream', async (req, res) => {
117
124
  var authData = await getAuthDataByRequest(this.server, req, res);
@@ -1 +1 @@
1
- {"version":3,"file":"endpoint-replication.js","names":["prepareQuery","getChangedDocumentsSinceQuery","getReplicationHandlerByCollection","filter","mergeMap","ensureNotFalsy","lastOfArray","docContainsServerOnlyFields","doesContainRegexQuerySelector","getAuthDataByRequest","getDocAllowedMatcher","mergeServerDocumentFieldsMonad","removeServerOnlyFieldsMonad","setCors","RxServerReplicationEndpoint","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","type","adapter","join","blockPreviousReplicationVersionPaths","schema","version","urlPath","primaryPath","replicationHandler","database","authData","query","selector","Error","change","assumedMasterState","newDocumentState","removeServerOnlyFields","mergeServerDocumentFields","get","serverApp","req","res","urlQuery","getRequestQuery","id","lwt","parseFloat","limit","parseInt","plainQuery","storageInstance","useQueryChanges","prepared","jsonSchema","result","newCheckpoint","documents","length","_meta","responseDocuments","map","d","setResponseHeader","endResponseJson","checkpoint","post","docDataMatcherWrite","rows","getRequestBody","ids","forEach","row","push","nonAllowedRow","find","closeConnection","hasInvalidChange","currentStateDocsArray","findDocumentsById","currentStateDocs","Map","set","useRows","isChangeValid","serverDoc","conflicts","masterWrite","setSSEHeaders","docDataMatcherStream","subscription","masterChangeStream$","pipe","changes","authHandler","getRequestHeaders","err","useDocs","f","subscribe","filteredAndModified","responseWrite","JSON","stringify","onRequestClose","unsubscribe","endResponse","path","currentVersion","v","_loop","subPath","all"],"sources":["../../../../src/plugins/server/endpoint-replication.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n StringKeys,\n prepareQuery,\n getChangedDocumentsSinceQuery,\n RxDocumentData\n} from 'rxdb/plugins/core';\nimport { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerAuthData,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n lastOfArray\n} from 'rxdb/plugins/utils';\n\nimport {\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getAuthDataByRequest,\n getDocAllowedMatcher,\n mergeServerDocumentFieldsMonad,\n removeServerOnlyFieldsMonad,\n setCors\n} from './helper.ts';\nimport type { RxServerCheckpoint } from '../replication-server/types.ts';\n\nexport type RxReplicationEndpointMessageType = {\n id: string;\n method: StringKeys<RxReplicationHandler<any, any>> | 'auth';\n params: any[];\n};\n\nexport class RxServerReplicationEndpoint<ServerAppType, AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'replication';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<ServerAppType, AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string,\n ) {\n const adapter = this.server.adapter;\n\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousReplicationVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n\n const primaryPath = this.collection.schema.primaryPath;\n const replicationHandler: RxReplicationHandler<RxDocType, RxServerCheckpoint> = getReplicationHandlerByCollection<RxDocType>(this.server.database, collection.name);\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (change.assumedMasterState && docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n const mergeServerDocumentFields = mergeServerDocumentFieldsMonad<RxDocType>(this.serverOnlyFields);\n\n this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pull', async (req: any, res: any) => {\n const authData = await getAuthDataByRequest(this.server, req, res);\n if (!authData) { return; }\n\n const urlQuery = adapter.getRequestQuery(req);\n const id = urlQuery.id ? urlQuery.id as string : '';\n const lwt = urlQuery.lwt ? parseFloat(urlQuery.lwt as string) : 0;\n const limit = urlQuery.limit ? parseInt(urlQuery.limit as string, 10) : 1;\n const plainQuery = getChangedDocumentsSinceQuery<RxDocType, RxServerCheckpoint>(\n this.collection.storageInstance,\n limit,\n { id, lwt }\n );\n const useQueryChanges: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n plainQuery\n );\n const prepared = prepareQuery<RxDocType>(\n this.collection.schema.jsonSchema,\n useQueryChanges\n );\n const result = await this.collection.storageInstance.query(prepared);\n\n const newCheckpoint: RxServerCheckpoint = result.documents.length === 0 ? { id, lwt } : {\n id: ensureNotFalsy(lastOfArray(result.documents))[primaryPath] as string,\n lwt: ensureNotFalsy(lastOfArray(result.documents))._meta.lwt\n };\n const responseDocuments = result.documents.map(d => removeServerOnlyFields(d));\n adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, {\n documents: responseDocuments,\n checkpoint: newCheckpoint\n });\n });\n\n this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/push', async (req: any, res: any) => {\n const authData = await getAuthDataByRequest(this.server, req, res);\n if (!authData) { return; }\n\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData as any));\n const rows: RxReplicationWriteToMasterRow<RxDocType>[] = adapter.getRequestBody(req);\n const ids: string[] = [];\n rows.forEach(row => ids.push((row.newDocumentState as any)[primaryPath]));\n\n for (const row of rows) {\n // TODO remove this check\n if (row.assumedMasterState && (row.assumedMasterState as any)._meta) {\n throw new Error('body document contains meta!');\n }\n }\n\n // ensure all writes are allowed\n const nonAllowedRow = rows.find(row => {\n if (\n !docDataMatcherWrite(row.newDocumentState as any) ||\n (row.assumedMasterState && !docDataMatcherWrite(row.assumedMasterState as any))\n ) {\n return true;\n }\n });\n if (nonAllowedRow) {\n adapter.closeConnection(res, 403, 'Forbidden');\n return;\n }\n let hasInvalidChange = false;\n\n const currentStateDocsArray = await this.collection.storageInstance.findDocumentsById(ids, true);\n const currentStateDocs = new Map<string, RxDocumentData<RxDocType>>();\n currentStateDocsArray.forEach(d => currentStateDocs.set((d as any)[primaryPath], d));\n\n const useRows: typeof rows = rows.map((row) => {\n const id = (row.newDocumentState as any)[primaryPath];\n const isChangeValid = this.changeValidator(ensureNotFalsy(authData), {\n newDocumentState: removeServerOnlyFields(row.newDocumentState),\n assumedMasterState: removeServerOnlyFields(row.assumedMasterState)\n });\n if (!isChangeValid) {\n hasInvalidChange = true;\n }\n\n const serverDoc = currentStateDocs.get(id);\n return {\n newDocumentState: mergeServerDocumentFields(row.newDocumentState, serverDoc),\n assumedMasterState: mergeServerDocumentFields(row.assumedMasterState as any, serverDoc)\n } as typeof row;\n });\n if (hasInvalidChange) {\n adapter.closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const conflicts = await replicationHandler.masterWrite(useRows);\n\n adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, conflicts);\n });\n this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pullStream', async (req, res) => {\n\n const authData = await getAuthDataByRequest<AuthType, any, any>(this.server, req, res);\n if (!authData) { return; }\n\n adapter.setSSEHeaders(res);\n const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const subscription = replicationHandler.masterChangeStream$.pipe(\n mergeMap(async (changes) => {\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting an event.\n */\n let authData: RxServerAuthData<AuthType>;\n try {\n authData = await server.authHandler(adapter.getRequestHeaders(req));\n } catch (err) {\n adapter.closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n if (changes === 'RESYNC') {\n return changes;\n } else {\n const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));\n return {\n documents: useDocs,\n checkpoint: changes.checkpoint\n };\n }\n }),\n filter(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))\n ).subscribe(filteredAndModified => {\n if (filteredAndModified === 'RESYNC') {\n adapter.responseWrite(res, 'data: ' + JSON.stringify(filteredAndModified) + '\\n\\n');\n } else {\n const responseDocuments = ensureNotFalsy(filteredAndModified).documents.map(d => removeServerOnlyFields(d as any));\n adapter.responseWrite(\n res,\n 'data: ' + JSON.stringify({\n documents: responseDocuments,\n checkpoint: ensureNotFalsy(filteredAndModified).checkpoint\n }) + '\\n\\n'\n );\n }\n\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n adapter.onRequestClose(req, () => {\n subscription.unsubscribe();\n adapter.endResponse(res);\n });\n });\n }\n}\n\n\n/**\n * \"block\" the previous version urls and send a 426 on them so that\n * the clients know they must update.\n */\nexport function blockPreviousReplicationVersionPaths(\n server: RxServer<any, any>,\n path: string,\n currentVersion: number\n\n) {\n let v = 0;\n while (v < currentVersion) {\n const version = v;\n /**\n * Some adapters do not allow regex or handle them property (like Koa),\n * so to make it easier, use the hard-coded array of path parts.\n */\n [\n '',\n 'pull',\n 'push',\n 'pullStream'\n ].forEach(subPath => {\n server.adapter.all(server.serverApp, '/' + path + '/' + version + '/' + subPath, (req, res) => {\n server.adapter.closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');\n });\n });\n v++;\n }\n}\n"],"mappings":"AAAA,SAMIA,YAAY,EACZC,6BAA6B,QAE1B,mBAAmB;AAC1B,SAASC,iCAAiC,QAAQ,oCAAoC;AAQtF,SAASC,MAAM,EAAEC,QAAQ,QAAQ,MAAM;AACvC,SACIC,cAAc,EACdC,WAAW,QACR,oBAAoB;AAE3B,SACIC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,oBAAoB,EACpBC,oBAAoB,EACpBC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,OAAO,QACJ,aAAa;AASpB,WAAaC,2BAA2B,GAKpC,SAAAA,4BACoBC,MAAyC,EACzCC,IAAY,EACZC,UAAmC,EACnDC,aAAyD,EACzDC,eAA6D,EAC7CC,gBAA0B,EAC1BC,IAAa,EAC/B;EAAA,KAZOC,IAAI,GAAG,aAAa;EAAA,KAKTP,MAAyC,GAAzCA,MAAyC;EAAA,KACzCC,IAAY,GAAZA,IAAY;EAAA,KACZC,UAAmC,GAAnCA,UAAmC;EAAA,KAGnCG,gBAA0B,GAA1BA,gBAA0B;EAAA,KAC1BC,IAAa,GAAbA,IAAa;EAE7B,IAAME,OAAO,GAAG,IAAI,CAACR,MAAM,CAACQ,OAAO;EAE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,CAACC,SAAS,CAAC;UACtB9C,SAAS,EAAEG,iBAAiB;UAC5BK,UAAU,EAAE9D,cAAc,CAACiG,mBAAmB,CAAC,CAACnC;QACpD,CAAC,CAAC,GAAG,MACT,CAAC;MACL;IAEJ,CAAC,CAAC;;IAEF;AACZ;AACA;IACY5C,OAAO,CAACmF,cAAc,CAAC/D,GAAG,EAAE,MAAM;MAC9BiD,YAAY,CAACe,WAAW,CAAC,CAAC;MAC1BpF,OAAO,CAACqF,WAAW,CAAChE,GAAG,CAAC;IAC5B,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC;;AAIL;AACA;AACA;AACA;AACA,OAAO,SAASnB,oCAAoCA,CAChDV,MAA0B,EAC1B8F,IAAY,EACZC,cAAsB,EAExB;EACE,IAAIC,CAAC,GAAG,CAAC;EAAC,IAAAC,KAAA,YAAAA,CAAA,EACiB;IACvB,IAAMrF,OAAO,GAAGoF,CAAC;IACjB;AACR;AACA;AACA;IACQ,CACI,EAAE,EACF,MAAM,EACN,MAAM,EACN,YAAY,CACf,CAACtC,OAAO,CAACwC,OAAO,IAAI;MACjBlG,MAAM,CAACQ,OAAO,CAAC2F,GAAG,CAACnG,MAAM,CAAC2B,SAAS,EAAE,GAAG,GAAGmE,IAAI,GAAG,GAAG,GAAGlF,OAAO,GAAG,GAAG,GAAGsF,OAAO,EAAE,CAACtE,GAAG,EAAEC,GAAG,KAAK;QAC3F7B,MAAM,CAACQ,OAAO,CAACuD,eAAe,CAAClC,GAAG,EAAE,GAAG,EAAE,mBAAmB,GAAGjB,OAAO,GAAG,cAAc,GAAGmF,cAAc,GAAG,GAAG,CAAC;MACnH,CAAC,CAAC;IACN,CAAC,CAAC;IACFC,CAAC,EAAE;EACP,CAAC;EAjBD,OAAOA,CAAC,GAAGD,cAAc;IAAAE,KAAA;EAAA;AAkB7B","ignoreList":[]}
1
+ {"version":3,"file":"endpoint-replication.js","names":["prepareQuery","getChangedDocumentsSinceQuery","getReplicationHandlerByCollection","filter","mergeMap","ensureNotFalsy","lastOfArray","docContainsServerOnlyFields","doesContainRegexQuerySelector","getAuthDataByRequest","getDocAllowedMatcher","mergeServerDocumentFieldsMonad","removeServerOnlyFieldsMonad","setCors","stripServerOnlyFieldsMonad","RxServerReplicationEndpoint","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","type","adapter","join","blockPreviousReplicationVersionPaths","schema","version","urlPath","primaryPath","replicationHandler","database","authData","query","selector","Error","change","assumedMasterState","newDocumentState","removeServerOnlyFields","mergeServerDocumentFields","stripServerOnlyFields","get","serverApp","req","res","urlQuery","getRequestQuery","id","lwt","parseFloat","limit","parseInt","plainQuery","storageInstance","useQueryChanges","prepared","jsonSchema","result","newCheckpoint","documents","length","_meta","responseDocuments","map","d","setResponseHeader","endResponseJson","checkpoint","post","docDataMatcherWrite","rows","getRequestBody","ids","forEach","row","push","nonAllowedRow","find","closeConnection","hasInvalidChange","currentStateDocsArray","findDocumentsById","currentStateDocs","Map","set","useRows","isChangeValid","serverDoc","conflicts","masterWrite","c","setSSEHeaders","docDataMatcherStream","subscription","masterChangeStream$","pipe","changes","authHandler","getRequestHeaders","err","useDocs","f","subscribe","filteredAndModified","responseWrite","JSON","stringify","onRequestClose","unsubscribe","endResponse","path","currentVersion","v","_loop","subPath","all"],"sources":["../../../../src/plugins/server/endpoint-replication.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n StringKeys,\n prepareQuery,\n getChangedDocumentsSinceQuery,\n RxDocumentData\n} from 'rxdb/plugins/core';\nimport { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerAuthData,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n lastOfArray\n} from 'rxdb/plugins/utils';\n\nimport {\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getAuthDataByRequest,\n getDocAllowedMatcher,\n mergeServerDocumentFieldsMonad,\n removeServerOnlyFieldsMonad,\n setCors,\n stripServerOnlyFieldsMonad\n} from './helper.ts';\nimport type { RxServerCheckpoint } from '../replication-server/types.ts';\n\nexport type RxReplicationEndpointMessageType = {\n id: string;\n method: StringKeys<RxReplicationHandler<any, any>> | 'auth';\n params: any[];\n};\n\nexport class RxServerReplicationEndpoint<ServerAppType, AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'replication';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<ServerAppType, AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string,\n ) {\n const adapter = this.server.adapter;\n\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousReplicationVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n\n const primaryPath = this.collection.schema.primaryPath;\n const replicationHandler: RxReplicationHandler<RxDocType, RxServerCheckpoint> = getReplicationHandlerByCollection<RxDocType>(this.server.database, collection.name);\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (change.assumedMasterState && docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n const mergeServerDocumentFields = mergeServerDocumentFieldsMonad<RxDocType>(this.serverOnlyFields);\n const stripServerOnlyFields = stripServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n\n this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pull', async (req: any, res: any) => {\n const authData = await getAuthDataByRequest(this.server, req, res);\n if (!authData) { return; }\n\n const urlQuery = adapter.getRequestQuery(req);\n const id = urlQuery.id ? urlQuery.id as string : '';\n const lwt = urlQuery.lwt ? parseFloat(urlQuery.lwt as string) : 0;\n const limit = urlQuery.limit ? parseInt(urlQuery.limit as string, 10) : 1;\n const plainQuery = getChangedDocumentsSinceQuery<RxDocType, RxServerCheckpoint>(\n this.collection.storageInstance,\n limit,\n { id, lwt }\n );\n const useQueryChanges: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n plainQuery\n );\n const prepared = prepareQuery<RxDocType>(\n this.collection.schema.jsonSchema,\n useQueryChanges\n );\n const result = await this.collection.storageInstance.query(prepared);\n\n const newCheckpoint: RxServerCheckpoint = result.documents.length === 0 ? { id, lwt } : {\n id: ensureNotFalsy(lastOfArray(result.documents))[primaryPath] as string,\n lwt: ensureNotFalsy(lastOfArray(result.documents))._meta.lwt\n };\n const responseDocuments = result.documents.map(d => removeServerOnlyFields(d));\n adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, {\n documents: responseDocuments,\n checkpoint: newCheckpoint\n });\n });\n\n this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/push', async (req: any, res: any) => {\n const authData = await getAuthDataByRequest(this.server, req, res);\n if (!authData) { return; }\n\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData as any));\n const rows: RxReplicationWriteToMasterRow<RxDocType>[] = adapter.getRequestBody(req);\n const ids: string[] = [];\n rows.forEach(row => ids.push((row.newDocumentState as any)[primaryPath]));\n\n for (const row of rows) {\n // TODO remove this check\n if (row.assumedMasterState && (row.assumedMasterState as any)._meta) {\n throw new Error('body document contains meta!');\n }\n }\n\n // ensure all writes are allowed\n const nonAllowedRow = rows.find(row => {\n if (\n !docDataMatcherWrite(row.newDocumentState as any) ||\n (row.assumedMasterState && !docDataMatcherWrite(row.assumedMasterState as any))\n ) {\n return true;\n }\n });\n if (nonAllowedRow) {\n adapter.closeConnection(res, 403, 'Forbidden');\n return;\n }\n let hasInvalidChange = false;\n\n const currentStateDocsArray = await this.collection.storageInstance.findDocumentsById(ids, true);\n const currentStateDocs = new Map<string, RxDocumentData<RxDocType>>();\n currentStateDocsArray.forEach(d => currentStateDocs.set((d as any)[primaryPath], d));\n\n const useRows: typeof rows = rows.map((row) => {\n const id = (row.newDocumentState as any)[primaryPath];\n const isChangeValid = this.changeValidator(ensureNotFalsy(authData), {\n newDocumentState: removeServerOnlyFields(row.newDocumentState),\n assumedMasterState: removeServerOnlyFields(row.assumedMasterState)\n });\n if (!isChangeValid) {\n hasInvalidChange = true;\n }\n\n const serverDoc = currentStateDocs.get(id);\n // When the document does not yet exist on the server, strip\n // server-only fields from the new document state so a client\n // cannot populate them on insert. Updates of existing docs\n // are already protected because mergeServerDocumentFields\n // overwrites those fields with the stored server value.\n const newDocumentState = serverDoc\n ? mergeServerDocumentFields(row.newDocumentState, serverDoc)\n : stripServerOnlyFields(row.newDocumentState);\n return {\n newDocumentState,\n assumedMasterState: mergeServerDocumentFields(row.assumedMasterState as any, serverDoc)\n } as typeof row;\n });\n if (hasInvalidChange) {\n adapter.closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const conflicts = await replicationHandler.masterWrite(useRows);\n\n adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, conflicts.map(c => removeServerOnlyFields(c)));\n });\n this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pullStream', async (req, res) => {\n\n const authData = await getAuthDataByRequest<AuthType, any, any>(this.server, req, res);\n if (!authData) { return; }\n\n adapter.setSSEHeaders(res);\n const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const subscription = replicationHandler.masterChangeStream$.pipe(\n mergeMap(async (changes) => {\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting an event.\n */\n let authData: RxServerAuthData<AuthType>;\n try {\n authData = await server.authHandler(adapter.getRequestHeaders(req));\n } catch (err) {\n adapter.closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n if (changes === 'RESYNC') {\n return changes;\n } else {\n const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));\n return {\n documents: useDocs,\n checkpoint: changes.checkpoint\n };\n }\n }),\n filter(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))\n ).subscribe(filteredAndModified => {\n if (filteredAndModified === 'RESYNC') {\n adapter.responseWrite(res, 'data: ' + JSON.stringify(filteredAndModified) + '\\n\\n');\n } else {\n const responseDocuments = ensureNotFalsy(filteredAndModified).documents.map(d => removeServerOnlyFields(d as any));\n adapter.responseWrite(\n res,\n 'data: ' + JSON.stringify({\n documents: responseDocuments,\n checkpoint: ensureNotFalsy(filteredAndModified).checkpoint\n }) + '\\n\\n'\n );\n }\n\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n adapter.onRequestClose(req, () => {\n subscription.unsubscribe();\n adapter.endResponse(res);\n });\n });\n }\n}\n\n\n/**\n * \"block\" the previous version urls and send a 426 on them so that\n * the clients know they must update.\n */\nexport function blockPreviousReplicationVersionPaths(\n server: RxServer<any, any>,\n path: string,\n currentVersion: number\n\n) {\n let v = 0;\n while (v < currentVersion) {\n const version = v;\n /**\n * Some adapters do not allow regex or handle them property (like Koa),\n * so to make it easier, use the hard-coded array of path parts.\n */\n [\n '',\n 'pull',\n 'push',\n 'pullStream'\n ].forEach(subPath => {\n server.adapter.all(server.serverApp, '/' + path + '/' + version + '/' + subPath, (req, res) => {\n server.adapter.closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');\n });\n });\n v++;\n }\n}\n"],"mappings":"AAAA,SAMI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AAY,CAACe,WAAW,CAAC,CAAC;MAC1BtF,OAAO,CAACuF,WAAW,CAACjE,GAAG,CAAC;IAC5B,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC;;AAIL;AACA;AACA;AACA;AACA,OAAO,SAASpB,oCAAoCA,CAChDV,MAA0B,EAC1BgG,IAAY,EACZC,cAAsB,EAExB;EACE,IAAIC,CAAC,GAAG,CAAC;EAAC,IAAAC,KAAA,YAAAA,CAAA,EACiB;IACvB,IAAMvF,OAAO,GAAGsF,CAAC;IACjB;AACR;AACA;AACA;IACQ,CACI,EAAE,EACF,MAAM,EACN,MAAM,EACN,YAAY,CACf,CAACvC,OAAO,CAACyC,OAAO,IAAI;MACjBpG,MAAM,CAACQ,OAAO,CAAC6F,GAAG,CAACrG,MAAM,CAAC4B,SAAS,EAAE,GAAG,GAAGoE,IAAI,GAAG,GAAG,GAAGpF,OAAO,GAAG,GAAG,GAAGwF,OAAO,EAAE,CAACvE,GAAG,EAAEC,GAAG,KAAK;QAC3F9B,MAAM,CAACQ,OAAO,CAACwD,eAAe,CAAClC,GAAG,EAAE,GAAG,EAAE,mBAAmB,GAAGlB,OAAO,GAAG,cAAc,GAAGqF,cAAc,GAAG,GAAG,CAAC;MACnH,CAAC,CAAC;IACN,CAAC,CAAC;IACFC,CAAC,EAAE;EACP,CAAC;EAjBD,OAAOA,CAAC,GAAGD,cAAc;IAAAE,KAAA;EAAA;AAkB7B","ignoreList":[]}
@@ -1,7 +1,7 @@
1
1
  import { normalizeMangoQuery } from 'rxdb/plugins/core';
2
2
  import { filter, mergeMap } from 'rxjs';
3
3
  import { ensureNotFalsy } from 'rxdb/plugins/utils';
4
- import { docContainsServerOnlyFields, doesContainRegexQuerySelector, getAuthDataByRequest, getDocAllowedMatcher, removeServerOnlyFieldsMonad, setCors } from "./helper.js";
4
+ import { docContainsServerOnlyFields, doesContainRegexQuerySelector, getAuthDataByRequest, getDocAllowedMatcher, mergeServerDocumentFieldsMonad, removeServerOnlyFieldsMonad, setCors, stripServerOnlyFieldsMonad } from "./helper.js";
5
5
  export var REST_PATHS = ['query', 'query/observe', 'get', 'set', 'delete'
6
6
 
7
7
  // TODO
@@ -36,6 +36,8 @@ export var RxServerRestEndpoint = function RxServerRestEndpoint(server, name, co
36
36
  return changeValidator(authData, change);
37
37
  };
38
38
  var removeServerOnlyFields = removeServerOnlyFieldsMonad(this.serverOnlyFields);
39
+ var mergeServerDocumentFields = mergeServerDocumentFieldsMonad(this.serverOnlyFields);
40
+ var stripServerOnlyFields = stripServerOnlyFieldsMonad(this.serverOnlyFields);
39
41
  this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/query', async (req, res) => {
40
42
  ensureNotFalsy(adapter.getRequestBody(req), 'req body is empty');
41
43
  var authData = await getAuthDataByRequest(this.server, req, res);
@@ -67,8 +69,19 @@ export var RxServerRestEndpoint = function RxServerRestEndpoint(server, name, co
67
69
  if (!authData) {
68
70
  return;
69
71
  }
72
+
73
+ // Run the queryModifier BEFORE setSSEHeaders so that a bad
74
+ // request (e.g. a $regex query that the modifier wrapper
75
+ // rejects to prevent DOS attacks) can still be answered
76
+ // with a proper 400 response, mirroring the /query endpoint.
77
+ var useQuery;
78
+ try {
79
+ useQuery = this.queryModifier(ensureNotFalsy(authData), normalizeMangoQuery(this.collection.schema.jsonSchema, JSON.parse(atob(adapter.getRequestQuery(req).query))));
80
+ } catch (err) {
81
+ adapter.closeConnection(res, 400, 'Bad Request');
82
+ return;
83
+ }
70
84
  adapter.setSSEHeaders(res);
71
- var useQuery = this.queryModifier(ensureNotFalsy(authData), normalizeMangoQuery(this.collection.schema.jsonSchema, JSON.parse(atob(adapter.getRequestQuery(req).query))));
72
85
  var rxQuery = this.collection.find(useQuery);
73
86
  var subscription = rxQuery.$.pipe(mergeMap(async result => {
74
87
  var resultData = result.map(doc => removeServerOnlyFields(doc.toJSON()));
@@ -143,15 +156,20 @@ export var RxServerRestEndpoint = function RxServerRestEndpoint(server, name, co
143
156
  var docs = await collection.findByIds(docsData.map(d => d[primaryPath])).exec();
144
157
  var useDocsData = docsData.slice();
145
158
  docsData = [];
146
- var _loop = async function (_docData) {
159
+ var _loop = async function () {
147
160
  var id = _docData[primaryPath];
148
161
  var doc = docs.get(id);
149
162
  if (!doc) {
150
- promises.push(_this.collection.insert(_docData).catch(err => onWriteError(err, _docData)));
151
- } else {
163
+ // Run the changeValidator for new document inserts as
164
+ // well. Previously the validator was only invoked for
165
+ // updates, so a changeValidator that rejected writes
166
+ // had no effect on inserts via /set, which is
167
+ // inconsistent with the replication endpoint and the
168
+ // documented contract that the validator gates all
169
+ // changes.
152
170
  var isAllowed = _this.changeValidator(authData, {
153
171
  newDocumentState: removeServerOnlyFields(_docData),
154
- assumedMasterState: removeServerOnlyFields(doc.toJSON(true))
172
+ assumedMasterState: undefined
155
173
  });
156
174
  if (!isAllowed) {
157
175
  adapter.closeConnection(res, 403, 'Forbidden');
@@ -159,12 +177,43 @@ export var RxServerRestEndpoint = function RxServerRestEndpoint(server, name, co
159
177
  v: void 0
160
178
  };
161
179
  }
162
- promises.push(doc.patch(_docData).catch(err => onWriteError(err, _docData)));
180
+ // Strip server-only fields from the client doc before
181
+ // inserting. Without this, a client could populate
182
+ // server-only ("readonly") fields when creating a new
183
+ // document via /set, which contradicts the documented
184
+ // behavior that clients cannot do writes where one of
185
+ // the serverOnlyFields is set.
186
+ var mergedDocData = stripServerOnlyFields(mergeServerDocumentFields(_docData, undefined));
187
+ promises.push(_this.collection.insert(mergedDocData).catch(err => onWriteError(err, mergedDocData)));
188
+ } else {
189
+ // The user must also be allowed to access the existing document.
190
+ // Without this check, a client could overwrite arbitrary
191
+ // documents by sending a write whose new state matches the
192
+ // queryModifier while targeting a foreign document's primary.
193
+ var isExistingDocAllowed = docDataMatcherWrite(doc.toJSON(true));
194
+ if (!isExistingDocAllowed) {
195
+ adapter.closeConnection(res, 403, 'Forbidden');
196
+ return {
197
+ v: void 0
198
+ };
199
+ }
200
+ var _isAllowed = _this.changeValidator(authData, {
201
+ newDocumentState: removeServerOnlyFields(_docData),
202
+ assumedMasterState: removeServerOnlyFields(doc.toJSON(true))
203
+ });
204
+ if (!_isAllowed) {
205
+ adapter.closeConnection(res, 403, 'Forbidden');
206
+ return {
207
+ v: void 0
208
+ };
209
+ }
210
+ var _mergedDocData = mergeServerDocumentFields(_docData, doc.toJSON(true));
211
+ promises.push(doc.patch(_mergedDocData).catch(err => onWriteError(err, _mergedDocData)));
163
212
  }
164
213
  },
165
214
  _ret;
166
215
  for (var _docData of useDocsData) {
167
- _ret = await _loop(_docData);
216
+ _ret = await _loop();
168
217
  if (_ret) return _ret.v;
169
218
  }
170
219
  await Promise.all(promises);
@@ -195,8 +244,8 @@ export var RxServerRestEndpoint = function RxServerRestEndpoint(server, name, co
195
244
  };
196
245
  }
197
246
  var isAllowedChange = _this.changeValidator(authData, {
198
- newDocumentState: doc.toJSON(true),
199
- assumedMasterState: doc.toJSON(true)
247
+ newDocumentState: removeServerOnlyFields(doc.toJSON(true)),
248
+ assumedMasterState: removeServerOnlyFields(doc.toJSON(true))
200
249
  });
201
250
  if (!isAllowedChange) {
202
251
  adapter.closeConnection(res, 403, 'Forbidden');