@encore.dev/sdk 2.0.0-beta.14 → 2.0.0-beta.16

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 (269) hide show
  1. package/README.md +144 -90
  2. package/app_meta.ts +56 -54
  3. package/config/config.test.ts +47 -13
  4. package/config/config.ts +60 -57
  5. package/config/secrets.ts +47 -50
  6. package/config/value.ts +23 -26
  7. package/cron/mod.test.ts +12 -0
  8. package/cron/mod.ts +37 -22
  9. package/dist/app_meta.d.ts +52 -50
  10. package/dist/app_meta.d.ts.map +1 -1
  11. package/dist/app_meta.js +2 -2
  12. package/dist/app_meta.js.map +1 -1
  13. package/dist/config/config.d.ts +58 -55
  14. package/dist/config/config.d.ts.map +1 -1
  15. package/dist/config/config.js +8 -9
  16. package/dist/config/config.js.map +1 -1
  17. package/dist/config/secrets.d.ts +45 -50
  18. package/dist/config/secrets.d.ts.map +1 -1
  19. package/dist/config/secrets.js +11 -9
  20. package/dist/config/secrets.js.map +1 -1
  21. package/dist/config/value.d.ts +20 -23
  22. package/dist/config/value.d.ts.map +1 -1
  23. package/dist/config/value.js +20 -23
  24. package/dist/config/value.js.map +1 -1
  25. package/dist/cron/mod.d.ts +34 -20
  26. package/dist/cron/mod.d.ts.map +1 -1
  27. package/dist/cron/mod.js +13 -13
  28. package/dist/cron/mod.js.map +1 -1
  29. package/dist/frontends/mod.d.ts +20 -19
  30. package/dist/frontends/mod.d.ts.map +1 -1
  31. package/dist/frontends/mod.js +20 -19
  32. package/dist/frontends/mod.js.map +1 -1
  33. package/dist/gateway/errors.d.ts +28 -30
  34. package/dist/gateway/errors.d.ts.map +1 -1
  35. package/dist/gateway/errors.js +29 -31
  36. package/dist/gateway/errors.js.map +1 -1
  37. package/dist/gateway/match.d.ts +54 -54
  38. package/dist/gateway/match.d.ts.map +1 -1
  39. package/dist/gateway/match.js +56 -56
  40. package/dist/gateway/match.js.map +1 -1
  41. package/dist/gateway/middleware.d.ts +62 -64
  42. package/dist/gateway/middleware.d.ts.map +1 -1
  43. package/dist/gateway/middleware.js +1 -1
  44. package/dist/gateway/middleware.js.map +1 -1
  45. package/dist/gateway/mod.d.ts +64 -67
  46. package/dist/gateway/mod.d.ts.map +1 -1
  47. package/dist/gateway/mod.js +72 -76
  48. package/dist/gateway/mod.js.map +1 -1
  49. package/dist/gateway/request.d.ts +138 -134
  50. package/dist/gateway/request.d.ts.map +1 -1
  51. package/dist/gateway/request.js +117 -108
  52. package/dist/gateway/request.js.map +1 -1
  53. package/dist/gateway/serve.d.ts +29 -34
  54. package/dist/gateway/serve.d.ts.map +1 -1
  55. package/dist/gateway/serve.js +51 -56
  56. package/dist/gateway/serve.js.map +1 -1
  57. package/dist/gateways/mod.d.ts +23 -21
  58. package/dist/gateways/mod.d.ts.map +1 -1
  59. package/dist/gateways/mod.js +25 -23
  60. package/dist/gateways/mod.js.map +1 -1
  61. package/dist/internal/otel/http.d.ts +4 -2
  62. package/dist/internal/otel/http.d.ts.map +1 -1
  63. package/dist/internal/otel/http.js +32 -5
  64. package/dist/internal/otel/http.js.map +1 -1
  65. package/dist/internal/runtime/napi/napi.cjs +6 -5
  66. package/dist/internal/runtime/napi/napi.d.cts +58 -16
  67. package/dist/internal/runtime/shutdown.d.ts +75 -57
  68. package/dist/internal/runtime/shutdown.d.ts.map +1 -1
  69. package/dist/internal/runtime/shutdown.js +88 -84
  70. package/dist/internal/runtime/shutdown.js.map +1 -1
  71. package/dist/log/logger.d.ts +43 -37
  72. package/dist/log/logger.d.ts.map +1 -1
  73. package/dist/log/logger.js +26 -25
  74. package/dist/log/logger.js.map +1 -1
  75. package/dist/metrics/mod.d.ts +133 -114
  76. package/dist/metrics/mod.d.ts.map +1 -1
  77. package/dist/metrics/mod.js +109 -101
  78. package/dist/metrics/mod.js.map +1 -1
  79. package/dist/otel.d.ts +6 -3
  80. package/dist/otel.d.ts.map +1 -1
  81. package/dist/otel.js +6 -3
  82. package/dist/otel.js.map +1 -1
  83. package/dist/pubsub/subscription.d.ts +88 -116
  84. package/dist/pubsub/subscription.d.ts.map +1 -1
  85. package/dist/pubsub/subscription.js +14 -17
  86. package/dist/pubsub/subscription.js.map +1 -1
  87. package/dist/pubsub/topic.d.ts +86 -113
  88. package/dist/pubsub/topic.d.ts.map +1 -1
  89. package/dist/pubsub/topic.js +68 -82
  90. package/dist/pubsub/topic.js.map +1 -1
  91. package/dist/redaction/mod.d.ts +62 -0
  92. package/dist/redaction/mod.d.ts.map +1 -0
  93. package/dist/redaction/mod.js +102 -0
  94. package/dist/redaction/mod.js.map +1 -0
  95. package/dist/reqctx/mod.d.ts +83 -86
  96. package/dist/reqctx/mod.d.ts.map +1 -1
  97. package/dist/reqctx/mod.js +39 -41
  98. package/dist/reqctx/mod.js.map +1 -1
  99. package/dist/services/index.d.ts +76 -75
  100. package/dist/services/index.d.ts.map +1 -1
  101. package/dist/services/index.js +73 -71
  102. package/dist/services/index.js.map +1 -1
  103. package/dist/shutdown/mod.d.ts +26 -25
  104. package/dist/shutdown/mod.d.ts.map +1 -1
  105. package/dist/shutdown/mod.js +26 -25
  106. package/dist/shutdown/mod.js.map +1 -1
  107. package/dist/storage/clickhouse/database.d.ts +113 -115
  108. package/dist/storage/clickhouse/database.d.ts.map +1 -1
  109. package/dist/storage/clickhouse/database.js +65 -79
  110. package/dist/storage/clickhouse/database.js.map +1 -1
  111. package/dist/storage/clickhouse/errors.d.ts +25 -26
  112. package/dist/storage/clickhouse/errors.d.ts.map +1 -1
  113. package/dist/storage/clickhouse/errors.js +15 -17
  114. package/dist/storage/clickhouse/errors.js.map +1 -1
  115. package/dist/storage/clickhouse/mod.d.ts +10 -10
  116. package/dist/storage/clickhouse/mod.js +10 -10
  117. package/dist/storage/objects/bucket.d.ts +230 -203
  118. package/dist/storage/objects/bucket.d.ts.map +1 -1
  119. package/dist/storage/objects/bucket.js +146 -106
  120. package/dist/storage/objects/bucket.js.map +1 -1
  121. package/dist/storage/objects/error.d.ts +4 -4
  122. package/dist/storage/objects/error.js +4 -4
  123. package/dist/storage/objects/mod.d.ts +1 -1
  124. package/dist/storage/objects/mod.d.ts.map +1 -1
  125. package/dist/storage/objects/mod.js.map +1 -1
  126. package/dist/storage/objects/refs.d.ts +2 -5
  127. package/dist/storage/objects/refs.d.ts.map +1 -1
  128. package/dist/storage/objects/refs.js.map +1 -1
  129. package/dist/storage/postgres/database.d.ts +124 -149
  130. package/dist/storage/postgres/database.d.ts.map +1 -1
  131. package/dist/storage/postgres/database.js +98 -135
  132. package/dist/storage/postgres/database.js.map +1 -1
  133. package/dist/storage/postgres/errors.d.ts +42 -48
  134. package/dist/storage/postgres/errors.d.ts.map +1 -1
  135. package/dist/storage/postgres/errors.js +44 -51
  136. package/dist/storage/postgres/errors.js.map +1 -1
  137. package/dist/storage/postgres/interval.d.ts +19 -19
  138. package/dist/storage/postgres/interval.d.ts.map +1 -1
  139. package/dist/storage/postgres/interval.js +21 -21
  140. package/dist/storage/postgres/interval.js.map +1 -1
  141. package/dist/storage/redis/bitfield.d.ts +48 -23
  142. package/dist/storage/redis/bitfield.d.ts.map +1 -1
  143. package/dist/storage/redis/bitfield.js +38 -19
  144. package/dist/storage/redis/bitfield.js.map +1 -1
  145. package/dist/storage/redis/command.d.ts +16 -12
  146. package/dist/storage/redis/command.d.ts.map +1 -1
  147. package/dist/storage/redis/command.js +16 -12
  148. package/dist/storage/redis/command.js.map +1 -1
  149. package/dist/storage/redis/commands.d.ts +99 -100
  150. package/dist/storage/redis/commands.d.ts.map +1 -1
  151. package/dist/storage/redis/commands.js +84 -85
  152. package/dist/storage/redis/commands.js.map +1 -1
  153. package/dist/storage/redis/database.d.ts +138 -122
  154. package/dist/storage/redis/database.d.ts.map +1 -1
  155. package/dist/storage/redis/database.js +120 -101
  156. package/dist/storage/redis/database.js.map +1 -1
  157. package/dist/storage/redis/mod.d.ts +52 -48
  158. package/dist/storage/redis/mod.d.ts.map +1 -1
  159. package/dist/storage/redis/mod.js +52 -48
  160. package/dist/storage/redis/mod.js.map +1 -1
  161. package/dist/storage/redis/options.d.ts +26 -24
  162. package/dist/storage/redis/options.d.ts.map +1 -1
  163. package/dist/storage/redis/options.js.map +1 -1
  164. package/dist/storage/redis/pubsub.d.ts +16 -16
  165. package/dist/storage/redis/pubsub.d.ts.map +1 -1
  166. package/dist/storage/redis/pubsub.js +14 -14
  167. package/dist/storage/redis/pubsub.js.map +1 -1
  168. package/dist/storage/redis/reply.d.ts +80 -72
  169. package/dist/storage/redis/reply.d.ts.map +1 -1
  170. package/dist/storage/redis/reply.js +53 -46
  171. package/dist/storage/redis/reply.js.map +1 -1
  172. package/dist/storage/redis/scan.d.ts +4 -4
  173. package/dist/storage/redis/scan.d.ts.map +1 -1
  174. package/dist/storage/redis/scan.js +6 -6
  175. package/dist/storage/redis/scan.js.map +1 -1
  176. package/dist/storage/redis/script.d.ts +28 -21
  177. package/dist/storage/redis/script.d.ts.map +1 -1
  178. package/dist/storage/redis/script.js +29 -22
  179. package/dist/storage/redis/script.js.map +1 -1
  180. package/dist/storage/redis/target.d.ts +17 -1
  181. package/dist/storage/redis/target.d.ts.map +1 -1
  182. package/dist/storage/redis/target.js +30 -1
  183. package/dist/storage/redis/target.js.map +1 -1
  184. package/dist/storage/redis/wire.d.ts +6 -6
  185. package/dist/storage/redis/wire.d.ts.map +1 -1
  186. package/dist/storage/redis/wire.js +6 -6
  187. package/dist/storage/redis/wire.js.map +1 -1
  188. package/dist/testing/mod.d.ts +83 -88
  189. package/dist/testing/mod.d.ts.map +1 -1
  190. package/dist/testing/mod.js +75 -81
  191. package/dist/testing/mod.js.map +1 -1
  192. package/dist/testing/playwright.d.ts +28 -32
  193. package/dist/testing/playwright.d.ts.map +1 -1
  194. package/dist/testing/playwright.js +22 -27
  195. package/dist/testing/playwright.js.map +1 -1
  196. package/dist/testing/puppeteer.d.ts +11 -12
  197. package/dist/testing/puppeteer.d.ts.map +1 -1
  198. package/dist/testing/puppeteer.js +17 -18
  199. package/dist/testing/puppeteer.js.map +1 -1
  200. package/dist/testing/system.d.ts +72 -90
  201. package/dist/testing/system.d.ts.map +1 -1
  202. package/dist/testing/system.js +90 -107
  203. package/dist/testing/system.js.map +1 -1
  204. package/dist/tracing/http.d.ts +2 -1
  205. package/dist/tracing/http.d.ts.map +1 -1
  206. package/dist/tracing/http.js +2 -1
  207. package/dist/tracing/http.js.map +1 -1
  208. package/dist/tracing/node.d.ts.map +1 -1
  209. package/dist/tracing/node.js +1 -1
  210. package/dist/tracing/node.js.map +1 -1
  211. package/dist/tsconfig.build.tsbuildinfo +1 -1
  212. package/frontends/mod.test.ts +6 -2
  213. package/frontends/mod.ts +20 -19
  214. package/gateway/errors.ts +30 -32
  215. package/gateway/match.ts +61 -57
  216. package/gateway/middleware.ts +62 -64
  217. package/gateway/mod.ts +73 -76
  218. package/gateway/request.ts +143 -140
  219. package/gateway/serve.ts +58 -63
  220. package/gateways/mod.ts +25 -23
  221. package/internal/otel/http.test.ts +50 -0
  222. package/internal/otel/http.ts +40 -5
  223. package/internal/runtime/napi/napi.cjs +6 -5
  224. package/internal/runtime/napi/napi.d.cts +58 -16
  225. package/internal/runtime/shutdown.ts +113 -101
  226. package/log/logger.test.ts +8 -0
  227. package/log/logger.ts +48 -45
  228. package/metrics/mod.ts +138 -122
  229. package/otel.ts +6 -3
  230. package/package.json +6 -1
  231. package/pubsub/subscription.ts +93 -123
  232. package/pubsub/topic.ts +96 -130
  233. package/redaction/bridge.test.ts +99 -0
  234. package/redaction/mod.test.ts +188 -0
  235. package/redaction/mod.ts +226 -0
  236. package/reqctx/mod.ts +83 -86
  237. package/services/index.ts +78 -78
  238. package/shutdown/mod.ts +26 -25
  239. package/storage/clickhouse/database.ts +115 -129
  240. package/storage/clickhouse/errors.ts +27 -29
  241. package/storage/clickhouse/mod.ts +10 -10
  242. package/storage/objects/bucket.test.ts +168 -16
  243. package/storage/objects/bucket.ts +336 -247
  244. package/storage/objects/error.ts +4 -4
  245. package/storage/objects/mod.ts +1 -0
  246. package/storage/objects/refs.ts +2 -5
  247. package/storage/postgres/database.ts +131 -164
  248. package/storage/postgres/errors.ts +45 -52
  249. package/storage/postgres/interval.ts +21 -21
  250. package/storage/redis/bitfield.ts +51 -26
  251. package/storage/redis/command.ts +16 -12
  252. package/storage/redis/commands.ts +99 -100
  253. package/storage/redis/database.ts +145 -123
  254. package/storage/redis/mod.ts +52 -48
  255. package/storage/redis/options.ts +26 -24
  256. package/storage/redis/pubsub.ts +14 -14
  257. package/storage/redis/redis.test.ts +17 -2
  258. package/storage/redis/reply.ts +85 -77
  259. package/storage/redis/scan.ts +6 -6
  260. package/storage/redis/script.ts +29 -22
  261. package/storage/redis/target.ts +34 -1
  262. package/storage/redis/wire.ts +8 -8
  263. package/testing/mod.ts +99 -105
  264. package/testing/playwright.ts +32 -37
  265. package/testing/puppeteer.ts +22 -23
  266. package/testing/system.ts +117 -133
  267. package/tracing/http.ts +2 -1
  268. package/tracing/native.test.ts +158 -8
  269. package/tracing/node.ts +1 -0
