@statewalker/webrun-rpc-http 0.2.0 → 0.3.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.
package/README.md CHANGED
@@ -95,7 +95,8 @@ call, and cached for the client's lifetime; create a new client to refresh it.
95
95
  Every method call is one `POST` with no connection held open.
96
96
  `loadService` rejects with `Service <name> not found` for a name the descriptor
97
97
  does not list, and with `Failed to load services descriptor: <status> <statusText>`
98
- when the descriptor request fails.
98
+ when the descriptor request fails. A failed descriptor load is not cached: the
99
+ next `loadService` call fetches it again.
99
100
 
100
101
  ### Wire client to server in process
101
102
 
@@ -163,7 +164,7 @@ Call encoding:
163
164
  | --- | --- |
164
165
  | `POST /svc/method`, `multipart/form-data` | `params` field (JSON) and optional `body` field (`Blob`). |
165
166
  | `POST /svc/method`, any other content type | `params` is `{}`; the raw body becomes the `body` Blob. |
166
- | `GET /svc/method?k=v` | Query string as `params`. Dot-separated keys nest: `?a.b=c&a.d=e` gives `{ a: { b: "c", d: "e" } }`. Values stay strings; repeated keys overwrite. |
167
+ | `GET /svc/method?k=v` | Query string as `params`. Dot-separated keys nest: `?a.b=c&a.d=e` gives `{ a: { b: "c", d: "e" } }`. Values stay strings; repeated keys overwrite. A key with a `__proto__`, `constructor` or `prototype` segment is ignored, so a query string cannot reach `Object.prototype`; the objects are ordinary ones, as with `POST`. |
167
168
 
168
169
  The URL tail after `/svc/method/` is set as `params.$path` (an empty string when
169
170
  there is none), so a method can serve REST-style paths such as
@@ -180,7 +181,7 @@ Every error is a JSON object `{ "type": "error", "message", "stack", ...custom f
180
181
  | Cause | HTTP status |
181
182
  | --- | --- |
182
183
  | The method throws | `200`; the call reached the method |
183
- | Unknown method: `Method <m> not found in service <s>` | `500` |
184
+ | Unknown service or method: `Method <m> not found in service <s>` | `404` |
184
185
  | Path outside the prefix, or a method other than `GET`/`POST`: `Not found` | `404` |
185
186
  | Non-JSON error response | client throws `RPC call failed: <status> <statusText>` |
186
187
 
@@ -196,8 +197,9 @@ it.
196
197
  streaming. For streaming responses use `fetchOverDuplex` /
197
198
  `serveFetchOverDuplex` from `@statewalker/webrun-http-streams` directly.
198
199
  - **Only the prototype chain below `Object.prototype` is exposed.**
199
- `toString`, `hasOwnProperty` and the like are never endpoints. Methods of
200
- every ancestor class are.
200
+ `toString`, `hasOwnProperty`, `constructor`, `__proto__` and the like are
201
+ never endpoints, and never service names either: they answer `404`. Methods
202
+ of every ancestor class are.
201
203
  - **`baseUrl` takes no trailing slash.** The client builds
202
204
  `${baseUrl}/${service}/${method}`; a trailing slash doubles it and the call
203
205
  fails with `Not found`.
@@ -223,6 +225,7 @@ One runtime dependency, `@statewalker/webrun-streams`, for `serializeError` /
223
225
 
224
226
  ```sh
225
227
  pnpm test # vitest run
228
+ pnpm run typecheck # tsc --noEmit
226
229
  pnpm run build # rolldown + tsc --emitDeclarationOnly
227
230
  pnpm run lint # biome check src tests
