@ultimat3/testing 30.8.0 → 31.0.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 (159) hide show
  1. package/CLAUDE.md +49 -62
  2. package/README.md +179 -39
  3. package/package.json +23 -17
  4. package/src/ai-conformance-answer.ts +67 -0
  5. package/src/ai-gateway-conformance.ts +105 -0
  6. package/src/ai-provider-conformance.ts +69 -0
  7. package/src/ai-provider-transport-conformance.ts +170 -0
  8. package/src/audit-sink-conformance.ts +204 -0
  9. package/src/auth-adapter-conformance-credentials.ts +124 -0
  10. package/src/auth-adapter-conformance-mfa.ts +70 -0
  11. package/src/auth-adapter-conformance-passkeys.ts +133 -0
  12. package/src/auth-adapter-conformance-sessions.ts +115 -0
  13. package/src/auth-adapter-conformance-support.ts +71 -0
  14. package/src/auth-adapter-conformance-users.ts +128 -0
  15. package/src/auth-adapter-conformance.ts +34 -0
  16. package/src/auth-limiter-factory-conformance.ts +224 -0
  17. package/src/auth-server-store-conformance-records.ts +69 -0
  18. package/src/auth-server-store-conformance.ts +208 -0
  19. package/src/cache-tier-conformance-checks.ts +142 -0
  20. package/src/cache-tier-conformance.ts +24 -0
  21. package/src/cassette-format.ts +8 -13
  22. package/src/cassette-record.ts +1 -1
  23. package/src/cdp-browser.ts +10 -11
  24. package/src/cdp-e2e-page.ts +2 -2
  25. package/src/cdp-e2e-session.ts +2 -2
  26. package/src/cdp-network-probe.ts +1 -1
  27. package/src/cdp-offline-script.ts +2 -2
  28. package/src/clock-conformance.ts +126 -0
  29. package/src/conformance.ts +239 -0
  30. package/src/e2e-browser-handle.ts +1 -2
  31. package/src/e2e-error-codes.ts +17 -16
  32. package/src/e2e-run.ts +4 -3
  33. package/src/embedder-conformance.ts +101 -0
  34. package/src/entity-conformance-aggregates.ts +210 -0
  35. package/src/entity-conformance-batches.ts +216 -0
  36. package/src/entity-conformance-bulk.ts +379 -0
  37. package/src/entity-conformance-checks.ts +27 -0
  38. package/src/entity-conformance-entities.ts +52 -0
  39. package/src/entity-conformance-locks.ts +286 -0
  40. package/src/entity-conformance-matrix.ts +397 -0
  41. package/src/entity-conformance-reads.ts +241 -0
  42. package/src/entity-conformance-support.ts +56 -0
  43. package/src/entity-conformance-tenancy.ts +296 -0
  44. package/src/entity-conformance-values.ts +305 -0
  45. package/src/entity-conformance-versions.ts +60 -0
  46. package/src/entity-conformance-writes.ts +348 -0
  47. package/src/entity-driver-conformance.ts +103 -0
  48. package/src/error-groups-store-conformance.ts +198 -0
  49. package/src/error-reporter-conformance.ts +119 -0
  50. package/src/errors.ts +41 -11
  51. package/src/event-bus-conformance.ts +161 -0
  52. package/src/exercise-drift-hint.ts +4 -1
  53. package/src/exercise-judge.ts +5 -3
  54. package/src/exercise-override-input.ts +22 -9
  55. package/src/exercise-override-line.ts +98 -0
  56. package/src/exercise-report.ts +30 -51
  57. package/src/exercise-sweeps.ts +3 -1
  58. package/src/exercise.ts +38 -19
  59. package/src/factories.ts +192 -179
  60. package/src/factory-api.ts +131 -0
  61. package/src/factory-associations.ts +67 -0
  62. package/src/factory-errors.ts +38 -0
  63. package/src/factory-lint.ts +92 -0
  64. package/src/factory-persist.ts +74 -16
  65. package/src/factory-pipeline.ts +191 -0
  66. package/src/factory-registry.ts +2 -1
  67. package/src/factory-types.ts +131 -0
  68. package/src/failure-store-conformance.ts +137 -0
  69. package/src/fixture-jobs.ts +50 -15
  70. package/src/fixture-mail.ts +7 -7
  71. package/src/fixture-seed.ts +111 -0
  72. package/src/fixture-statements.ts +68 -52
  73. package/src/framework-fixtures.ts +1 -1
  74. package/src/idempotency-store-conformance.ts +186 -0
  75. package/src/idempotency-store-replay-conformance.ts +140 -0
  76. package/src/idempotency-store-tx-conformance.ts +132 -0
  77. package/src/idempotency-store-world-conformance.ts +82 -0
  78. package/src/identity-provider-conformance.ts +144 -0
  79. package/src/image-transform-conformance.ts +89 -0
  80. package/src/index.ts +68 -157
  81. package/src/isr-store-conformance.ts +113 -0
  82. package/src/job-sim-effects.ts +19 -31
  83. package/src/job-sim-world.ts +6 -15
  84. package/src/lease-store-conformance.ts +195 -0
  85. package/src/mail-driver-conformance.ts +108 -0
  86. package/src/matcher-doubles.ts +104 -0
  87. package/src/matcher-stub.ts +78 -0
  88. package/src/matcher-surface.ts +21 -0
  89. package/src/matchers.ts +19 -1
  90. package/src/mcp-confirmation-store-conformance.ts +262 -0
  91. package/src/meter-store-conformance.ts +135 -0
  92. package/src/notify-digest-conformance.ts +133 -0
  93. package/src/notify-inbox-conformance.ts +130 -0
  94. package/src/notify-ledger-conformance.ts +134 -0
  95. package/src/notify-preference-conformance.ts +49 -0
  96. package/src/notify-stores-conformance.ts +73 -0
  97. package/src/outbox-store-conformance-claims.ts +112 -0
  98. package/src/outbox-store-conformance-subject.ts +65 -0
  99. package/src/outbox-store-conformance.ts +71 -0
  100. package/src/per-test-reset.ts +55 -20
  101. package/src/plan-oracle.ts +10 -3
  102. package/src/plan-sweep.ts +37 -12
  103. package/src/preload.ts +4 -2
  104. package/src/purge-conformance.ts +79 -0
  105. package/src/push-device-conformance.ts +124 -0
  106. package/src/push-subscription-conformance.ts +123 -0
  107. package/src/quiet-logs.ts +4 -4
  108. package/src/rate-limit-store-conformance.ts +178 -0
  109. package/src/registry-leak-error.ts +8 -1
  110. package/src/scale-sweep-run.ts +3 -1
  111. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  112. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  113. package/src/scrape-driver-conformance-site.ts +84 -0
  114. package/src/scrape-driver-conformance.ts +34 -0
  115. package/src/sealed-dns-resolver.ts +56 -0
  116. package/src/sealed-dns.ts +63 -64
  117. package/src/sealed-network.ts +13 -12
  118. package/src/sealed-node-sockets.ts +63 -0
  119. package/src/sealed-sockets.ts +13 -8
  120. package/src/sealed-udp.ts +118 -0
  121. package/src/search-index-conformance-list.ts +76 -0
  122. package/src/search-index-conformance-support.ts +69 -0
  123. package/src/search-index-conformance-versions.ts +66 -0
  124. package/src/search-index-conformance.ts +126 -0
  125. package/src/secret-source-conformance.ts +91 -0
  126. package/src/seed-factories.ts +57 -0
  127. package/src/seed-writer.ts +8 -19
  128. package/src/semantic-cache-factory-conformance.ts +86 -0
  129. package/src/sms-transport-conformance.ts +102 -0
  130. package/src/step-store-conformance.ts +171 -0
  131. package/src/storage-conformance-read-checks.ts +132 -0
  132. package/src/storage-conformance-shape.ts +121 -0
  133. package/src/storage-conformance-stream-checks.ts +226 -0
  134. package/src/storage-conformance.ts +34 -0
  135. package/src/stub-action.ts +24 -0
  136. package/src/stub-errors.ts +86 -0
  137. package/src/stub-job.ts +30 -0
  138. package/src/stub-query.ts +25 -0
  139. package/src/stub-script.ts +76 -0
  140. package/src/stub-stack.ts +29 -0
  141. package/src/stub.ts +73 -0
  142. package/src/swap-adapter.ts +135 -0
  143. package/src/test-scope.ts +96 -0
  144. package/src/test-types.ts +1 -1
  145. package/src/totp-replay-guard-conformance.ts +76 -0
  146. package/src/transport-conformance.ts +179 -0
  147. package/src/upload-scanner-conformance.ts +112 -0
  148. package/src/vector-store-conformance-checks.ts +174 -0
  149. package/src/vector-store-conformance.ts +21 -0
  150. package/src/cdp-connection.ts +0 -291
  151. package/src/cdp-errors.ts +0 -179
  152. package/src/cdp-launch-attempt.ts +0 -224
  153. package/src/cdp-launch-candidates.ts +0 -62
  154. package/src/cdp-launch-profile.ts +0 -106
  155. package/src/cdp-launch-reap.ts +0 -68
  156. package/src/cdp-launch-wire.ts +0 -171
  157. package/src/cdp-launch.ts +0 -175
  158. package/src/cdp-pipe.ts +0 -77
  159. package/src/cdp-wire-watch.ts +0 -113