@@ -0,0 +1,188 @@
1
+ import {expect, test} from 'bun:test';
2
+ import type {DescMethod} from '@bufbuild/protobuf';
3
+ import type {Redactor} from './mod';
4
+
5
+ // The public adapter accepts library descriptors, not descriptor-shaped objects.
6
+ function descriptorTypes(sdk: Redactor, descriptor: DescMethod) {
7
+ const grpc = sdk.grpc(descriptor);
8
+ grpc.request({metadata: [], message: new Uint8Array()});
9
+ grpc.response({metadata: [], trailers: []});
10
+ // @ts-expect-error Requests do not accept trailers.
11
+ grpc.request({metadata: [], trailers: []});
12
+ // @ts-expect-error Exchanges require their metadata.
13
+ grpc.request();
14
+ // @ts-expect-error No chained metadata view.
15
+ grpc.headers();
16
+ const http = sdk.http('GET', '/items');
17
+ const url: {route: string | null; path: string | null; query: string | null} =
18
+ http.requestUrl();
19
+ void url;
20
+ http.request({headers: []});
21
+ http.response({headers: [], body: new Uint8Array()});
22
+ // @ts-expect-error No chained request view.
23
+ http.request();
24
+ // @ts-expect-error No chained header view.
25
+ http.headers();
26
+ sdk.grpc({
27
+ // @ts-expect-error A method requires the full protobuf-es descriptor.
28
+ parent: {typeName: 'probe.Check'},
29
+ name: 'Run',
30
+ methodKind: 'unary',
31
+ });
32
+ }
33
+ void descriptorTypes;
34
+
35
+ const jsonRules = {
36
+ rules: {
37
+ json: {paths: [{entries: [{kind: {object_field: {field_name: 'token'}}}]}]},
38
+ },
39
+ };
40
+ const protobufRules = {
41
+ rules: {
42
+ protobuf: {paths: [{elements: [{field_number: 1, field_type: 'string'}]}]},
43
+ },
44
+ };
45
+
46
+ test('redacts copies using the configured policy and library descriptors', () => {
47
+ const config = {
48
+ environment: {
49
+ app_id: 'app',
50
+ env_name: 'test',
51
+ env_type: 'development',
52
+ cloud: 'local',
53
+ },
54
+ deployment: {
55
+ hosted_services: [
56
+ {
57
+ name: 'app',
58
+ routes: [
59
+ {
60
+ path: '/private/{id}',
61
+ methods: ['POST'],
62
+ endpoint: {
63
+ name: 'private',
64
+ recording: {
65
+ redaction: {
66
+ path_params: ['id'],
67
+ request_headers: ['user-agent'],
68
+ request: [jsonRules],
69
+ response: [jsonRules],
70
+ },
71
+ },
72
+ },
73
+ },
74
+ ...['Run', 'Repeat', 'Join', 'Chat'].map(name => ({
75
+ path: `/probe.Check/${name}`,
76
+ methods: ['POST'],
77
+ endpoint: {
78
+ name,
79
+ recording: {
80
+ redaction: {
81
+ request: [protobufRules],
82
+ response: [protobufRules],
83
+ },
84
+ },
85
+ },
86
+ })),
87
+ ],
88
+ },
89
+ ],
90
+ },
91
+ infra: {
92
+ resources: {
93
+ pubsub_clusters: [
94
+ {topics: [{encore_name: 'submitted', payload_redaction: jsonRules}]},
95
+ ],
96
+ },
97
+ },
98
+ };
99
+ const child = Bun.spawnSync({
100
+ cmd: [
101
+ process.execPath,
102
+ '-e',
103
+ `
104
+ import {create, createFileRegistry, fromBinary, toBinary} from '@bufbuild/protobuf';
105
+ import {FileDescriptorSetSchema} from '@bufbuild/protobuf/wkt';
106
+ import {redactor} from './mod';
107
+ const files = createFileRegistry(create(FileDescriptorSetSchema, {
108
+ file: [{
109
+ name: 'probe.proto', package: 'probe', syntax: 'proto3',
110
+ messageType: [{name: 'Message', field: [
111
+ {name: 'token', number: 1, type: 9},
112
+ {name: 'label', number: 2, type: 9},
113
+ ]}],
114
+ service: [{name: 'Check', method: [
115
+ {name: 'Run'},
116
+ {name: 'Repeat', serverStreaming: true},
117
+ {name: 'Join', clientStreaming: true},
118
+ {name: 'Chat', clientStreaming: true, serverStreaming: true},
119
+ ].map(method => ({...method, inputType: '.probe.Message', outputType: '.probe.Message'}))}],
120
+ }],
121
+ }));
122
+ const schema = files.getMessage('probe.Message');
123
+ const protobuf = toBinary(schema, create(schema, {token: 'private', label: 'ok'}));
124
+ const sdk = redactor();
125
+ const grpc = files.getService('probe.Check').methods.map(method => {
126
+ const rpc = sdk.grpc(method);
127
+ const decode = payload => payload.kind === 'recorded'
128
+ ? {...payload, body: fromBinary(schema, payload.body)} : payload;
129
+ return [decode(rpc.request({metadata: [], message: protobuf}).message), decode(rpc.response({metadata: [], message: protobuf}).message)];
130
+ });
131
+ const http = sdk.http('POST', '/private/synthetic-secret');
132
+ const original = 'synthetic-agent';
133
+ const safe = http.request({headers: [['user-agent', original]]}).headers;
134
+ const json = new TextEncoder().encode('{"token":"private","label":"ok"}');
135
+ const decode = payload => payload.kind === 'recorded'
136
+ ? {...payload, body: JSON.parse(new TextDecoder().decode(payload.body))} : payload;
137
+ console.log(JSON.stringify({
138
+ path: http.requestUrl().path,
139
+ headers: safe,
140
+ original: original,
141
+ jsonOriginal: new TextDecoder().decode(json),
142
+ protobufOriginal: fromBinary(schema, protobuf),
143
+ bodies: [http.request({headers: [], body: json}).body, http.response({headers: [], body: json}).body, sdk.topic('submitted').publish(json)].map(decode),
144
+ unknownTopic: sdk.topic('unknown').publish(json),
145
+ unknownDelivery: sdk.topic('unknown').delivery('worker', json),
146
+ grpc,
147
+ }));
148
+ `,
149
+ ],
150
+ cwd: import.meta.dir,
151
+ env: {...process.env, ENCORE_RUNTIME_CONFIG: JSON.stringify(config)},
152
+ });
153
+ if (child.exitCode !== 0) {
154
+ throw new Error(`${child.stdout.toString()}\n${child.stderr.toString()}`);
155
+ }
156
+ const recorded = {
157
+ kind: 'recorded',
158
+ body: {token: '[REDACTED]', label: 'ok'},
159
+ truncated: false,
160
+ };
161
+ const protobufRecorded = {
162
+ ...recorded,
163
+ body: {...recorded.body, $typeName: 'probe.Message'},
164
+ };
165
+ const withheld = {kind: 'withheld', reason: 'streaming'};
166
+ expect(
167
+ JSON.parse(child.stdout.toString().trim().split('\n').at(-1)!),
168
+ ).toEqual({
169
+ path: '/private/REDACTED',
170
+ headers: [['user-agent', '[REDACTED]']],
171
+ original: 'synthetic-agent',
172
+ jsonOriginal: '{"token":"private","label":"ok"}',
173
+ protobufOriginal: {
174
+ $typeName: 'probe.Message',
175
+ token: 'private',
176
+ label: 'ok',
177
+ },
178
+ bodies: [recorded, recorded, recorded],
179
+ unknownTopic: {kind: 'omit'},
180
+ unknownDelivery: {kind: 'omit'},
181
+ grpc: [
182
+ [protobufRecorded, protobufRecorded],
183
+ [protobufRecorded, withheld],
184
+ [withheld, protobufRecorded],
185
+ [withheld, withheld],
186
+ ],
187
+ });
188
+ });
@@ -0,0 +1,226 @@
1
+ import {Buffer} from 'node:buffer';
2
+ import type {DescMethod} from '@bufbuild/protobuf';
3
+ import {RT} from '../internal/runtime/mod';
4
+
5
+ /** HTTP headers or gRPC metadata in wire form. gRPC binary values use base64. */
6
+ export type Headers = Iterable<readonly [name: string, value: string]>;
7
+
8
+ export interface RequestUrl {
9
+ readonly route: string | null;
10
+ /** Safe path; never substitute the original if null. */
11
+ readonly path: string | null;
12
+ /** Safe query without the leading question mark. */
13
+ readonly query: string | null;
14
+ }
15
+
16
+ export type Payload =
17
+ | {readonly kind: 'omit'}
18
+ | {
19
+ readonly kind: 'recorded';
20
+ readonly body: Uint8Array;
21
+ readonly truncated: boolean;
22
+ }
23
+ | {readonly kind: 'withheld'; readonly reason: string};
24
+
25
+ export interface HttpExchange {
26
+ readonly headers: Headers;
27
+ readonly body?: Uint8Array;
28
+ }
29
+
30
+ export interface SafeHttpExchange {
31
+ readonly headers: [string, string][];
32
+ readonly body?: Payload;
33
+ }
34
+
35
+ export interface GrpcRequest {
36
+ readonly metadata: Headers;
37
+ readonly message?: Uint8Array;
38
+ }
39
+
40
+ export interface GrpcResponse extends GrpcRequest {
41
+ readonly trailers?: Headers;
42
+ }
43
+
44
+ export interface SafeGrpcRequest {
45
+ readonly metadata: [string, string][];
46
+ readonly message?: Payload;
47
+ }
48
+
49
+ export interface SafeGrpcResponse extends SafeGrpcRequest {
50
+ readonly trailers?: [string, string][];
51
+ }
52
+
53
+ type HttpSpec = {kind: 'http'; method: string; target: string};
54
+ type GrpcSpec = {
55
+ kind: 'grpc';
56
+ service: string;
57
+ method: string;
58
+ client_streaming: boolean;
59
+ server_streaming: boolean;
60
+ };
61
+ type TopicSpec = {kind: 'topic'; name: string} & (
62
+ {operation: 'publish'} | {operation: 'delivery'; subscription: string}
63
+ );
64
+ type HeaderPairs = [string, string][];
65
+ type Spec =
66
+ | (HttpSpec & {operation: 'request_url'})
67
+ | (HttpSpec & {
68
+ operation: 'exchange';
69
+ response: boolean;
70
+ headers: HeaderPairs;
71
+ capture: boolean;
72
+ })
73
+ | (GrpcSpec & {
74
+ operation: 'exchange';
75
+ response: boolean;
76
+ metadata: HeaderPairs;
77
+ trailers: HeaderPairs;
78
+ capture: boolean;
79
+ })
80
+ | TopicSpec;
81
+ type EncodedPayload =
82
+ | Exclude<Payload, {kind: 'recorded'}>
83
+ | {kind: 'recorded'; body: string; truncated: boolean};
84
+ type Result =
85
+ | ({kind: 'request_url'} & RequestUrl)
86
+ | {kind: 'http'; headers: HeaderPairs; body: EncodedPayload | null}
87
+ | {
88
+ kind: 'grpc';
89
+ metadata: HeaderPairs;
90
+ message: EncodedPayload | null;
91
+ trailers: HeaderPairs;
92
+ }
93
+ | EncodedPayload;
94
+
95
+ function apply(spec: Spec, payload: Uint8Array = new Uint8Array()): Result {
96
+ return JSON.parse(
97
+ RT.redact(
98
+ JSON.stringify(spec),
99
+ Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength),
100
+ ),
101
+ ) as Result;
102
+ }
103
+
104
+ function headerPairs(headers: Headers): HeaderPairs {
105
+ return Array.from(headers, ([name, value]) => [name, value]);
106
+ }
107
+
108
+ function payload(result: EncodedPayload): Payload {
109
+ switch (result.kind) {
110
+ case 'omit':
111
+ case 'withheld':
112
+ return result;
113
+ case 'recorded':
114
+ return {...result, body: Buffer.from(result.body, 'base64')};
115
+ default:
116
+ throw new Error('unexpected payload redaction result');
117
+ }
118
+ }
119
+
120
+ /** Applies the service's deployed policy to copies, without emitting telemetry. */
121
+ export class Redactor {
122
+ http(method: string, pathAndQuery: string) {
123
+ const spec = {kind: 'http', method, target: pathAndQuery} as const;
124
+ const exchange = (
125
+ response: boolean,
126
+ original: HttpExchange,
127
+ ): SafeHttpExchange => {
128
+ const result = apply(
129
+ {
130
+ ...spec,
131
+ operation: 'exchange',
132
+ response,
133
+ headers: headerPairs(original.headers),
134
+ capture: original.body !== undefined,
135
+ },
136
+ original.body,
137
+ );
138
+ if (result.kind !== 'http')
139
+ throw new Error('unexpected HTTP redaction result');
140
+ return {
141
+ headers: result.headers,
142
+ ...(result.body === null ? {} : {body: payload(result.body)}),
143
+ };
144
+ };
145
+ return {
146
+ requestUrl: (): RequestUrl => {
147
+ const result = apply({...spec, operation: 'request_url'});
148
+ if (result.kind !== 'request_url')
149
+ throw new Error('unexpected request URL redaction result');
150
+ return {route: result.route, path: result.path, query: result.query};
151
+ },
152
+ request: (original: HttpExchange) => exchange(false, original),
153
+ response: (original: HttpExchange) => exchange(true, original),
154
+ };
155
+ }
156
+
157
+ grpc(descriptor: DescMethod) {
158
+ const spec = {
159
+ kind: 'grpc',
160
+ service: descriptor.parent.typeName,
161
+ method: descriptor.name,
162
+ client_streaming:
163
+ descriptor.methodKind === 'client_streaming' ||
164
+ descriptor.methodKind === 'bidi_streaming',
165
+ server_streaming:
166
+ descriptor.methodKind === 'server_streaming' ||
167
+ descriptor.methodKind === 'bidi_streaming',
168
+ } as const;
169
+ const exchange = (
170
+ response: boolean,
171
+ original: GrpcResponse,
172
+ ): SafeGrpcResponse => {
173
+ const result = apply(
174
+ {
175
+ ...spec,
176
+ operation: 'exchange',
177
+ response,
178
+ metadata: headerPairs(original.metadata),
179
+ trailers: headerPairs(original.trailers ?? []),
180
+ capture: original.message !== undefined,
181
+ },
182
+ original.message,
183
+ );
184
+ if (result.kind !== 'grpc')
185
+ throw new Error('unexpected gRPC redaction result');
186
+ return {
187
+ metadata: result.metadata,
188
+ ...(result.message === null ? {} : {message: payload(result.message)}),
189
+ ...(original.trailers === undefined ? {} : {trailers: result.trailers}),
190
+ };
191
+ };
192
+ return {
193
+ request: (original: GrpcRequest): SafeGrpcRequest =>
194
+ exchange(false, original),
195
+ response: (original: GrpcResponse) => exchange(true, original),
196
+ };
197
+ }
198
+
199
+ topic(name: string) {
200
+ const redact = (spec: TopicSpec, original: Uint8Array): Payload => {
201
+ const result = apply(spec, original);
202
+ if (
203
+ result.kind !== 'omit' &&
204
+ result.kind !== 'withheld' &&
205
+ result.kind !== 'recorded'
206
+ )
207
+ throw new Error('unexpected payload redaction result');
208
+ return payload(result);
209
+ };
210
+ return {
211
+ /** Redact a publish payload using the topic's deployed policy. */
212
+ publish: (original: Uint8Array) =>
213
+ redact({kind: 'topic', name, operation: 'publish'}, original),
214
+ /** Redact a delivery payload using the subscription's deployed policy. */
215
+ delivery: (subscription: string, original: Uint8Array) =>
216
+ redact(
217
+ {kind: 'topic', name, operation: 'delivery', subscription},
218
+ original,
219
+ ),
220
+ };
221
+ }
222
+ }
223
+
224
+ export function redactor(): Redactor {
225
+ return new Redactor();
226
+ }