228
231
  ```
package/dist/index.js CHANGED
@@ -24,7 +24,8 @@ function getInstanceMethods(instance) {
24
24
  * Build an RPC client that calls services exposed by {@link newRpcServer}.
25
25
  *
26
26
  * The descriptor at `GET {baseUrl}/` is fetched lazily on the first
27
- * `loadService` call and cached for subsequent calls.
27
+ * `loadService` call and cached for subsequent calls. A failed load is not
28
+ * cached; the next `loadService` call tries again.
28
29
  */
29
30
  function newRpcClient({ baseUrl, fetch = globalThis.fetch.bind(globalThis) }) {
30
31
  let apiPromise = null;
@@ -41,7 +42,10 @@ function newRpcClient({ baseUrl, fetch = globalThis.fetch.bind(globalThis) }) {
41
42
  return services;
42
43
  };
43
44
  return { async loadService(serviceName) {
44
- if (!apiPromise) apiPromise = loadApi();
45
+ if (!apiPromise) apiPromise = loadApi().catch((error) => {
46
+ apiPromise = null;
47
+ throw error;
48
+ });
45
49
  const service = (await apiPromise)[serviceName];
46
50
  if (!service) throw new Error(`Service ${serviceName} not found`);
47
51
  return service;
@@ -96,6 +100,7 @@ function newRpcServer(services, { path = "" } = {}) {
96
100
  if (request.method === "GET" && !serviceName) return jsonResponse(describeServices(index));
97
101
  if (request.method === "GET" && serviceName && !methodName) return jsonResponse(listMethods(index, serviceName));
98
102
  if ((request.method === "GET" || request.method === "POST") && serviceName && methodName) {
103
+ if (!lookupMethod(index, serviceName, methodName)) return errorResponse(/* @__PURE__ */ new Error(`Method ${methodName} not found in service ${serviceName}`), 404);
99
104
  const { params, body } = await parseCallArgs(request);
100
105
  const result = await invoke(index, serviceName, methodName, subPath, params, body);
101
106
  return result instanceof Blob ? blobResponse(result) : jsonResponse(result);
@@ -107,15 +112,19 @@ function newRpcServer(services, { path = "" } = {}) {
107
112
  };
108
113
  }
109
114
  function buildServiceIndex(services) {
110
- const index = {};
115
+ const index = Object.create(null);
111
116
  for (const [serviceName, service] of Object.entries(services)) {
112
117
  const methods = getInstanceMethods(service);
113
- const methodsIndex = {};
118
+ const methodsIndex = Object.create(null);
114
119
  for (const [methodName, method] of Object.entries(methods)) methodsIndex[methodName] = async (params, body) => await method.call(service, params, body);
115
120
  index[serviceName] = methodsIndex;
116
121
  }
117
122
  return index;
118
123
  }
124
+ function lookupMethod(index, serviceName, methodName) {
125
+ const service = Object.hasOwn(index, serviceName) ? index[serviceName] : void 0;
126
+ return service && Object.hasOwn(service, methodName) ? service[methodName] : void 0;
127
+ }
119
128
  function splitRequestPath(request, prefix) {
120
129
  const pathname = new URL(request.url).pathname;
121
130
  if (prefix && pathname !== prefix && !pathname.startsWith(`${prefix}/`)) return null;
@@ -143,18 +152,28 @@ async function parseCallArgs(request) {
143
152
  body: request.body ? await request.blob() : void 0
144
153
  };
145
154
  }
155
+ const FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set([
156
+ "__proto__",
157
+ "constructor",
158
+ "prototype"
159
+ ]);
146
160
  /**
147
161
  * Expand dot-separated query keys (`a.b=c`) into nested JSON objects.
148
162
  * Repeated keys overwrite rather than merging — same as the original.
163
+ * Keys with a `__proto__`, `constructor` or `prototype` segment are ignored and
164
+ * existing levels are found with `Object.hasOwn`, so a query string cannot
165
+ * write to `Object.prototype`. The objects themselves are ordinary ones, as a
166
+ * POST's `JSON.parse` gives, so a method may call `params.hasOwnProperty`.
149
167
  */
150
168
  function parseQueryParams(search) {
151
169
  const root = {};
152
170
  for (const [key, value] of search.entries()) {
153
171
  const segments = key.split(".");
172
+ if (segments.some((seg) => FORBIDDEN_SEGMENTS.has(seg))) continue;
154
173
  let cursor = root;
155
174
  for (let i = 0; i < segments.length - 1; i++) {
156
175
  const seg = segments[i];
157
- const existing = cursor[seg];
176
+ const existing = Object.hasOwn(cursor, seg) ? cursor[seg] : void 0;
158
177
  if (typeof existing !== "object" || existing === null || Array.isArray(existing)) cursor[seg] = {};
159
178
  cursor = cursor[seg];
160
179
  }
@@ -164,7 +183,7 @@ function parseQueryParams(search) {
164
183
  }
165
184
  async function invoke(index, serviceName, methodName, subPath, params, body) {
166
185
  if (params && typeof params === "object" && !Array.isArray(params)) params.$path = subPath;
167
- const method = index[serviceName]?.[methodName];
186
+ const method = lookupMethod(index, serviceName, methodName);
168
187
  if (!method) throw new Error(`Method ${methodName} not found in service ${serviceName}`);
169
188
  try {
170
189
  const result = await method(params, body);
@@ -185,7 +204,7 @@ function describeServices(index) {
185
204
  return out;
186
205
  }
187
206
  function listMethods(index, serviceName) {
188
- const svc = index[serviceName];
207
+ const svc = Object.hasOwn(index, serviceName) ? index[serviceName] : void 0;
189
208
  return svc ? Object.keys(svc) : [];
190
209
  }
191
210
  function jsonResponse(body, status = 200) {
@@ -19,7 +19,8 @@ export interface RpcClient {
19
19
  * Build an RPC client that calls services exposed by {@link newRpcServer}.
20
20
  *
21
21
  * The descriptor at `GET {baseUrl}/` is fetched lazily on the first
22
- * `loadService` call and cached for subsequent calls.
22
+ * `loadService` call and cached for subsequent calls. A failed load is not
23
+ * cached; the next `loadService` call tries again.
23
24
  */
24
25
  export declare function newRpcClient({ baseUrl, fetch, }: NewRpcClientOptions): RpcClient;
25
26
  //# sourceMappingURL=new-rpc-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"new-rpc-client.d.ts","sourceRoot":"","sources":["../src/new-rpc-client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAoB,SAAS,EAAE,MAAM,YAAY,CAAC;AAE9D,MAAM,WAAW,mBAAmB;IAClC,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;CACjD;AAED,MAAM,WAAW,SAAS;IACxB;;;OAGG;IACH,WAAW,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC7E;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,EAC3B,OAAO,EACP,KAAyC,GAC1C,EAAE,mBAAmB,GAAG,SAAS,CA+BjC"}
1
+ {"version":3,"file":"new-rpc-client.d.ts","sourceRoot":"","sources":["../src/new-rpc-client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAoB,SAAS,EAAE,MAAM,YAAY,CAAC;AAE9D,MAAM,WAAW,mBAAmB;IAClC,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;CACjD;AAED,MAAM,WAAW,SAAS;IACxB;;;OAGG;IACH,WAAW,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC7E;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,EAC3B,OAAO,EACP,KAAyC,GAC1C,EAAE,mBAAmB,GAAG,SAAS,CAqCjC"}
@@ -1 +1 @@
1
- {"version":3,"file":"new-rpc-server.d.ts","sourceRoot":"","sources":["../src/new-rpc-server.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAID;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAChC,EAAE,IAAS,EAAE,GAAE,mBAAwB,GACtC,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAyBzC"}
1
+ {"version":3,"file":"new-rpc-server.d.ts","sourceRoot":"","sources":["../src/new-rpc-server.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAID;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAChC,EAAE,IAAS,EAAE,GAAE,mBAAwB,GACtC,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CA+BzC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-rpc-http",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "HTTP-based service RPC: expose object methods as a (Request) => Response handler and call them with fetch",
@@ -33,7 +33,7 @@
33
33
  "src"
34
34
  ],
35
35
  "dependencies": {
36
- "@statewalker/webrun-streams": "^0.3.0"
36
+ "@statewalker/webrun-streams": "^0.4.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@biomejs/biome": "^2.5.15",
@@ -50,6 +50,8 @@
50
50
  "scripts": {
51
51
  "build": "rimraf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
52
52
  "test": "vitest run",
53
+ "typecheck": "tsc -p tsconfig.json --noEmit",
54
+ "typecheck:tests": "tsc -p tsconfig.tests.json",
53
55
  "lint": "biome check src tests"
54
56
  }
55
57
  }
@@ -23,7 +23,8 @@ export interface RpcClient {
23
23
  * Build an RPC client that calls services exposed by {@link newRpcServer}.
24
24
  *
25
25
  * The descriptor at `GET {baseUrl}/` is fetched lazily on the first
26
- * `loadService` call and cached for subsequent calls.
26
+ * `loadService` call and cached for subsequent calls. A failed load is not
27
+ * cached; the next `loadService` call tries again.
27
28
  */
28
29
  export function newRpcClient({
29
30
  baseUrl,
@@ -52,7 +53,13 @@ export function newRpcClient({
52
53
 
53
54
  return {
54
55
  async loadService<T = Record<string, RpcMethod>>(serviceName: string): Promise<T> {
55
- if (!apiPromise) apiPromise = loadApi();
56
+ // A failed load is not cached: the next call fetches the descriptor again.
57
+ if (!apiPromise) {
58
+ apiPromise = loadApi().catch((error) => {
59
+ apiPromise = null;
60
+ throw error;
61
+ });
62
+ }
56
63
  const apis = await apiPromise;
57
64
  const service = apis[serviceName];
58
65
  if (!service) throw new Error(`Service ${serviceName} not found`);
@@ -46,6 +46,12 @@ export function newRpcServer(
46
46
  return jsonResponse(listMethods(index, serviceName));
47
47
  }
48
48
  if ((request.method === "GET" || request.method === "POST") && serviceName && methodName) {
49
+ if (!lookupMethod(index, serviceName, methodName)) {
50
+ return errorResponse(
51
+ new Error(`Method ${methodName} not found in service ${serviceName}`),
52
+ 404,
53
+ );
54
+ }
49
55
  const { params, body } = await parseCallArgs(request);
50
56
  const result = await invoke(index, serviceName, methodName, subPath, params, body);
51
57
  return result instanceof Blob ? blobResponse(result) : jsonResponse(result);
@@ -57,11 +63,13 @@ export function newRpcServer(
57
63
  };
58
64
  }
59
65
 
66
+ // Both levels are prototype-less, so a request for `constructor`, `toString`,
67
+ // `__proto__` and the like finds nothing instead of an `Object.prototype` member.
60
68
  function buildServiceIndex(services: Record<string, object>): ServiceIndex {
61
- const index: ServiceIndex = {};
69
+ const index: ServiceIndex = Object.create(null);
62
70
  for (const [serviceName, service] of Object.entries(services)) {
63
71
  const methods = getInstanceMethods(service);
64
- const methodsIndex: Record<string, RpcMethod> = {};
72
+ const methodsIndex: Record<string, RpcMethod> = Object.create(null);
65
73
  for (const [methodName, method] of Object.entries(methods)) {
66
74
  methodsIndex[methodName] = async (params, body) =>
67
75
  (await method.call(service, params, body)) as Blob | Json;
@@ -71,6 +79,15 @@ function buildServiceIndex(services: Record<string, object>): ServiceIndex {
71
79
  return index;
72
80
  }
73
81
 
82
+ function lookupMethod(
83
+ index: ServiceIndex,
84
+ serviceName: string,
85
+ methodName: string,
86
+ ): RpcMethod | undefined {
87
+ const service = Object.hasOwn(index, serviceName) ? index[serviceName] : undefined;
88
+ return service && Object.hasOwn(service, methodName) ? service[methodName] : undefined;
89
+ }
90
+
74
91
  interface ParsedPath {
75
92
  serviceName?: string;
76
93
  methodName?: string;
@@ -107,18 +124,26 @@ async function parseCallArgs(request: Request): Promise<{ params: Json; body?: B
107
124
  return { params: {}, body };
108
125
  }
109
126
 
127
+ // Query segments that could reach a prototype; a key containing one is dropped.
128
+ const FORBIDDEN_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
129
+
110
130
  /**
111
131
  * Expand dot-separated query keys (`a.b=c`) into nested JSON objects.
112
132
  * Repeated keys overwrite rather than merging — same as the original.
133
+ * Keys with a `__proto__`, `constructor` or `prototype` segment are ignored and
134
+ * existing levels are found with `Object.hasOwn`, so a query string cannot
135
+ * write to `Object.prototype`. The objects themselves are ordinary ones, as a
136
+ * POST's `JSON.parse` gives, so a method may call `params.hasOwnProperty`.
113
137
  */
114
138
  function parseQueryParams(search: URLSearchParams): JsonObject {
115
139
  const root: JsonObject = {};
116
140
  for (const [key, value] of search.entries()) {
117
141
  const segments = key.split(".");
142
+ if (segments.some((seg) => FORBIDDEN_SEGMENTS.has(seg))) continue;
118
143
  let cursor: JsonObject = root;
119
144
  for (let i = 0; i < segments.length - 1; i++) {
120
145
  const seg = segments[i];
121
- const existing = cursor[seg];
146
+ const existing = Object.hasOwn(cursor, seg) ? cursor[seg] : undefined;
122
147
  if (typeof existing !== "object" || existing === null || Array.isArray(existing)) {
123
148
  cursor[seg] = {};
124
149
  }
@@ -140,7 +165,7 @@ async function invoke(
140
165
  if (params && typeof params === "object" && !Array.isArray(params)) {
141
166
  (params as JsonObject).$path = subPath;
142
167
  }
143
- const method = index[serviceName]?.[methodName];
168
+ const method = lookupMethod(index, serviceName, methodName);
144
169
  if (!method) {
145
170
  throw new Error(`Method ${methodName} not found in service ${serviceName}`);
146
171
  }
@@ -161,7 +186,7 @@ function describeServices(index: ServiceIndex): JsonObject {
161
186
  }
162
187
 
163
188
  function listMethods(index: ServiceIndex, serviceName: string): Json[] {
164
- const svc = index[serviceName];
189
+ const svc = Object.hasOwn(index, serviceName) ? index[serviceName] : undefined;
165
190
  return svc ? Object.keys(svc) : [];
166
191
  }
167
192