package/src/sealed-dns.ts CHANGED
@@ -1,86 +1,85 @@
1
- // The resolver half of the sealed network: `Bun.dns.lookup`, `dns.lookup` and `dns.promises.lookup`.
2
- // Only the patching lives here; WHAT a name resolves to is `sealed-network.ts`'s one gate, handed in,
3
- // so a host `fetch` would answer by mock resolves and a host it would refuse does not. A named ESM
4
- // import (`import { lookup } from 'node:dns'`) binds before the seal and is NOT covered (measured).
1
+ // The resolver half of the sealed network: every `Bun.dns` resolution function, which is the ROOT
2
+ // every `node:dns` module function calls at call time — so a named import bound before the seal is
3
+ // sealed too (`sealed-dns-paths.test.ts`). `Resolver` instances: `sealed-dns-resolver.ts`. WHAT a
4
+ // name resolves to is `sealed-network.ts`'s one gate, handed in.
5
5
 
6
- // why: `dns.lookup` and `dns.promises.lookup` are what an app's own resolver calls; Bun ships both.
7
- import nodeDns from 'node:dns';
6
+ import { installResolverSeal } from './sealed-dns-resolver';
8
7
 
9
- /** One lookup's verdict: the addresses to answer, a refusal to raise, or `real` for the resolver. */
8
+ /** One query's verdict: the addresses to answer, a refusal to raise, or `real` for the resolver. */
10
9
  export type DnsVerdict =
11
10
  | { readonly answer: readonly string[] }
12
11
  | { readonly refused: Error }
13
12
  | { readonly real: true };
14
13
 
15
- export type DnsGate = (hostname: string) => DnsVerdict;
14
+ /** `LOOKUP` (getaddrinfo), `REVERSE` (an address to its names) or a record type: `A`, `MX`, … */
15
+ export type DnsGate = (name: string, query: string) => DnsVerdict;
16
16
 
