@tealbrick/provider-transport 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tealbrick contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Independently authored Teal Brick transport extracted from @tealbrick/voice
2
+ for reuse by Voice and Vision. No Kybernesis implementation is copied.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @tealbrick/provider-transport
2
+
3
+ Shared trusted-runtime transport for Teal Brick Voice and Vision. Node 24+, no harness dependency.
4
+
5
+ Exports exact endpoint/credential policy enforcement, credential resolution scoped to organization and agent, redirect refusal, timeout validation, abort-aware waits and bounded stream reads. It performs no user authentication: domain handlers must authenticate and authorize before calling `upstream`.
6
+
7
+ Use `createProviderTransport({binding,endpoints,resolveCredential,errorPrefix})`, then `upstream({url,credentialRef},body,signal,contentType)`. HTTPS is required except explicitly approved loopback HTTP. Anonymous access must be explicitly approved. Never source endpoint policies or the credential resolver from an untrusted request. No retries or response persistence are performed.
8
+
9
+ This is portfolio support code, not a separate miniapp. Domain protocols remain owned by their packages.
@@ -0,0 +1,40 @@
1
+ export interface EndpointPolicy {
2
+ url: string;
3
+ credentialRefs?: readonly string[];
4
+ allowAnonymous?: boolean;
5
+ allowLoopback?: boolean;
6
+ }
7
+ export interface ProviderEndpoint {
8
+ url: string;
9
+ credentialRef?: string;
10
+ }
11
+ export interface ProviderOptions {
12
+ binding: {
13
+ org: string;
14
+ agent: string;
15
+ };
16
+ endpoints: readonly EndpointPolicy[];
17
+ resolveCredential?: (binding: {
18
+ reference: string;
19
+ url: string;
20
+ org: string;
21
+ agent: string;
22
+ }) => string | Promise<string>;
23
+ fetch?: typeof fetch;
24
+ /** Stable public error-code namespace, not provider exception text. */
25
+ errorPrefix?: string;
26
+ }
27
+ export declare class ProviderFailure extends Error {
28
+ readonly status: number;
29
+ readonly code: string;
30
+ constructor(status: number, code: string);
31
+ }
32
+ export declare function endpointUrl(value: unknown, allowLoopback?: boolean): string;
33
+ export declare function providerTimeout(value?: number): number;
34
+ export declare function boundedWait<T>(pending: Promise<T>, signal: AbortSignal): Promise<T>;
35
+ export declare function bytes(body: ReadableStream<Uint8Array> | null, limit: number, signal: AbortSignal, tooLargeCode?: string): Promise<Uint8Array<ArrayBuffer>>;
36
+ /** Shared transport only. Callers must authenticate and authorize before calling upstream. */
37
+ export declare function createProviderTransport(options: ProviderOptions): {
38
+ policy: (endpoint: ProviderEndpoint) => string;
39
+ upstream: (endpoint: ProviderEndpoint, body: BodyInit, signal: AbortSignal, contentType?: string) => Promise<Response>;
40
+ };
package/dist/index.js ADDED
@@ -0,0 +1,128 @@
1
+ export class ProviderFailure extends Error {
2
+ status;
3
+ code;
4
+ constructor(status, code) {
5
+ super(code);
6
+ this.status = status;
7
+ this.code = code;
8
+ }
9
+ }
10
+ export function endpointUrl(value, allowLoopback = false) {
11
+ if (typeof value !== "string" || !value.trim() || value.length > 2048 || /[\u0000-\u0020\u007f]/.test(value))
12
+ throw new Error("invalid_provider_endpoint");
13
+ const url = new URL(value);
14
+ const local = allowLoopback && url.protocol === "http:" && ["127.0.0.1", "[::1]", "localhost"].includes(url.hostname);
15
+ if ((!local && url.protocol !== "https:") || url.username || url.password || url.search || url.hash)
16
+ throw new Error("invalid_provider_endpoint");
17
+ return url.href;
18
+ }
19
+ export function providerTimeout(value = 30000) {
20
+ if (!Number.isInteger(value) || value < 1 || value > 120000)
21
+ throw new Error("invalid_provider_timeout");
22
+ return value;
23
+ }
24
+ export async function boundedWait(pending, signal) {
25
+ if (signal.aborted) {
26
+ void pending.catch(() => { });
27
+ throw signal.reason;
28
+ }
29
+ let abort = () => { };
30
+ const cancelled = new Promise((_, reject) => {
31
+ abort = () => reject(signal.reason);
32
+ signal.addEventListener("abort", abort, { once: true });
33
+ });
34
+ try {
35
+ return await Promise.race([pending, cancelled]);
36
+ }
37
+ finally {
38
+ signal.removeEventListener("abort", abort);
39
+ }
40
+ }
41
+ export async function bytes(body, limit, signal, tooLargeCode = "provider_payload_too_large") {
42
+ if (!Number.isSafeInteger(limit) || limit < 1)
43
+ throw new Error("invalid_provider_size_limit");
44
+ if (!body) {
45
+ signal.throwIfAborted();
46
+ return new Uint8Array();
47
+ }
48
+ const reader = body.getReader();
49
+ let size = 0;
50
+ const chunks = [];
51
+ const cancel = () => { void reader.cancel().catch(() => { }); };
52
+ signal.addEventListener("abort", cancel, { once: true });
53
+ try {
54
+ signal.throwIfAborted();
55
+ for (;;) {
56
+ const next = await reader.read();
57
+ signal.throwIfAborted();
58
+ if (next.done)
59
+ break;
60
+ size += next.value.byteLength;
61
+ if (size > limit) {
62
+ cancel();
63
+ throw new ProviderFailure(413, tooLargeCode);
64
+ }
65
+ chunks.push(next.value);
66
+ }
67
+ const result = new Uint8Array(size);
68
+ let offset = 0;
69
+ for (const chunk of chunks) {
70
+ result.set(chunk, offset);
71
+ offset += chunk.length;
72
+ }
73
+ return result;
74
+ }
75
+ finally {
76
+ signal.removeEventListener("abort", cancel);
77
+ reader.releaseLock();
78
+ }
79
+ }
80
+ /** Shared transport only. Callers must authenticate and authorize before calling upstream. */
81
+ export function createProviderTransport(options) {
82
+ const binding = Object.freeze({ ...options.binding });
83
+ const policies = options.endpoints.map(p => ({ ...p, url: endpointUrl(p.url, p.allowLoopback), credentialRefs: [...(p.credentialRefs ?? [])] }));
84
+ if (new Set(policies.map(p => p.url)).size !== policies.length)
85
+ throw new Error("duplicate_provider_endpoint_policy");
86
+ const prefix = options.errorPrefix ?? "provider";
87
+ if (!/^[a-z][a-z0-9_]{0,40}$/.test(prefix))
88
+ throw new Error("invalid_provider_error_prefix");
89
+ function fail(status, suffix) { throw new ProviderFailure(status, `${prefix}_${suffix}`); }
90
+ function policy(endpoint) {
91
+ const url = endpointUrl(endpoint.url, true);
92
+ const found = policies.find(p => p.url === url);
93
+ if (!found || (endpoint.credentialRef ? !found.credentialRefs.includes(endpoint.credentialRef) : !found.allowAnonymous))
94
+ fail(503, "endpoint_not_approved");
95
+ return url;
96
+ }
97
+ async function upstream(endpoint, body, signal, contentType) {
98
+ const url = policy(endpoint);
99
+ let token;
100
+ if (endpoint.credentialRef) {
101
+ try {
102
+ token = await boundedWait(Promise.resolve(options.resolveCredential?.({ ...binding, reference: endpoint.credentialRef, url })), signal);
103
+ }
104
+ catch {
105
+ fail(503, "credential_unavailable");
106
+ }
107
+ if (!token || /[\s\u0000-\u001f\u007f]/.test(token))
108
+ fail(503, "credential_unavailable");
109
+ }
110
+ let response;
111
+ try {
112
+ signal.throwIfAborted();
113
+ response = await boundedWait((options.fetch ?? fetch)(url, {
114
+ method: "POST", redirect: "error", signal,
115
+ headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(contentType ? { "content-type": contentType } : {}) }, body,
116
+ }), signal);
117
+ }
118
+ catch {
119
+ return fail(signal.aborted ? 504 : 502, signal.aborted ? "timeout_or_cancelled" : "provider_unavailable");
120
+ }
121
+ if (!response.ok) {
122
+ void response.body?.cancel().catch(() => { });
123
+ fail(502, "provider_rejected");
124
+ }
125
+ return response;
126
+ }
127
+ return { policy, upstream };
128
+ }
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@tealbrick/provider-transport",
3
+ "version": "0.1.0",
4
+ "description": "Shared bounded provider transport and endpoint credential policy for Teal Brick adapters",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "files": [
8
+ "dist",
9
+ "README.md",
10
+ "LICENSE",
11
+ "NOTICE"
12
+ ],
13
+ "engines": {
14
+ "node": ">=24"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json",
24
+ "test": "node --test test/*.test.mjs"
25
+ },
26
+ "devDependencies": {
27
+ "typescript": "^5.9.3",
28
+ "@types/node": "^24.0.0"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "registry": "https://registry.npmjs.org"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/Doppelabs/tealbrick-packages.git",
37
+ "directory": "packages/provider-transport"
38
+ }
39
+ }