tinfoil 1.4.0 → 2.0.0-rc.1

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 (206) hide show
  1. package/README.md +33 -33
  2. package/dist/ai-sdk.d.ts +12 -0
  3. package/dist/ai-sdk.d.ts.map +1 -0
  4. package/dist/ai-sdk.js +12 -0
  5. package/dist/ai-sdk.js.map +1 -0
  6. package/dist/enclave-client.d.ts +64 -0
  7. package/dist/enclave-client.d.ts.map +1 -0
  8. package/dist/enclave-client.js +196 -0
  9. package/dist/enclave-client.js.map +1 -0
  10. package/dist/errors.d.ts +68 -0
  11. package/dist/errors.d.ts.map +1 -0
  12. package/dist/errors.js +84 -0
  13. package/dist/errors.js.map +1 -0
  14. package/dist/gateway-client.d.ts +71 -0
  15. package/dist/gateway-client.d.ts.map +1 -0
  16. package/dist/gateway-client.js +145 -0
  17. package/dist/gateway-client.js.map +1 -0
  18. package/dist/index.browser.d.ts +16 -12
  19. package/dist/index.browser.d.ts.map +1 -1
  20. package/dist/index.browser.js +16 -12
  21. package/dist/index.browser.js.map +1 -1
  22. package/dist/index.d.ts +2 -12
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -11
  25. package/dist/index.js.map +1 -1
  26. package/dist/internal/ai-sdk.d.ts +58 -0
  27. package/dist/internal/ai-sdk.d.ts.map +1 -0
  28. package/dist/internal/ai-sdk.js +73 -0
  29. package/dist/internal/ai-sdk.js.map +1 -0
  30. package/dist/internal/body.js +69 -0
  31. package/dist/internal/body.js.map +1 -0
  32. package/dist/internal/cachesecret-store.browser.js +5 -0
  33. package/dist/internal/cachesecret-store.browser.js.map +1 -0
  34. package/dist/internal/cachesecret-store.js +137 -0
  35. package/dist/internal/cachesecret-store.js.map +1 -0
  36. package/dist/internal/cachesecret.js +310 -0
  37. package/dist/internal/cachesecret.js.map +1 -0
  38. package/dist/internal/credential.js +35 -0
  39. package/dist/internal/credential.js.map +1 -0
  40. package/dist/internal/dispose.d.ts +18 -0
  41. package/dist/internal/dispose.d.ts.map +1 -0
  42. package/dist/internal/dispose.js +20 -0
  43. package/dist/internal/dispose.js.map +1 -0
  44. package/dist/internal/enclave.js +214 -0
  45. package/dist/internal/enclave.js.map +1 -0
  46. package/dist/internal/fetch.js +136 -0
  47. package/dist/internal/fetch.js.map +1 -0
  48. package/dist/internal/gateway/catalog.js +192 -0
  49. package/dist/internal/gateway/catalog.js.map +1 -0
  50. package/dist/internal/gateway/policy.js +114 -0
  51. package/dist/internal/gateway/policy.js.map +1 -0
  52. package/dist/internal/gateway/prepare.js +289 -0
  53. package/dist/internal/gateway/prepare.js.map +1 -0
  54. package/dist/internal/gateway/transport.js +262 -0
  55. package/dist/internal/gateway/transport.js.map +1 -0
  56. package/dist/internal/platform.browser.js +27 -0
  57. package/dist/internal/platform.browser.js.map +1 -0
  58. package/dist/internal/platform.js +86 -0
  59. package/dist/internal/platform.js.map +1 -0
  60. package/dist/internal/router.js +82 -0
  61. package/dist/internal/router.js.map +1 -0
  62. package/dist/internal/transport/base-url.js +78 -0
  63. package/dist/internal/transport/base-url.js.map +1 -0
  64. package/dist/internal/transport/ehbp.js +183 -0
  65. package/dist/internal/transport/ehbp.js.map +1 -0
  66. package/dist/internal/transport/header.js +35 -0
  67. package/dist/internal/transport/header.js.map +1 -0
  68. package/dist/internal/transport/origin.js +75 -0
  69. package/dist/internal/transport/origin.js.map +1 -0
  70. package/dist/internal/transport/pin-errors.js +24 -0
  71. package/dist/internal/transport/pin-errors.js.map +1 -0
  72. package/dist/internal/transport/pin.js +31 -0
  73. package/dist/internal/transport/pin.js.map +1 -0
  74. package/dist/internal/transport/replay.js +60 -0
  75. package/dist/internal/transport/replay.js.map +1 -0
  76. package/dist/internal/transport/tls.browser.js +10 -0
  77. package/dist/internal/transport/tls.browser.js.map +1 -0
  78. package/dist/internal/transport/tls.js +189 -0
  79. package/dist/internal/transport/tls.js.map +1 -0
  80. package/dist/internal/transport/transport.js +171 -0
  81. package/dist/internal/transport/transport.js.map +1 -0
  82. package/dist/internal/transport/ws.browser.js +20 -0
  83. package/dist/internal/transport/ws.browser.js.map +1 -0
  84. package/dist/internal/transport/ws.js +220 -0
  85. package/dist/internal/transport/ws.js.map +1 -0
  86. package/dist/internal/unsafe-client.d.ts +49 -0
  87. package/dist/internal/unsafe-client.d.ts.map +1 -0
  88. package/dist/internal/unsafe-client.js +159 -0
  89. package/dist/internal/unsafe-client.js.map +1 -0
  90. package/dist/internal/verified.js +134 -0
  91. package/dist/internal/verified.js.map +1 -0
  92. package/dist/internal/websocket.js +92 -0
  93. package/dist/internal/websocket.js.map +1 -0
  94. package/dist/openai-client.d.ts +140 -0
  95. package/dist/openai-client.d.ts.map +1 -0
  96. package/dist/openai-client.js +279 -0
  97. package/dist/openai-client.js.map +1 -0
  98. package/dist/options.d.ts +293 -0
  99. package/dist/options.d.ts.map +1 -0
  100. package/dist/options.js +2 -0
  101. package/dist/options.js.map +1 -0
  102. package/dist/realtime.browser.js +4 -4
  103. package/dist/realtime.browser.js.map +1 -1
  104. package/dist/realtime.d.ts +17 -11
  105. package/dist/realtime.d.ts.map +1 -1
  106. package/dist/realtime.js +22 -9
  107. package/dist/realtime.js.map +1 -1
  108. package/dist/router-client.d.ts +47 -0
  109. package/dist/router-client.d.ts.map +1 -0
  110. package/dist/router-client.js +123 -0
  111. package/dist/router-client.js.map +1 -0
  112. package/dist/session-recovery.d.ts +25 -0
  113. package/dist/session-recovery.d.ts.map +1 -0
  114. package/dist/session-recovery.js +32 -0
  115. package/dist/session-recovery.js.map +1 -0
  116. package/dist/surface.d.ts +17 -0
  117. package/dist/surface.d.ts.map +1 -0
  118. package/dist/surface.js +17 -0
  119. package/dist/surface.js.map +1 -0
  120. package/dist/unsafe.d.ts +9 -2
  121. package/dist/unsafe.d.ts.map +1 -1
  122. package/dist/unsafe.js +9 -2
  123. package/dist/unsafe.js.map +1 -1
  124. package/dist/version.d.ts +1 -1
  125. package/dist/version.d.ts.map +1 -1
  126. package/dist/version.js +1 -1
  127. package/dist/version.js.map +1 -1
  128. package/dist/websocket.d.ts +31 -0
  129. package/dist/websocket.d.ts.map +1 -0
  130. package/dist/websocket.js +28 -0
  131. package/dist/websocket.js.map +1 -0
  132. package/package.json +18 -17
  133. package/dist/ai-sdk-provider.d.ts +0 -54
  134. package/dist/ai-sdk-provider.d.ts.map +0 -1
  135. package/dist/ai-sdk-provider.js +0 -59
  136. package/dist/ai-sdk-provider.js.map +0 -1
  137. package/dist/atc.d.ts +0 -23
  138. package/dist/atc.d.ts.map +0 -1
  139. package/dist/atc.js +0 -70
  140. package/dist/atc.js.map +0 -1
  141. package/dist/config.d.ts +0 -14
  142. package/dist/config.d.ts.map +0 -1
  143. package/dist/config.js +0 -14
  144. package/dist/config.js.map +0 -1
  145. package/dist/encrypted-body-fetch.d.ts +0 -34
  146. package/dist/encrypted-body-fetch.d.ts.map +0 -1
  147. package/dist/encrypted-body-fetch.js +0 -200
  148. package/dist/encrypted-body-fetch.js.map +0 -1
  149. package/dist/env.d.ts +0 -8
  150. package/dist/env.d.ts.map +0 -1
  151. package/dist/env.js +0 -43
  152. package/dist/env.js.map +0 -1
  153. package/dist/pinned-tls-fetch.browser.d.ts +0 -2
  154. package/dist/pinned-tls-fetch.browser.d.ts.map +0 -1
  155. package/dist/pinned-tls-fetch.browser.js +0 -13
  156. package/dist/pinned-tls-fetch.browser.js.map +0 -1
  157. package/dist/pinned-tls-fetch.d.ts +0 -3
  158. package/dist/pinned-tls-fetch.d.ts.map +0 -1
  159. package/dist/pinned-tls-fetch.js +0 -159
  160. package/dist/pinned-tls-fetch.js.map +0 -1
  161. package/dist/pinned-ws.browser.d.ts +0 -15
  162. package/dist/pinned-ws.browser.d.ts.map +0 -1
  163. package/dist/pinned-ws.browser.js +0 -10
  164. package/dist/pinned-ws.browser.js.map +0 -1
  165. package/dist/pinned-ws.d.ts +0 -31
  166. package/dist/pinned-ws.d.ts.map +0 -1
  167. package/dist/pinned-ws.js +0 -84
  168. package/dist/pinned-ws.js.map +0 -1
  169. package/dist/realtime.browser.d.ts +0 -16
  170. package/dist/realtime.browser.d.ts.map +0 -1
  171. package/dist/secure-client.d.ts +0 -242
  172. package/dist/secure-client.d.ts.map +0 -1
  173. package/dist/secure-client.js +0 -383
  174. package/dist/secure-client.js.map +0 -1
  175. package/dist/secure-fetch.d.ts +0 -16
  176. package/dist/secure-fetch.d.ts.map +0 -1
  177. package/dist/secure-fetch.js +0 -44
  178. package/dist/secure-fetch.js.map +0 -1
  179. package/dist/tinfoil-ai.d.ts +0 -179
  180. package/dist/tinfoil-ai.d.ts.map +0 -1
  181. package/dist/tinfoil-ai.js +0 -200
  182. package/dist/tinfoil-ai.js.map +0 -1
  183. package/dist/unsafe.browser.d.ts +0 -3
  184. package/dist/unsafe.browser.d.ts.map +0 -1
  185. package/dist/unsafe.browser.js +0 -3
  186. package/dist/unsafe.browser.js.map +0 -1
  187. package/dist/unverified-client.d.ts +0 -19
  188. package/dist/unverified-client.d.ts.map +0 -1
  189. package/dist/unverified-client.js +0 -69
  190. package/dist/unverified-client.js.map +0 -1
  191. package/dist/user-cache-secret-store.browser.d.ts +0 -7
  192. package/dist/user-cache-secret-store.browser.d.ts.map +0 -1
  193. package/dist/user-cache-secret-store.browser.js +0 -9
  194. package/dist/user-cache-secret-store.browser.js.map +0 -1
  195. package/dist/user-cache-secret-store.d.ts +0 -19
  196. package/dist/user-cache-secret-store.d.ts.map +0 -1
  197. package/dist/user-cache-secret-store.js +0 -160
  198. package/dist/user-cache-secret-store.js.map +0 -1
  199. package/dist/user-cache-secret.d.ts +0 -62
  200. package/dist/user-cache-secret.d.ts.map +0 -1
  201. package/dist/user-cache-secret.js +0 -400
  202. package/dist/user-cache-secret.js.map +0 -1
  203. package/dist/verifier.d.ts +0 -2
  204. package/dist/verifier.d.ts.map +0 -1
  205. package/dist/verifier.js +0 -2
  206. package/dist/verifier.js.map +0 -1
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![NPM version](https://img.shields.io/npm/v/tinfoil.svg)](https://npmjs.org/package/tinfoil)
5
5
  [![Documentation](https://img.shields.io/badge/docs-tinfoil.sh-blue)](https://docs.tinfoil.sh/sdk/javascript-sdk)
6
6
 
7
- A TypeScript client for verifiably private AI inference with Tinfoil. It wraps the [OpenAI Node client](https://github.com/openai/openai-node) with the same API, and before sending any request it verifies the enclave's attestation and encrypts the request body to the attested key using [EHBP](https://docs.tinfoil.sh/resources/ehbp), so only the verified enclave can read it. Works in Node (22.23.4+, 24.22.1+, or 26.12.1+), browsers, Electron, and Bun, and supports the [Vercel AI SDK](https://sdk.vercel.ai/).
7
+ A TypeScript client for verifiably private AI inference with Tinfoil. It wraps the [OpenAI Node client](https://github.com/openai/openai-node) with the same API. A client verifies the enclave's attestation before it is returned, and every request it sends is bound to the verified enclave: on Node and Bun the TLS connection is pinned to the attested key, and in browsers the request body is encrypted to the attested key with [EHBP](https://docs.tinfoil.sh/resources/ehbp), so only the verified enclave can read it. Works in Node (22.23.4+, 24.22.1+, or 26.12.1+), browsers, Electron, and Bun (1.4.0+ for the pinned TLS connection; see below), and supports the [Vercel AI SDK](https://sdk.vercel.ai/).
8
8
 
9
9
  ## Installation
10
10
 
@@ -15,57 +15,57 @@ npm install tinfoil
15
15
  ## Quick Start
16
16
 
17
17
  ```typescript
18
- import { TinfoilAI } from "tinfoil";
18
+ import { createClient } from "tinfoil";
19
19
 
20
- const client = new TinfoilAI({
21
- apiKey: "<YOUR_API_KEY>", // or set TINFOIL_API_KEY
22
- });
20
+ // Discovers Tinfoil's inference router and verifies it before returning.
21
+ const client = await createClient({ apiKey: "<YOUR_API_KEY>" });
23
22
 
24
- // Enclave verification and encryption happen automatically.
25
23
  const completion = await client.chat.completions.create({
26
24
  messages: [{ role: "user", content: "Hello!" }],
27
25
  model: "gpt-oss-120b", // see https://docs.tinfoil.sh/models/chat
28
26
  });
29
27
  ```
30
28
 
31
- Never put `apiKey` in browser code: route browser requests through a [proxy server](https://docs.tinfoil.sh/guides/proxy-server) that adds the key, and authenticate the browser with `bearerToken`. Multi-user services must scope prompt caches to each end user with `userCacheSecret` or a per-request `user_cache_secret`; see [Prompt caching](https://docs.tinfoil.sh/sdk/prompt-caching).
29
+ Every attested client is an async factory: one that exists has been verified, and it verifies again by itself when the verification expires or the enclave's key changes. `createClient` takes the OpenAI client's own options (except `baseURL` and `fetch`, which the attested transport owns) plus `bearerToken`, and returns a client with the same API as `new OpenAI(...)`. Anything about the route itself lives on the configurable clients: `RouterOpenAIClient.create(routerOptions, openaiOptions)` for the discovered router with a proxy, transport mode, verifier or cache-secret setting; `EnclaveOpenAIClient.create(host, repo, options, openaiOptions)` for one enclave instead of the router; and `RouterHTTPClient.create()` / `EnclaveHTTPClient.create(host, repo)` for a verified `fetch` to any HTTP API. An HTTP client's `close()` releases its pooled connections and refuses further use, and both kinds of client support `await using` (an OpenAI client closes the HTTP client under it).
30
+
31
+ Never put `apiKey` in browser code: the OpenAI clients and the AI SDK provider refuse it outside Node and Bun, `dangerouslyAllowBrowser` or not. Route browser requests through a [proxy server](https://docs.tinfoil.sh/guides/proxy-server) that adds the key, and authenticate the browser with a token of your own:
32
+
33
+ ```typescript
34
+ import { RouterOpenAIClient } from "tinfoil";
35
+
36
+ const client = await RouterOpenAIClient.create({ baseURL: "https://proxy.example.com/v1/" }, { bearerToken: "<SESSION_TOKEN>" });
37
+ ```
38
+
39
+ Browsers use the EHBP transport, the default and the only one available there. The package's type declarations are shared with the Node build, so a browser project type-checks a few names that throw a `ConfigurationError` when called: `createWebSocket` and `pinnedWebSocketOptions` (a verified WebSocket pins the server certificate, which browsers don't expose to scripts), `createRealtimeWebSocket` (a realtime session runs over such a WebSocket), and `transportMode: "tls"` (the `"tls"` transport mode pins the server certificate too; `"ehbp"` seals request and response bodies to the enclave's key instead).
40
+
41
+ Bun pins the TLS connection from Bun 1.4.0, the first release whose `fetch` checks the server certificate before it sends the request; on an older Bun the default transport mode is `"ehbp"` and `transportMode: "tls"` is refused with a `ConfigurationError`. `createWebSocket` needs Bun 1.4.4 or later, the first release whose WebSocket runs the certificate check at all, and is refused on an older Bun before anything is sent. `pinnedWebSocketOptions` and `createRealtimeWebSocket` hand settings to the `ws` library, which Bun replaces with its own WebSocket, so they are available on Node only.
42
+
43
+ The request body is still encrypted to the verified enclave's key; the proxy only forwards it. `baseURL` is the API root, as for `new OpenAI({ baseURL })`: the client appends `chat/completions` and the other OpenAI paths to it, so a proxy that forwards paths as they are takes the enclave's `/v1/`. Multi-user services must scope prompt caches to each end user with `userCacheSecret` or a per-request `user_cache_secret`; see [Prompt caching](https://docs.tinfoil.sh/sdk/prompt-caching).
32
44
 
33
- ## Custom HTTP transport
45
+ ### Custom network transport
34
46
 
35
- `SecureClient` accepts a fetch-compatible network implementation for native HTTP
36
- bridges (such as Tauri) or trusted relays:
47
+ `RouterHTTPClient.create`, `EnclaveHTTPClient.create` and `GatewayHTTPClient.create`, and the route options of the OpenAI clients over them (`RouterOpenAIClient.create(routerOptions, openaiOptions)` and the enclave and gateway equivalents), take a `fetch` option: a fetch-compatible network implementation that carries their requests in the EHBP transport mode, for a native HTTP bridge (such as Tauri's) or a trusted relay. The AI SDK provider's `createTinfoil` takes it too. `createClient` takes only the OpenAI options, so it doesn't take it.
37
48
 
38
49
  ```typescript
39
- import { SecureClient } from "tinfoil";
50
+ import { RouterHTTPClient } from "tinfoil";
40
51
 
41
- const client = new SecureClient({
42
- fetch: nativeFetch, // Your fetch-compatible native HTTP adapter
43
- });
44
- await client.ready();
45
- const response = await client.fetch("/v1/chat/completions", {
46
- method: "POST",
47
- headers: { "Content-Type": "application/json" },
48
- body: JSON.stringify({ model: "gpt-oss-120b", messages: [] }),
49
- });
52
+ // nativeFetch: a fetch-compatible function that sends the sealed requests.
53
+ const client = await RouterHTTPClient.create({ fetch: nativeFetch, transportMode: "ehbp" }); // "ehbp" is already the default in browsers
50
54
  ```
51
55
 
52
- The SDK verifies the enclave and encrypts request bodies before invoking this
53
- callback, then decrypts responses as usual. Attestation requests continue using
54
- the existing transport. This option is only supported in EHBP mode; combining it
55
- with `transport: "tls"` throws rather than bypassing certificate pinning.
56
+ The client verifies the enclave and seals each request body before calling it, and opens the response that it returns; attestation documents, the router list and the gateway catalog are still fetched with the runtime's fetch. The function must return a standard `Response` and honour the request's signal, and a relay must pass the sealed body and the protocol headers through unchanged. The method, URL and headers aren't sealed, so a relay sees the API key: use only a relay that you trust, over HTTPS. A request without a body passes through it unsealed, as the mode leaves it. The option is refused with `transportMode: "tls"`, which pins the connection itself.
57
+
58
+ ## Errors
56
59
 
57
- The adapter must return a standard `Response` and honor cancellation and redirect
58
- policy. If it routes requests through a relay, it must preserve encrypted bodies
59
- and protocol headers. Only use trusted relays: EHBP encrypts bodies, not headers
60
- such as authorization. Use HTTPS for remote endpoints and relay connections to
61
- protect those headers in transit; the SDK retains its existing HTTP(S) URL
62
- policy. Bodyless requests retain existing EHBP behavior.
60
+ The clients throw three error classes, each a `TinfoilError` with a `category`, and with the underlying failure as `cause` when there is one: `ConfigurationError` (invalid options, or a closed client), `NetworkError` (the enclave or its attestation couldn't be reached) and `AttestationError` (the enclave couldn't be trusted: when verification rejected the document, `cause` is the verifier's `VerificationError` whose `layer` names the rejecting check; a key that doesn't match the attested one, or one the enclave no longer holds after rotation, is an `AttestationError` too). Switch on `category` (`"configuration"`, `"network"` or `"attestation"`), which is the stable discriminant; each error's `name` matches its class, for logs and stack traces. The factories, `ensureVerified()`, `reverify()` and an HTTP client's `fetch` throw them directly. A call through the OpenAI API surface, such as `client.chat.completions.create(...)`, goes through the OpenAI client's request loop, which catches whatever the attested `fetch` throws, retries the request `maxRetries` times (2 by default, with backoff; only a request whose body is a stream isn't retried) and then throws `APIConnectionError` with the client's error as its `cause`. So an enclave that fails to verify again on a request surfaces as an `APIConnectionError` whose `cause` is an `AttestationError`, after three verification attempts; pass `maxRetries: 0` to the client or the request to see the first failure. Errors from the API itself (`AuthenticationError`, `RateLimitError` and the rest) keep the OpenAI client's types; all of them are re-exported from the package root.
63
61
 
64
62
  ## Documentation
65
63
 
66
- - [JavaScript SDK documentation](https://docs.tinfoil.sh/sdk/javascript-sdk), including `SecureClient` and verification documents. Realtime transcription over WebSockets is covered in [Processing audio](https://docs.tinfoil.sh/guides/processing-audio).
67
- - [Examples](packages/tinfoil/examples/), including the Vercel AI SDK on the server and in React.
68
- - The resources `TinfoilAI` exposes, such as `chat`, `responses`, `embeddings`, and `audio`, keep the OpenAI methods and types; see the [OpenAI Node client documentation](https://github.com/openai/openai-node).
64
+ - [JavaScript SDK documentation](https://docs.tinfoil.sh/sdk/javascript-sdk). Realtime transcription over WebSockets is covered in [Processing audio](https://docs.tinfoil.sh/guides/processing-audio): `createRealtimeWebSocket(client, { model })` opens a session over a WebSocket pinned to the attested key.
65
+ - [Examples](packages/tinfoil/examples/), including the Vercel AI SDK provider (`createTinfoil` from `tinfoil/ai-sdk`) on the server and in React.
66
+ - [Migrating from 1.x to 2.0](https://github.com/tinfoilsh/tinfoil-js/blob/main/MIGRATION.md).
67
+ - The resources a client exposes, such as `chat`, `responses`, `embeddings`, and `audio`, keep the OpenAI methods and types; see the [OpenAI Node client documentation](https://github.com/openai/openai-node).
68
+ - `tinfoil/unsafe` exports `UnverifiedClient`, which skips attestation: for development against a local server only, never for real data.
69
69
 
70
70
  ## Development
71
71
 
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The `tinfoil/ai-sdk` entry: a provider for the Vercel AI SDK over an
3
+ * attested client. It is its own entry so the AI SDK stays out of bundles
4
+ * that don't use it. The provider has no platform-specific code of its own;
5
+ * the clients it builds on resolve to their browser variants through the
6
+ * package's browser field, as from the main entry. That is why this entry
7
+ * and `tinfoil/unsafe` have no `browser` condition in the package's exports
8
+ * map: a bundler substitutes the internal modules that the browser field
9
+ * lists, so neither entry needs a browser build of its own.
10
+ */
11
+ export { createTinfoil, type TinfoilProvider, type TinfoilProviderOptions, type TinfoilProviderEnclave } from "./internal/ai-sdk.js";
12
+ //# sourceMappingURL=ai-sdk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-sdk.d.ts","sourceRoot":"","sources":["../src/ai-sdk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,aAAa,EAAE,KAAK,eAAe,EAAE,KAAK,sBAAsB,EAAE,KAAK,sBAAsB,EAAE,MAAM,sBAAsB,CAAC"}
package/dist/ai-sdk.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The `tinfoil/ai-sdk` entry: a provider for the Vercel AI SDK over an
3
+ * attested client. It is its own entry so the AI SDK stays out of bundles
4
+ * that don't use it. The provider has no platform-specific code of its own;
5
+ * the clients it builds on resolve to their browser variants through the
6
+ * package's browser field, as from the main entry. That is why this entry
7
+ * and `tinfoil/unsafe` have no `browser` condition in the package's exports
8
+ * map: a bundler substitutes the internal modules that the browser field
9
+ * lists, so neither entry needs a browser build of its own.
10
+ */
11
+ export { createTinfoil } from "./internal/ai-sdk.js";
12
+ //# sourceMappingURL=ai-sdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-sdk.js","sourceRoot":"","sources":["../src/ai-sdk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,aAAa,EAAkF,MAAM,sBAAsB,CAAC"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * An HTTP client whose requests reach only one attested enclave. The client
3
+ * verifies the enclave before its factory returns, verifies again by itself
4
+ * when the verification expires or is rejected, and refuses requests to any
5
+ * origin other than the one it is bound to.
6
+ */
7
+ import type { Verification } from "@tinfoilsh/verifier";
8
+ import { asyncDispose } from "./internal/dispose.js";
9
+ import type { CallOptions, EnclaveOptions, Fetch } from "./options.js";
10
+ /**
11
+ * An HTTP client bound to one attested enclave; see the module header. The
12
+ * constructor is private: type-checked code cannot call it, and a call from
13
+ * untyped code is refused at runtime. Clients come from
14
+ * {@link EnclaveHTTPClient.create}, and from the factories built over it:
15
+ * {@link EnclaveOpenAIClient.create} and the AI SDK provider's `enclave`
16
+ * option.
17
+ */
18
+ export declare class EnclaveHTTPClient {
19
+ #private;
20
+ /**
21
+ * Sends a request through the attested transport. Bound, so it can be
22
+ * passed as a `fetch` implementation. A request to another origin is a
23
+ * {@link ConfigurationError}.
24
+ */
25
+ readonly fetch: Fetch;
26
+ /** Where requests go: the `baseURL` option, or the enclave's own origin. Always ends with `/`, so a relative path resolves against it with `new URL(path, client.baseURL)`. */
27
+ readonly baseURL: string;
28
+ /** The host of the verified enclave, even when `baseURL` is a proxy. */
29
+ readonly enclave: string;
30
+ /** The repository pin, empty when the verifier authorizes the config instead. */
31
+ readonly repo: string;
32
+ private constructor();
33
+ /**
34
+ * A client for the enclave at `host`, verified against `repo`
35
+ * (`owner/name[@tag][@sha256:digest]`). An empty `repo` accepts configs
36
+ * authorized by the verifier option. Options are checked before any network
37
+ * I/O; the enclave is verified before the client is returned.
38
+ */
39
+ static create(host: string, repo: string, options?: EnclaveOptions): Promise<EnclaveHTTPClient>;
40
+ /** The last successful verification, unchecked: it may have expired or been rejected. */
41
+ get current(): Verification | undefined;
42
+ /**
43
+ * A verification valid now, verifying first only if the cached one has
44
+ * expired or been rejected. Success means requests can be sent.
45
+ */
46
+ ensureVerified(options?: CallOptions): Promise<Verification>;
47
+ /** Verifies again even if the cached verification is still valid. */
48
+ reverify(options?: CallOptions): Promise<Verification>;
49
+ /**
50
+ * Releases what the client holds and refuses further use. On Node, the
51
+ * `"tls"` transport's pooled connections are closed, which also ends any
52
+ * request still in flight on them with a {@link NetworkError}; the
53
+ * `"ehbp"` transport sends through the runtime's fetch, or the `fetch`
54
+ * option, and holds no connections of its own, so a request in flight
55
+ * completes. No verification runs again. Afterwards `fetch`, `ensureVerified`,
56
+ * `reverify` and the WebSocket functions reject with a
57
+ * {@link ConfigurationError}; `current` still reports the last
58
+ * verification. Closing again does nothing.
59
+ */
60
+ close(): Promise<void>;
61
+ /** Closes the client at the end of an `await using` block; see {@link close}. */
62
+ [asyncDispose](): Promise<void>;
63
+ }
64
+ //# sourceMappingURL=enclave-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enclave-client.d.ts","sourceRoot":"","sources":["../src/enclave-client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGxD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAWrD,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,KAAK,EAAiB,MAAM,cAAc,CAAC;AA6HtF;;;;;;;GAOG;AACH,qBAAa,iBAAiB;;IAC5B;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,+KAA+K;IAC/K,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,wEAAwE;IACxE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,iFAAiF;IACjF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAGtB,OAAO;IAgBP;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAI/F,yFAAyF;IACzF,IAAI,OAAO,IAAI,YAAY,GAAG,SAAS,CAEtC;IAED;;;OAGG;IACH,cAAc,CAAC,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC;IAI5D,qEAAqE;IACrE,QAAQ,CAAC,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC;IAItD;;;;;;;;;;OAUG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,iFAAiF;IACjF,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;CAGhC"}
@@ -0,0 +1,196 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _EnclaveHTTPClient_transport;
13
+ import { ConfigurationError } from "./errors.js";
14
+ import { withCacheSecret } from "./internal/cachesecret.js";
15
+ import { asyncDispose } from "./internal/dispose.js";
16
+ import { Enclave } from "./internal/enclave.js";
17
+ import { normalizeBaseURL, validateBaseURL, validateTLSBaseURL } from "./internal/transport/base-url.js";
18
+ import { ehbpMode } from "./internal/transport/ehbp.js";
19
+ import { withEnclaveURL } from "./internal/transport/header.js";
20
+ import { withOriginRestriction } from "./internal/transport/origin.js";
21
+ import { checkTransportMode, defaultTransportMode } from "./internal/platform.js";
22
+ import { withReplay } from "./internal/transport/replay.js";
23
+ import { tlsMode } from "./internal/transport/tls.js";
24
+ import { isKeyRejection, KeyedTransport } from "./internal/transport/transport.js";
25
+ import { registerWebSocketAccess } from "./internal/websocket.js";
26
+ const openAIURLs = new WeakMap();
27
+ /** @internal Where an OpenAI client over `client` sends requests: the base URL option, or the enclave's `/v1/` API. */
28
+ export function openAIURLOf(client) {
29
+ const url = openAIURLs.get(client);
30
+ if (url === undefined)
31
+ throw new ConfigurationError("client was not created by its factory");
32
+ return url;
33
+ }
34
+ /** @internal Records where an OpenAI client over `client` sends requests. */
35
+ export function setOpenAIURL(client, url) {
36
+ openAIURLs.set(client, url);
37
+ }
38
+ /**
39
+ * @internal `mode`, or the platform's default: pinned connections where the
40
+ * runtime exposes them, sealed bodies in browsers. A mode the platform can't
41
+ * provide is a {@link ConfigurationError}.
42
+ */
43
+ export function resolveTransportMode(mode, globals) {
44
+ if (mode === undefined)
45
+ return defaultTransportMode(globals);
46
+ if (mode !== "tls" && mode !== "ehbp")
47
+ throw new ConfigurationError(`unknown transport mode ${JSON.stringify(mode)}`);
48
+ checkTransportMode(mode, globals);
49
+ return mode;
50
+ }
51
+ /**
52
+ * @internal The EHBP mode's settings: the caller's `fetch` option carries the
53
+ * sealed requests when given; otherwise the seam's fetch does, standing in
54
+ * for the runtime's, so a test of the option runs the same path as a caller.
55
+ */
56
+ export function ehbpOptionsFor(fetchImpl, seams) {
57
+ return { ...seams.ehbp, fetch: fetchImpl ?? seams.ehbp?.fetch };
58
+ }
59
+ /** @internal The transport mode's settings: the caller's `fetch` option for the EHBP mode, and the seams. */
60
+ export function modeFor(mode, fetchImpl, seams) {
61
+ return mode === "tls" ? tlsMode(seams.tls) : ehbpMode(ehbpOptionsFor(fetchImpl, seams));
62
+ }
63
+ /** @internal Rejects the `fetch` option under the `"tls"` mode, which pins its own connections and sends nothing through a caller's fetch. */
64
+ export function checkNetworkFetch(mode, fetchImpl) {
65
+ if (mode === "tls" && fetchImpl !== undefined) {
66
+ throw new ConfigurationError('the fetch option carries sealed requests, which requires transportMode "ehbp"; the "tls" transport mode pins its own connections');
67
+ }
68
+ }
69
+ /**
70
+ * @internal The fetch chain the enclave and router clients send through,
71
+ * from the inside out: the proxy header, one replay after a key rejection,
72
+ * the cache secret, and origin pinning. The cache secret sits above the
73
+ * transport, so the field it adds is sealed with the rest of the body or
74
+ * sent over the pinned connection.
75
+ */
76
+ export function attestedFetch(transport, host, baseURL, cacheSecret = "") {
77
+ let chain = withEnclaveURL(transport.fetch, host, baseURL);
78
+ chain = withReplay(chain, isKeyRejection);
79
+ chain = withCacheSecret(chain, cacheSecret);
80
+ return withOriginRestriction(chain, host, baseURL);
81
+ }
82
+ /** @internal The option checks that need no network I/O, so a misconfigured client fails before anything is fetched. The base URL comes back ending with `/`, or empty. */
83
+ export function checkEnclaveOptions(host, options, globals) {
84
+ if (host === "")
85
+ throw new ConfigurationError("enclave host is required");
86
+ const mode = resolveTransportMode(options.transportMode, globals);
87
+ checkNetworkFetch(mode, options.fetch);
88
+ const baseURL = options.baseURL ?? "";
89
+ if (baseURL !== "")
90
+ validateBaseURL(baseURL);
91
+ if (mode === "tls")
92
+ validateTLSBaseURL(baseURL, host);
93
+ return { mode, baseURL: baseURL === "" ? "" : normalizeBaseURL(baseURL) };
94
+ }
95
+ /** Only this module holds the token the constructor requires, so untyped code that calls it is refused. */
96
+ const TOKEN = Symbol("EnclaveHTTPClient");
97
+ /** Calls the private constructor; the class assigns it, as the only place the constructor can be called. */
98
+ let construct;
99
+ /** @internal The factory with its test seams; {@link EnclaveHTTPClient.create} is this without them. */
100
+ export async function createEnclaveHTTPClient(host, repo, options, seams) {
101
+ const { mode, baseURL } = checkEnclaveOptions(host, options, seams.globals);
102
+ const enclave = await Enclave.create({
103
+ host,
104
+ repo,
105
+ verifier: options.verifier,
106
+ verificationCheck: options.verificationCheck,
107
+ fetch: seams.documentFetch,
108
+ clock: seams.clock,
109
+ nonce: seams.nonce,
110
+ sleep: seams.sleep,
111
+ });
112
+ const transport = new KeyedTransport(enclave, modeFor(mode, options.fetch, seams), seams.clock);
113
+ const client = construct(transport, baseURL !== "" ? baseURL : `https://${host}/`, baseURL !== "" ? baseURL : `https://${host}/v1/`, attestedFetch(transport, host, baseURL, options.userCacheSecret ?? ""));
114
+ registerWebSocketAccess(client, transport, seams.tls ?? {});
115
+ // A verification that the signal cuts short goes on inside the transport,
116
+ // so the transport is closed when the client isn't returned: what that
117
+ // verification binds when it finishes is then released instead of kept
118
+ // by a client no one holds.
119
+ try {
120
+ await client.ensureVerified({ signal: options.signal });
121
+ }
122
+ catch (err) {
123
+ await client.close();
124
+ throw err;
125
+ }
126
+ return client;
127
+ }
128
+ /**
129
+ * An HTTP client bound to one attested enclave; see the module header. The
130
+ * constructor is private: type-checked code cannot call it, and a call from
131
+ * untyped code is refused at runtime. Clients come from
132
+ * {@link EnclaveHTTPClient.create}, and from the factories built over it:
133
+ * {@link EnclaveOpenAIClient.create} and the AI SDK provider's `enclave`
134
+ * option.
135
+ */
136
+ export class EnclaveHTTPClient {
137
+ constructor(token, transport, baseURL, openAIURL, fetchImpl) {
138
+ _EnclaveHTTPClient_transport.set(this, void 0);
139
+ if (token !== TOKEN)
140
+ throw new ConfigurationError("EnclaveHTTPClient is created with EnclaveHTTPClient.create");
141
+ __classPrivateFieldSet(this, _EnclaveHTTPClient_transport, transport, "f");
142
+ this.fetch = fetchImpl;
143
+ this.baseURL = baseURL;
144
+ this.enclave = transport.enclave().host();
145
+ this.repo = transport.enclave().repo();
146
+ setOpenAIURL(this, openAIURL);
147
+ // The client's state lives in the transport; the client itself never changes once created.
148
+ Object.freeze(this);
149
+ }
150
+ /**
151
+ * A client for the enclave at `host`, verified against `repo`
152
+ * (`owner/name[@tag][@sha256:digest]`). An empty `repo` accepts configs
153
+ * authorized by the verifier option. Options are checked before any network
154
+ * I/O; the enclave is verified before the client is returned.
155
+ */
156
+ static create(host, repo, options) {
157
+ return createEnclaveHTTPClient(host, repo, options ?? {}, {});
158
+ }
159
+ /** The last successful verification, unchecked: it may have expired or been rejected. */
160
+ get current() {
161
+ return __classPrivateFieldGet(this, _EnclaveHTTPClient_transport, "f").current();
162
+ }
163
+ /**
164
+ * A verification valid now, verifying first only if the cached one has
165
+ * expired or been rejected. Success means requests can be sent.
166
+ */
167
+ ensureVerified(options) {
168
+ return __classPrivateFieldGet(this, _EnclaveHTTPClient_transport, "f").ensureVerified(options?.signal);
169
+ }
170
+ /** Verifies again even if the cached verification is still valid. */
171
+ reverify(options) {
172
+ return __classPrivateFieldGet(this, _EnclaveHTTPClient_transport, "f").reverify(options?.signal);
173
+ }
174
+ /**
175
+ * Releases what the client holds and refuses further use. On Node, the
176
+ * `"tls"` transport's pooled connections are closed, which also ends any
177
+ * request still in flight on them with a {@link NetworkError}; the
178
+ * `"ehbp"` transport sends through the runtime's fetch, or the `fetch`
179
+ * option, and holds no connections of its own, so a request in flight
180
+ * completes. No verification runs again. Afterwards `fetch`, `ensureVerified`,
181
+ * `reverify` and the WebSocket functions reject with a
182
+ * {@link ConfigurationError}; `current` still reports the last
183
+ * verification. Closing again does nothing.
184
+ */
185
+ async close() {
186
+ __classPrivateFieldGet(this, _EnclaveHTTPClient_transport, "f").close();
187
+ }
188
+ /** Closes the client at the end of an `await using` block; see {@link close}. */
189
+ [(_EnclaveHTTPClient_transport = new WeakMap(), asyncDispose)]() {
190
+ return this.close();
191
+ }
192
+ }
193
+ (() => {
194
+ construct = (...parts) => new EnclaveHTTPClient(TOKEN, ...parts);
195
+ })();
196
+ //# sourceMappingURL=enclave-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enclave-client.js","sourceRoot":"","sources":["../src/enclave-client.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,OAAO,EAAsB,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACzG,OAAO,EAAE,QAAQ,EAAoB,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAuB,MAAM,wBAAwB,CAAC;AACvG,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,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O,uBAAuB,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;IAChE,CAAC;IAED,yFAAyF;IACzF,IAAI,OAAO;QACT,OAAO,uBAAA,IAAI,oCAAW,CAAC,OAAO,EAAE,CAAC;IACnC,CAAC;IAED;;;OAGG;IACH,cAAc,CAAC,OAAqB;QAClC,OAAO,uBAAA,IAAI,oCAAW,CAAC,cAAc,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACzD,CAAC;IAED,qEAAqE;IACrE,QAAQ,CAAC,OAAqB;QAC5B,OAAO,uBAAA,IAAI,oCAAW,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACnD,CAAC;IAED;;;;;;;;;;OAUG;IACH,KAAK,CAAC,KAAK;QACT,uBAAA,IAAI,oCAAW,CAAC,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,iFAAiF;IACjF,gDAAC,YAAY,EAAC;QACZ,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACF;AAnDC;IACE,SAAS,GAAG,CAAC,GAAG,KAAK,EAAE,EAAE,CAAC,IAAI,iBAAiB,CAAC,KAAK,EAAE,GAAG,KAAK,CAAC,CAAC;AACnE,CAAC,GAAA,CAAA"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The client's errors: one of three categories and the error that caused it.
3
+ * A message reads as the category, a colon, then the cause, as in
4
+ * "attestation error: <cause>". Errors from the OpenAI API keep their own
5
+ * types.
6
+ */
7
+ /**
8
+ * The categories a {@link TinfoilError} falls into: the stable discriminant
9
+ * to switch on, carried by every error's `category`.
10
+ */
11
+ export type ErrorCategory = "configuration" | "network" | "attestation";
12
+ /**
13
+ * Base class for every error the client throws. Switch on `category`, which
14
+ * is the stable discriminant; `name` matches the concrete class
15
+ * (`ConfigurationError`, `NetworkError` or `AttestationError`) for logs and
16
+ * stack traces.
17
+ */
18
+ export declare abstract class TinfoilError extends Error {
19
+ readonly category: ErrorCategory;
20
+ readonly cause?: unknown;
21
+ constructor(category: ErrorCategory, message: string, options?: {
22
+ cause?: unknown;
23
+ });
24
+ }
25
+ /** Invalid caller arguments or client configuration. Retrying won't help. */
26
+ export declare class ConfigurationError extends TinfoilError {
27
+ constructor(message: string, options?: {
28
+ cause?: unknown;
29
+ });
30
+ }
31
+ /**
32
+ * The client couldn't reach what it needed: a network failure, a timeout or
33
+ * an HTTP error status while fetching attestation material, or a gateway that
34
+ * keeps routing a request away from its enclave.
35
+ */
36
+ export declare class NetworkError extends TinfoilError {
37
+ constructor(message: string, options?: {
38
+ cause?: unknown;
39
+ });
40
+ }
41
+ /**
42
+ * Rejected evidence, policy, or channel binding: the enclave couldn't be
43
+ * trusted. When verification itself rejected the document, `cause` is the
44
+ * verifier's `VerificationError` (from `@tinfoilsh/verifier`), whose `layer`
45
+ * names the check that rejected it. A connection whose key doesn't match
46
+ * the attested one, or a key the enclave no longer holds after rotation, is
47
+ * reported as an AttestationError too.
48
+ */
49
+ export declare class AttestationError extends TinfoilError {
50
+ constructor(message: string, options?: {
51
+ cause?: unknown;
52
+ });
53
+ }
54
+ /** The message of an unknown thrown value. */
55
+ export declare function messageOf(err: unknown): string;
56
+ /** The message of `err` without its category prefix: what it was constructed with. */
57
+ export declare function stripCategory(err: TinfoilError): string;
58
+ /**
59
+ * A plain error of `err`'s category with `message`, caused by what caused
60
+ * `err` (or `err` itself): the form a layer throws when it gives up on
61
+ * `err`, leaving behind any subclass and what that promised the caller.
62
+ */
63
+ export declare function withMessage(err: TinfoilError, message: string): TinfoilError;
64
+ /** `err` as a {@link NetworkError}, unless it is already a client error. */
65
+ export declare function wrapNetwork(err: unknown): TinfoilError;
66
+ /** `err` as an {@link AttestationError}, unless it is already a client error. */
67
+ export declare function wrapAttestation(err: unknown): TinfoilError;
68
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":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ors.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The client's errors: one of three categories and the error that caused it.
3
+ * A message reads as the category, a colon, then the cause, as in
4
+ * "attestation error: <cause>". Errors from the OpenAI API keep their own
5
+ * types.
6
+ */
7
+ /**
8
+ * Base class for every error the client throws. Switch on `category`, which
9
+ * is the stable discriminant; `name` matches the concrete class
10
+ * (`ConfigurationError`, `NetworkError` or `AttestationError`) for logs and
11
+ * stack traces.
12
+ */
13
+ export class TinfoilError extends Error {
14
+ constructor(category, message, options) {
15
+ super(`${category} error: ${message}`);
16
+ this.category = category;
17
+ if (options?.cause !== undefined) {
18
+ this.cause = options.cause;
19
+ }
20
+ }
21
+ }
22
+ /** Invalid caller arguments or client configuration. Retrying won't help. */
23
+ export class ConfigurationError extends TinfoilError {
24
+ constructor(message, options) {
25
+ super("configuration", message, options);
26
+ this.name = "ConfigurationError";
27
+ }
28
+ }
29
+ /**
30
+ * The client couldn't reach what it needed: a network failure, a timeout or
31
+ * an HTTP error status while fetching attestation material, or a gateway that
32
+ * keeps routing a request away from its enclave.
33
+ */
34
+ export class NetworkError extends TinfoilError {
35
+ constructor(message, options) {
36
+ super("network", message, options);
37
+ this.name = "NetworkError";
38
+ }
39
+ }
40
+ /**
41
+ * Rejected evidence, policy, or channel binding: the enclave couldn't be
42
+ * trusted. When verification itself rejected the document, `cause` is the
43
+ * verifier's `VerificationError` (from `@tinfoilsh/verifier`), whose `layer`
44
+ * names the check that rejected it. A connection whose key doesn't match
45
+ * the attested one, or a key the enclave no longer holds after rotation, is
46
+ * reported as an AttestationError too.
47
+ */
48
+ export class AttestationError extends TinfoilError {
49
+ constructor(message, options) {
50
+ super("attestation", message, options);
51
+ this.name = "AttestationError";
52
+ }
53
+ }
54
+ /** The message of an unknown thrown value. */
55
+ export function messageOf(err) {
56
+ return err instanceof Error ? err.message : String(err);
57
+ }
58
+ /** The message of `err` without its category prefix: what it was constructed with. */
59
+ export function stripCategory(err) {
60
+ const prefix = `${err.category} error: `;
61
+ return err.message.startsWith(prefix) ? err.message.slice(prefix.length) : err.message;
62
+ }
63
+ /**
64
+ * A plain error of `err`'s category with `message`, caused by what caused
65
+ * `err` (or `err` itself): the form a layer throws when it gives up on
66
+ * `err`, leaving behind any subclass and what that promised the caller.
67
+ */
68
+ export function withMessage(err, message) {
69
+ const options = { cause: err.cause ?? err };
70
+ if (err instanceof NetworkError)
71
+ return new NetworkError(message, options);
72
+ if (err instanceof ConfigurationError)
73
+ return new ConfigurationError(message, options);
74
+ return new AttestationError(message, options);
75
+ }
76
+ /** `err` as a {@link NetworkError}, unless it is already a client error. */
77
+ export function wrapNetwork(err) {
78
+ return err instanceof TinfoilError ? err : new NetworkError(messageOf(err), { cause: err });
79
+ }
80
+ /** `err` as an {@link AttestationError}, unless it is already a client error. */
81
+ export function wrapAttestation(err) {
82
+ return err instanceof TinfoilError ? err : new AttestationError(messageOf(err), { cause: err });
83
+ }
84
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAQH;;;;;GAKG;AACH,MAAM,OAAgB,YAAa,SAAQ,KAAK;IAI9C,YAAY,QAAuB,EAAE,OAAe,EAAE,OAA6B;QACjF,KAAK,CAAC,GAAG,QAAQ,WAAW,OAAO,EAAE,CAAC,CAAC;QACvC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,OAAO,EAAE,KAAK,KAAK,SAAS,EAAE,CAAC;YAChC,IAA4B,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QACtD,CAAC;IACH,CAAC;CACF;AAED,6EAA6E;AAC7E,MAAM,OAAO,kBAAmB,SAAQ,YAAY;IAClD,YAAY,OAAe,EAAE,OAA6B;QACxD,KAAK,CAAC,eAAe,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QACzC,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC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