17
- interface LookupEntry {
18
- readonly address: string;
19
- readonly family: number;
20
- }
17
+ /**
18
+ * The queries an address list can answer. A mock declares an HTTP endpoint, not a zone: an MX or
19
+ * TXT answer would be invented, so the gate answers only these and refuses the rest.
20
+ */
21
+ export const ADDRESS_QUERIES: ReadonlySet<string> = new Set(['LOOKUP', 'A', 'ANY']);
21
22
 
22
23
  const familyOf = (address: string): number => (address.includes(':') ? 6 : 4);
23
24
 
24
- const entriesOf = (addresses: readonly string[]): LookupEntry[] =>
25
- addresses.map((address) => ({ address, family: familyOf(address) }));
25
+ /** The raw shape `Bun.dns` answers per query; `node:dns` maps it as it maps a real one. */
26
+ const shaped = (query: string, addresses: readonly string[]): unknown[] =>
27
+ addresses.map((address) => {
28
+ if (query === 'LOOKUP') return { address, family: familyOf(address), ttl: 0 };
29
+ if (query === 'ANY') return { address, ttl: 0, type: familyOf(address) === 6 ? 'AAAA' : 'A' };
30
+ return { address, ttl: 0 };
31
+ });
26
32
 
27
- type NodeCallback = (error: unknown, address?: unknown, family?: number) => void;
33
+ /** Each async `Bun.dns` resolver and the query its arguments ask. */
34
+ const BUN_QUERIES: Readonly<Record<string, (args: readonly unknown[]) => string>> = {
35
+ lookup: () => 'LOOKUP',
36
+ resolve: (args) => (typeof args[1] === 'string' ? args[1].toUpperCase() : 'A'),
37
+ resolveAny: () => 'ANY',
38
+ resolveCaa: () => 'CAA',
39
+ resolveCname: () => 'CNAME',
40
+ resolveMx: () => 'MX',
41
+ resolveNaptr: () => 'NAPTR',
42
+ resolveNs: () => 'NS',
43
+ resolvePtr: () => 'PTR',
44
+ resolveSoa: () => 'SOA',
45
+ resolveSrv: () => 'SRV',
46
+ resolveTxt: () => 'TXT',
47
+ reverse: () => 'REVERSE',
48
+ lookupService: () => 'REVERSE',
49
+ };
28
50
 
29
- /** Node's `(hostname, options?, callback)`; `options.all` answers the list, a number is a family. */
30
- const wantsAll = (options: unknown): boolean =>
31
- typeof options === 'object' && options !== null && 'all' in options && options.all === true;
51
+ type Resolve = (...args: unknown[]) => Promise<unknown>;
32
52
 
33
53
  /**
34
- * Patch the three resolvers and return the uninstaller, which puts back exactly what was there.
54
+ * Patch every resolver and return the uninstaller, which puts back exactly what was there.
35
55
  * Assigned through `Reflect.set`: each is a writable data property the types declare a function.
36
56
  */
37
57
  export function installDnsSeal(gate: DnsGate): () => void {
38
- const originalBun = Reflect.get(Bun.dns, 'lookup') as typeof Bun.dns.lookup;
39
- const originalNode = Reflect.get(nodeDns, 'lookup') as (...args: unknown[]) => void;
40
- const originalPromises = Reflect.get(nodeDns.promises, 'lookup') as (
41
- ...args: unknown[]
42
- ) => Promise<unknown>;
43
-
44
- const sealedBun = async (hostname: string, options?: unknown): Promise<unknown> => {
45
- const verdict = gate(hostname);
58
+ const originals = new Map<string, unknown>();
59
+ for (const [name, queryOf] of Object.entries(BUN_QUERIES)) {
60
+ const original = Reflect.get(Bun.dns, name) as Resolve;
61
+ originals.set(name, original);
62
+ const sealed: Resolve = async (...args) => {
63
+ const query = queryOf(args);
64
+ const verdict = gate(String(args[0]), query);
65
+ if ('refused' in verdict) throw verdict.refused;
66
+ if ('answer' in verdict) return shaped(query, verdict.answer);
67
+ return Reflect.apply(original, Bun.dns, args);
68
+ };
69
+ Reflect.set(Bun.dns, name, sealed);
70
+ }
71
+ // `prefetch` is synchronous and answers nothing: a mocked name has nothing to warm, and an
72
+ // unmocked one throws here rather than hide the egress until the dial that follows it.
73
+ const originalPrefetch = Reflect.get(Bun.dns, 'prefetch') as (...args: unknown[]) => void;
74
+ originals.set('prefetch', originalPrefetch);
75
+ Reflect.set(Bun.dns, 'prefetch', (...args: unknown[]): void => {
76
+ const verdict = gate(String(args[0]), 'LOOKUP');
46
77
  if ('refused' in verdict) throw verdict.refused;
47
- if ('answer' in verdict) return entriesOf(verdict.answer).map((one) => ({ ...one, ttl: 0 }));
48
- return Reflect.apply(originalBun, Bun.dns, [hostname, options]);
49
- };
50
-
51
- const sealedNode = (hostname: string, ...rest: unknown[]): void => {
52
- const verdict = gate(hostname);
53
- if ('real' in verdict) {
54
- Reflect.apply(originalNode, nodeDns, [hostname, ...rest]);
55
- return;
56
- }
57
- const callback = rest.findLast((one) => typeof one === 'function') as NodeCallback | undefined;
58
- const options = rest.length > 1 ? rest[0] : undefined;
59
- // A real lookup answers on a later tick, and a caller may rely on it: never synchronously.
60
- queueMicrotask(() => {
61
- if ('refused' in verdict) return callback?.(verdict.refused);
62
- const entries = entriesOf(verdict.answer);
63
- if (wantsAll(options)) return callback?.(null, entries);
64
- return callback?.(null, entries[0]?.address, entries[0]?.family);
65
- });
66
- };
67
-
68
- const sealedPromises = async (hostname: string, options?: unknown): Promise<unknown> => {
69
- const verdict = gate(hostname);
70
- if ('refused' in verdict) throw verdict.refused;
71
- if ('real' in verdict) {
72
- return Reflect.apply(originalPromises, nodeDns.promises, [hostname, options]);
73
- }
74
- const entries = entriesOf(verdict.answer);
75
- return wantsAll(options) ? entries : entries[0];
76
- };
77
-
78
- Reflect.set(Bun.dns, 'lookup', sealedBun);
79
- Reflect.set(nodeDns, 'lookup', sealedNode);
80
- Reflect.set(nodeDns.promises, 'lookup', sealedPromises);
78
+ if ('real' in verdict) Reflect.apply(originalPrefetch, Bun.dns, args);
79
+ });
80
+ const restoreResolver = installResolverSeal(gate);
81
81
  return () => {
82
- Reflect.set(Bun.dns, 'lookup', originalBun);
83
- Reflect.set(nodeDns, 'lookup', originalNode);
84
- Reflect.set(nodeDns.promises, 'lookup', originalPromises);
82
+ for (const [name, original] of originals) Reflect.set(Bun.dns, name, original);
83
+ restoreResolver();
85
84
  };
86
85
  }
@@ -9,7 +9,7 @@ import { mockRoute, routeMatches, routeNamesHost } from './mock-route';
9
9
  import type { LoggedRequest } from './request-log';
10
10
  import { hasStreamBody, headersOf, isOpenEnded, readBody, requestProbe } from './request-log';
11
11
  import type { DnsVerdict } from './sealed-dns';
12
- import { installDnsSeal } from './sealed-dns';
12
+ import { ADDRESS_QUERIES, installDnsSeal } from './sealed-dns';
13
13
  import { installSocketSeal } from './sealed-sockets';
14
14
 
15
15
  export type FetchLike = typeof globalThis.fetch;
@@ -99,25 +99,26 @@ const isAllowedName = (hostname: string): boolean =>
99
99
 
100
100
  /**
101
101
  * The resolver's gate, in `fetch`'s order: offline refuses every name, this machine and an allowed
102
- * host resolve for real, a host a mock answers resolves to `MOCKED_HOST_ADDRESS`, the rest is
103
- * `X_TEST_NETWORK_SEALED` — the code `fetch` would have raised a moment later.
102
+ * host resolve for real, as does a `LOOKUP` of an address literal (no query leaves; a `REVERSE` of
103
+ * one does), a host a mock answers resolves to `MOCKED_HOST_ADDRESS` for an address query only,
104
+ * the rest is `X_TEST_NETWORK_SEALED` — the code `fetch` would have raised a moment later.
104
105
  */
105
- const dnsVerdict = (hostname: string): DnsVerdict => {
106
+ const dnsVerdict = (hostname: string, query: string): DnsVerdict => {
106
107
  const name = hostname.toLowerCase().replace(/^\[|\]$/g, '');
107
108
  const url = `dns://${name}`;
109
+ const method = query === 'LOOKUP' || query === 'REVERSE' ? query : `RESOLVE ${query}`;
108
110
  if (state.network !== 'online') {
109
- return { refused: new NetworkOfflineError({ url, method: 'LOOKUP', mode: state.network }) };
111
+ return { refused: new NetworkOfflineError({ url, method, mode: state.network }) };
110
112
  }
111
- if (isThisMachine(name) || peerAddressClass(name) !== undefined || isAllowedName(name)) {
112
- return { real: true };
113
- }
114
- if (state.mocks.some((route) => routeNamesHost(route, name))) {
113
+ const literal = query === 'LOOKUP' && peerAddressClass(name) !== undefined;
114
+ if (isThisMachine(name) || literal || isAllowedName(name)) return { real: true };
115
+ if (ADDRESS_QUERIES.has(query) && state.mocks.some((route) => routeNamesHost(route, name))) {
115
116
  return { answer: [MOCKED_HOST_ADDRESS] };
116
117
  }
117
118
  const allowed = [...state.allowed];
118
- return {
119
- refused: new NetworkSealedError({ url, method: 'LOOKUP', allowed, transport: 'dns' }),
120
- };
119
+ // A record no mock answers (MX, TXT, a reverse) is lifted by `allowHost` alone: say that first.
120
+ const transport = ADDRESS_QUERIES.has(query) ? 'dns' : 'dns-record';
121
+ return { refused: new NetworkSealedError({ url, method, allowed, transport }) };
121
122
  };
122
123
 
123
124
  /** Replace global fetch, `WebSocket`, `Bun.connect` and the resolvers. Idempotent: sealing twice
@@ -0,0 +1,63 @@
1
+ // The `node:*` half of the socket seal: `net`, `tls`, `http(s)` and `http2` all dial through
2
+ // `net.Socket#connect` (measured; none reaches `Bun.connect` or `fetch`), so that one prototype is
3
+ // the root. WHETHER a dial may leave is `sealed-network.ts`'s socket gate, handed in.
4
+
5
+ // why: `net.Socket` is the class every node:* client socket is, and the only place they all meet.
6
+ import net from 'node:net';
7
+ import type { SocketGate } from './sealed-sockets';
8
+
9
+ /** A dial target as a URL, so the gate parses one shape. IPv6 literals need their brackets. */
10
+ export const dialUrl = (hostname: string, port: unknown, scheme: 'tcp' | 'udp' = 'tcp'): string => {
11
+ const host = hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname;
12
+ return `${scheme}://${host}:${typeof port === 'number' || typeof port === 'string' ? port : 0}`;
13
+ };
14
+
15
+ interface Target {
16
+ readonly host?: unknown;
17
+ readonly hostname?: unknown;
18
+ readonly port?: unknown;
19
+ readonly path?: unknown;
20
+ }
21
+
22
+ const isRecord = (value: unknown): value is Target => typeof value === 'object' && value !== null;
23
+
24
+ /**
25
+ * The TCP dial `connect`'s arguments name, or `undefined` for a unix socket — a path on this
26
+ * machine, never egress. Node's three shapes: `[options, cb]` (what `net.connect`, `tls`, `http`
27
+ * hand it), `(options, cb)` and `(port, host?, cb)`. No host is Node's `localhost`.
28
+ */
29
+ const tcpTarget = (args: readonly unknown[]): string | undefined => {
30
+ const first = Array.isArray(args[0]) ? args[0][0] : args[0];
31
+ if (isRecord(first)) {
32
+ const host = first.host ?? first.hostname;
33
+ if (typeof host !== 'string')
34
+ return typeof first.path === 'string' ? undefined : 'tcp://localhost:0';
35
+ return dialUrl(host, first.port);
36
+ }
37
+ if (typeof first === 'string' && !/^\d+$/.test(first)) return undefined;
38
+ return dialUrl(typeof args[1] === 'string' ? args[1] : 'localhost', first);
39
+ };
40
+
41
+ type Connect = (this: net.Socket, ...args: unknown[]) => net.Socket;
42
+
43
+ /**
44
+ * Patch `net.Socket#connect` and return the uninstaller. A refusal is a dial in flight that fails:
45
+ * `connecting` as the real one sets it, so `http`'s first write queues instead of failing
46
+ * `ERR_SOCKET_CLOSED` (measured), then the `error` event a macrotask later, once every client has
47
+ * its listener on. A throw from inside `http.get` would bypass every `error` handler the app wrote.
48
+ */
49
+ export function installNodeSocketSeal(gate: SocketGate): () => void {
50
+ const original = Reflect.get(net.Socket.prototype, 'connect') as Connect;
51
+ const sealed: Connect = function sealedConnect(this: net.Socket, ...args) {
52
+ const target = tcpTarget(args);
53
+ const refusal = target === undefined ? undefined : gate(target, 'CONNECT');
54
+ if (refusal === undefined) return Reflect.apply(original, this, args);
55
+ Reflect.set(this, 'connecting', true);
56
+ setImmediate(() => this.destroy(refusal));
57
+ return this;
58
+ };
59
+ Reflect.set(net.Socket.prototype, 'connect', sealed);
60
+ return () => {
61
+ Reflect.set(net.Socket.prototype, 'connect', original);
62
+ };
63
+ }
@@ -1,9 +1,16 @@
1
1
  // The socket half of the sealed network: `WebSocket` and `Bun.connect`, the two dials that are not
2
2
  // `fetch`. Only the patching lives here; WHETHER a dial may leave is `sealed-network.ts`'s one
3
3
  // gate, handed in, so fetch and sockets cannot disagree about the allow-list or the offline state.
4
+ // `node:*` TCP is `sealed-node-sockets.ts`, UDP `sealed-udp.ts`: installed and undone from here.
5
+
6
+ import { dialUrl, installNodeSocketSeal } from './sealed-node-sockets';
7
+ import { installUdpSeal } from './sealed-udp';
4
8
 
5
9
  /** A dial's verdict: the error to raise, or `undefined` to let it through to the real one. */
6
- export type SocketGate = (url: string, method: 'WEBSOCKET' | 'CONNECT') => Error | undefined;
10
+ export type SocketGate = (
11
+ url: string,
12
+ method: 'WEBSOCKET' | 'CONNECT' | 'SEND',
13
+ ) => Error | undefined;
7
14
 
8
15
  /** `Bun.connect`'s two option shapes, read structurally: TCP names a host, a unix socket a path. */
9
16
  interface ConnectOptions {
@@ -14,12 +21,6 @@ interface ConnectOptions {
14
21
 
15
22
  type Connect = (options: ConnectOptions) => Promise<unknown>;
16
23
 
17
- /** A dial target as a URL, so the gate parses one shape. IPv6 literals need their brackets. */
18
- const tcpUrl = (hostname: string, port: number | undefined): string => {
19
- const host = hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname;
20
- return `tcp://${host}:${port ?? 0}`;
21
- };
22
-
23
24
  /**
24
25
  * Patch both dials and return the uninstaller, which puts back exactly what was there — the same
25
26
  * originals, so `globalThis.WebSocket === original` holds again. Assigned through `Reflect.set`:
@@ -44,7 +45,7 @@ export function installSocketSeal(gate: SocketGate): () => void {
44
45
  // a path on this machine and is never egress.
45
46
  const sealedConnect: Connect = (options) => {
46
47
  if (options.unix === undefined && options.hostname !== undefined) {
47
- const refusal = gate(tcpUrl(options.hostname, options.port), 'CONNECT');
48
+ const refusal = gate(dialUrl(options.hostname, options.port), 'CONNECT');
48
49
  if (refusal !== undefined) return Promise.reject(refusal);
49
50
  }
50
51
  return originalConnect(options);
@@ -52,8 +53,12 @@ export function installSocketSeal(gate: SocketGate): () => void {
52
53
 
53
54
  Reflect.set(globalThis, 'WebSocket', SealedWebSocket);
54
55
  Reflect.set(Bun, 'connect', sealedConnect);
56
+ const restoreNode = installNodeSocketSeal(gate);
57
+ const restoreUdp = installUdpSeal(gate);
55
58
  return () => {
56
59
  Reflect.set(globalThis, 'WebSocket', OriginalWebSocket);
57
60
  Reflect.set(Bun, 'connect', originalConnect);
61
+ restoreNode();
62
+ restoreUdp();
58
63
  };
59
64
  }
@@ -0,0 +1,118 @@
1
+ // The UDP half of the socket seal: `Bun.udpSocket`, which `node:dgram` sends through too (measured).
2
+ // A connected socket is gated at `connect` and every send after; an unconnected one per datagram.
3
+ // A refusal surfaces as Bun's own UDP failures do: `send` throws, a `connect` rejects.
4
+
5
+ // why: Bun's `dgram.Socket#send` drops a throw when no callback is given (measured); patched below.
6
+ import dgram from 'node:dgram';
7
+ import { dialUrl } from './sealed-node-sockets';
8
+ import type { SocketGate } from './sealed-sockets';
9
+
10
+ type UdpSocketFactory = (options: unknown) => Promise<unknown>;
11
+ type Method = (...args: unknown[]) => unknown;
12
+
13
+ interface ConnectTarget {
14
+ readonly hostname?: unknown;
15
+ readonly port?: unknown;
16
+ }
17
+
18
+ /** The refusals this seal raised: the only errors the `dgram` patch re-emits. */
19
+ const refusals = new WeakSet<Error>();
20
+
21
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
22
+ typeof value === 'object' && value !== null;
23
+
24
+ /** The peer a `connect` option names, as the gate's URL; `undefined` for an unconnected socket. */
25
+ const peerOf = (options: unknown): string | undefined => {
26
+ const connect: unknown = isRecord(options) ? options['connect'] : undefined;
27
+ if (!isRecord(connect)) return undefined;
28
+ const target: ConnectTarget = connect;
29
+ return typeof target.hostname === 'string'
30
+ ? dialUrl(target.hostname, target.port, 'udp')
31
+ : undefined;
32
+ };
33
+
34
+ /**
35
+ * The peer a connected socket sends to, read off the socket at send time: `node:dgram`'s
36
+ * `connect()` re-points the native socket without `Bun.udpSocket` (measured), so a peer remembered
37
+ * from the options would miss it.
38
+ */
39
+ const remoteOf = (socket: object): string | undefined => {
40
+ const remote: unknown = Reflect.get(socket, 'remoteAddress');
41
+ if (!isRecord(remote) || typeof remote['address'] !== 'string') return undefined;
42
+ return dialUrl(remote['address'], remote['port'], 'udp');
43
+ };
44
+
45
+ /**
46
+ * Wrap one socket's two senders. Every datagram of a `sendMany` is judged before any leaves, so a
47
+ * refused batch sends nothing. A connected socket is judged per send: offline may have begun since.
48
+ */
49
+ const sealSends = (socket: object, gate: SocketGate): void => {
50
+ const send = Reflect.get(socket, 'send') as Method;
51
+ const sendMany = Reflect.get(socket, 'sendMany') as Method;
52
+ const judge = (target: string | undefined): void => {
53
+ // No target: an unconnected send without an address, which Bun refuses itself.
54
+ const refusal = target === undefined ? undefined : gate(target, 'SEND');
55
+ if (refusal === undefined) return;
56
+ refusals.add(refusal);
57
+ throw refusal;
58
+ };
59
+ Reflect.set(socket, 'send', (...args: unknown[]): unknown => {
60
+ judge(typeof args[2] === 'string' ? dialUrl(args[2], args[1], 'udp') : remoteOf(socket));
61
+ return Reflect.apply(send, socket, args);
62
+ });
63
+ Reflect.set(socket, 'sendMany', (packets: Iterable<unknown>): unknown => {
64
+ const list = [...packets];
65
+ const remote = remoteOf(socket);
66
+ if (remote !== undefined) judge(remote);
67
+ else {
68
+ for (let at = 0; at + 2 < list.length; at += 3) {
69
+ const address = list[at + 2];
70
+ if (typeof address === 'string') judge(dialUrl(address, list[at + 1], 'udp'));
71
+ }
72
+ }
73
+ return Reflect.apply(sendMany, socket, [list]);
74
+ });
75
+ };
76
+
77
+ /**
78
+ * Bun's `dgram` hands a failed send to the callback and DROPS it without one; Node emits `error`
79
+ * then. Without a callback, a refusal of ours is emitted as Node would, so it fails the test loudly.
80
+ */
81
+ const sealDgramSend = (): (() => void) => {
82
+ const send = Reflect.get(dgram.Socket.prototype, 'send') as Method;
83
+ Reflect.set(
84
+ dgram.Socket.prototype,
85
+ 'send',
86
+ function sealedSend(this: dgram.Socket, ...args: unknown[]) {
87
+ if (typeof args.at(-1) === 'function') return Reflect.apply(send, this, args);
88
+ const reemit = (error: unknown): void => {
89
+ if (error instanceof Error && refusals.has(error)) this.emit('error', error);
90
+ };
91
+ return Reflect.apply(send, this, [...args, reemit]);
92
+ },
93
+ );
94
+ return () => {
95
+ Reflect.set(dgram.Socket.prototype, 'send', send);
96
+ };
97
+ };
98
+
99
+ /** Patch `Bun.udpSocket` and return the uninstaller, which puts back exactly what was there. */
100
+ export function installUdpSeal(gate: SocketGate): () => void {
101
+ const restoreDgram = sealDgramSend();
102
+ const original = Reflect.get(Bun, 'udpSocket') as UdpSocketFactory;
103
+ const sealed: UdpSocketFactory = async (options) => {
104
+ const peer = peerOf(options);
105
+ if (peer !== undefined) {
106
+ const refusal = gate(peer, 'CONNECT');
107
+ if (refusal !== undefined) throw refusal;
108
+ }
109
+ const socket = await original(options);
110
+ if (isRecord(socket)) sealSends(socket, gate);
111
+ return socket;
112
+ };
113
+ Reflect.set(Bun, 'udpSocket', sealed);
114
+ return () => {
115
+ Reflect.set(Bun, 'udpSocket', original);
116
+ restoreDgram();
117
+ };
118
+ }
@@ -0,0 +1,76 @@
1
+ // The search index's `list` contract — what `reindex`'s sweep reads to find documents whose row is
2
+ // gone: every live document of one tenant, paged without a repeat or a gap, never a removed id and
3
+ // never another tenant's; every tenant's when the query names none.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { SearchListEntry, SearchListQuery, SearchScope } from '@ultimat3/entity/adapter';
7
+ import type { SearchIndexCheck, SearchIndexSubject } from './search-index-conformance-support';
8
+ import {
9
+ searchDoc as doc,
10
+ putSearchDocs,
11
+ SEARCH_TENANT_A,
12
+ SEARCH_TENANT_B,
13
+ searchDocId,
14
+ } from './search-index-conformance-support';
15
+
16
+ /** Every page of `query`, followed to its end; a page past the entries there are is a failure. */
17
+ export const listAll = async (
18
+ subject: SearchIndexSubject,
19
+ query: Omit<SearchListQuery, 'after' | 'entity'>,
20
+ ): Promise<readonly SearchListEntry[]> => {
21
+ const entries: SearchListEntry[] = [];
22
+ let after: string | null = null;
23
+ for (let pages = 0; pages < 20; pages += 1) {
24
+ const page = await subject.index.list({ ...query, entity: subject.entity, after });
25
+ expect(page.entries.length).toBeLessThanOrEqual(query.limit);
26
+ entries.push(...page.entries);
27
+ if (page.next === null) return entries;
28
+ after = page.next;
29
+ }
30
+ return expect.unreachable(`list never ended: ${entries.length} entries in 20 pages`);
31
+ };
32
+
33
+ const ids = (entries: readonly SearchListEntry[]) => entries.map((entry) => entry.id).sort();
34
+
35
+ export const SEARCH_INDEX_LIST_CHECKS: readonly SearchIndexCheck[] = [
36
+ {
37
+ name: "list pages one tenant's live documents: each once, none removed, none of another tenant",
38
+ async run(subject) {
39
+ await putSearchDocs(subject, [
40
+ doc(subject.entity, 1, 'zebra'),
41
+ doc(subject.entity, 2, 'quokka'),
42
+ doc(subject.entity, 3, 'lantern'),
43
+ doc(subject.entity, 4, 'harbour', { tenant: SEARCH_TENANT_B }),
44
+ ]);
45
+ const own: SearchScope = { entity: subject.entity, tenant: SEARCH_TENANT_A };
46
+ await subject.drop(own, [searchDocId(2)]);
47
+ await subject.index.remove(own, [searchDocId(2)], 2);
48
+ const listed = await listAll(subject, { tenant: SEARCH_TENANT_A, limit: 1 });
49
+ expect(ids(listed)).toEqual([searchDocId(1), searchDocId(3)]);
50
+ expect(listed.length).toBe(2);
51
+ for (const entry of listed) {
52
+ expect(entry.tenant).toBe(SEARCH_TENANT_A);
53
+ expect(Number.isFinite(entry.version)).toBe(true);
54
+ }
55
+ const other = await listAll(subject, { tenant: SEARCH_TENANT_B, limit: 10 });
56
+ expect(other.map((entry) => [entry.tenant, entry.id])).toEqual([
57
+ [SEARCH_TENANT_B, searchDocId(4)],
58
+ ]);
59
+ },
60
+ },
61
+ {
62
+ name: "list naming no tenant pages every tenant's documents, each with its own tenant",
63
+ async run(subject) {
64
+ await putSearchDocs(subject, [
65
+ doc(subject.entity, 1, 'zebra'),
66
+ doc(subject.entity, 2, 'zebra', { tenant: SEARCH_TENANT_B }),
67
+ ]);
68
+ const every = subject.everyTenant ?? ((read) => read());
69
+ const listed = await every(() => listAll(subject, { limit: 1 }));
70
+ expect(listed.map((entry) => [entry.tenant, entry.id]).sort()).toEqual([
71
+ [SEARCH_TENANT_A, searchDocId(1)],
72
+ [SEARCH_TENANT_B, searchDocId(2)],
73
+ ]);
74
+ },
75
+ },
76
+ ];
@@ -0,0 +1,69 @@
1
+ // What every search-index check shares: the subject, the suite's ids and tenants, one document
2
+ // builder (version 1 unless a check says otherwise), stored-then-indexed, and the sorted hit ids.
3
+
4
+ import { finiteOption } from '@ultimat3/core';
5
+ import type { SearchDocument, SearchIndex, SearchScope } from '@ultimat3/entity/adapter';
6
+
7
+ export interface SearchIndexSubject {
8
+ readonly index: SearchIndex;
9
+ /** A searchable entity with `title` and `body` searchable columns and a tenant column. */
10
+ readonly entity: string;
11
+ /** Writes (upserts) each document's source row; a no-op for an index holding its own copy. */
12
+ store(documents: readonly SearchDocument[]): Promise<void>;
13
+ /** Deletes the source rows of `ids` under `scope`; a no-op for an index holding its own copy. */
14
+ drop(scope: SearchScope, ids: readonly string[]): Promise<void>;
15
+ /**
16
+ * Runs a read that names no tenant — `list` across every tenant, as `reindex` sweeps. Absent, it
17
+ * runs as is; the built-in Postgres index needs the `crossTenant` capability around it.
18
+ */
19
+ everyTenant?<T>(read: () => Promise<T>): Promise<T>;
20
+ }
21
+
22
+ export interface SearchIndexCheck {
23
+ readonly name: string;
24
+ run(subject: SearchIndexSubject): Promise<void>;
25
+ }
26
+
27
+ export const SEARCH_TENANT_A = '00000000-0000-7000-8000-00000000a0a0';
28
+ export const SEARCH_TENANT_B = '00000000-0000-7000-8000-00000000b0b0';
29
+
30
+ /** A uuid-shaped id, so a uuid-keyed table holds the suite's rows. */
31
+ export const searchDocId = (n: number): string =>
32
+ `00000000-0000-7000-8000-${String(n).padStart(12, '0')}`;
33
+
34
+ export interface SearchDocOptions {
35
+ readonly body?: string;
36
+ readonly tenant?: string;
37
+ /** The row's version (its `onUpdateNow()` instant, epoch ms). Default 1. */
38
+ readonly version?: number;
39
+ }
40
+
41
+ /** One suite document: tenant A, version 1, unless the check says otherwise. */
42
+ export const searchDoc = (
43
+ entity: string,
44
+ n: number,
45
+ title: string,
46
+ options: SearchDocOptions = {},
47
+ ): SearchDocument => ({
48
+ entity,
49
+ tenant: options.tenant ?? SEARCH_TENANT_A,
50
+ id: searchDocId(n),
51
+ version: finiteOption('searchDoc', 'version', options.version ?? 1),
52
+ fields: options.body === undefined ? { title } : { title, body: options.body },
53
+ });
54
+
55
+ /** Stored then indexed — the order a write hook and `reindex` both keep. */
56
+ export const putSearchDocs = async (
57
+ subject: SearchIndexSubject,
58
+ documents: readonly SearchDocument[],
59
+ ) => {
60
+ await subject.store(documents);
61
+ await subject.index.index(documents);
62
+ };
63
+
64
+ export const searchIds = async (
65
+ subject: SearchIndexSubject,
66
+ term: string,
67
+ tenant = SEARCH_TENANT_A,
68
+ ) =>
69
+ (await subject.index.query({ entity: subject.entity, tenant, term })).map((hit) => hit.id).sort();
@@ -0,0 +1,66 @@
1
+ // The search index's ordering contract: keep only NEWER. A `reindex` batch that read a row at v1
2
+ // may call `index` after the write path indexed v2 or removed the row; the index must answer v2, or
3
+ // nothing. Each stale call is `index` ALONE, as when a batch's read raced a write, so the built-in
4
+ // Postgres index passes by construction.
5
+
6
+ // An EQUAL version is a replay: the writer, not the index, keeps versions strictly increasing per
7
+ // row (`@ultimat3/entity`'s `advanceVersion`). A `committed` document — the write path's — replaces
8
+ // a tombstone whatever its version: a key deleted and written again is live.
9
+
10
+ import { expect } from 'bun:test';
11
+ import type { SearchScope } from '@ultimat3/entity/adapter';
12
+ import type { SearchIndexCheck } from './search-index-conformance-support';
13
+ import {
14
+ searchDoc as doc,
15
+ putSearchDocs,
16
+ SEARCH_TENANT_A,
17
+ searchDocId,
18
+ searchIds,
19
+ } from './search-index-conformance-support';
20
+
21
+ export const SEARCH_INDEX_VERSION_CHECKS: readonly SearchIndexCheck[] = [
22
+ {
23
+ name: 'a committed document replaces a newer tombstone: a key deleted and written again is found',
24
+ async run(subject) {
25
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'zebra', { version: 10 })]);
26
+ const own: SearchScope = { entity: subject.entity, tenant: SEARCH_TENANT_A };
27
+ await subject.drop(own, [searchDocId(1)]);
28
+ await subject.index.remove(own, [searchDocId(1)], 30);
29
+ const again = doc(subject.entity, 1, 'quokka', { version: 20 });
30
+ await subject.store([again]);
31
+ await subject.index.index([again], { committed: true });
32
+ expect(await searchIds(subject, 'quokka')).toEqual([searchDocId(1)]);
33
+ },
34
+ },
35
+ {
36
+ name: 'an older version indexed after a newer one leaves the newer one',
37
+ async run(subject) {
38
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'lantern', { version: 20 })]);
39
+ await subject.index.index([doc(subject.entity, 1, 'zebra', { version: 10 })]);
40
+ expect(await searchIds(subject, 'zebra')).toEqual([]);
41
+ expect(await searchIds(subject, 'lantern')).toEqual([searchDocId(1)]);
42
+ },
43
+ },
44
+ {
45
+ name: 'a version indexed after the id was removed at a later version stays removed',
46
+ async run(subject) {
47
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'zebra', { version: 10 })]);
48
+ const own: SearchScope = { entity: subject.entity, tenant: SEARCH_TENANT_A };
49
+ await subject.drop(own, [searchDocId(1)]);
50
+ await subject.index.remove(own, [searchDocId(1)], 30);
51
+ await subject.index.index([doc(subject.entity, 1, 'zebra', { version: 20 })]);
52
+ expect(await searchIds(subject, 'zebra')).toEqual([]);
53
+ },
54
+ },
55
+ {
56
+ name: 'an id written again after its removal, at a newer version, is found',
57
+ async run(subject) {
58
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'zebra', { version: 10 })]);
59
+ const own: SearchScope = { entity: subject.entity, tenant: SEARCH_TENANT_A };
60
+ await subject.drop(own, [searchDocId(1)]);
61
+ await subject.index.remove(own, [searchDocId(1)], 30);
62
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'quokka', { version: 40 })]);
63
+ expect(await searchIds(subject, 'quokka')).toEqual([searchDocId(1)]);
64
+ },
65
+ },
66
+ ];