@tianacloud/serverless 0.1.0-beta.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.
package/README.md ADDED
@@ -0,0 +1,248 @@
1
+ # `@tianacloud/serverless`
2
+
3
+ `@tianacloud/serverless` is the JavaScript/TypeScript Custom Fetch adapter for
4
+ Tiana Fetch-over-HTTPS v1. It converts one standard same-origin `fetch()`
5
+ request into a TFQ1 request to the Tiana Gateway and exposes the TFS1 inner
6
+ response as a standard `Response`.
7
+
8
+ Install the prerelease with `npm install @tianacloud/serverless@next`. Its historical Fetch v1 compatibility baseline is
9
+ Contracts release `v0.17.2-rc.1` at commit
10
+ `d252fd7bf689657e50b6caf36298f8c57860df6b` (annotated tag object
11
+ `fb4fdf07f6e5b86eb00562f07dccf7bd120cd0f2`).
12
+
13
+ ## Intended use
14
+
15
+ ```ts
16
+ import { createTianaFetch } from "@tianacloud/serverless";
17
+
18
+ const databaseOrigin =
19
+ "https://ep-01j5c9m7q2v8x4k6n3r0t1w2yz.db.service.internal.tiana.com";
20
+
21
+ const tianaFetch = createTianaFetch({
22
+ origin: databaseOrigin,
23
+ tianaToken: process.env.TIANA_TOKEN!,
24
+ });
25
+
26
+ // Pass `tianaFetch` as the custom Fetch implementation of the database
27
+ // client. The database client's Authorization header remains an inner header;
28
+ // the Tiana Token is used only for the outer Gateway request.
29
+ ```
30
+
31
+ The adapter accepts `RequestInfo | URL` plus an optional `RequestInit`, uses
32
+ the platform `Request` constructor for normalization, and rejects any request
33
+ whose normalized origin differs from the configured origin. It performs one
34
+ outer request and never retries automatically.
35
+
36
+ Tokens are opaque credential strings, forwarded unchanged to Gateway in the
37
+ outer Authorization header. The adapter does not interpret their scope or encoding.
38
+
39
+ The configured HTTPS origin uses a v1 Endpoint ID
40
+ (`ep-[0-7][0-9a-hjkmnp-tv-z]{25}`) followed by the deployment's Endpoint DNS
41
+ suffix and port. Use the Endpoint address published by Gaia through the
42
+ connection configuration. Requests must use that same normalized origin.
43
+ Hosts without a v1 Endpoint ID, IP literals, paths, queries, fragments,
44
+ and embedded credentials are rejected before transport.
45
+
46
+ Browser transports can set `requestBodyMode: "buffered"` for native data
47
+ requests. HTTP data requests are always buffered. Responses remain streamed.
48
+
49
+ ## App HTTP data API
50
+
51
+ ```ts
52
+ const http = createTianaFetch({
53
+ origin: databaseOrigin,
54
+ tianaToken,
55
+ protocol: "tiana-http",
56
+ });
57
+ const response = await http(`${databaseOrigin}/v1/sql`, {
58
+ method: "POST",
59
+ headers: { "content-type": "application/json" },
60
+ body: JSON.stringify({ sql: "SELECT 1 AS answer;" }),
61
+ });
62
+ const result = await response.json();
63
+ ```
64
+
65
+ The optional protocol is top-level Fetch metadata, consumed by Gateway to
66
+ select the App HTTP data socket. Omitting it selects the existing native data
67
+ socket. Gateway forwards the inner path; `/v1/sql` belongs to the SQLite App.
68
+
69
+ The HTTP data adapter reads the complete request body before sending its
70
+ binary frame and retains streaming response decoding. It uses the existing
71
+ request-size bound and does not require browser request-stream support.
72
+ Abort cancels this call; requests are never replayed. Gateway handles CORS
73
+ preflight for arbitrary browser origins; actual requests retain Tiana Token
74
+ authorization and use `credentials: "omit"`.
75
+
76
+ Each call owns an independent App connection. Send `BEGIN; ...; COMMIT;` in
77
+ one request. Separate calls do not share a connection transaction or TEMP
78
+ state; SQL errors and partial success keep the App's existing semantics.
79
+
80
+ ## Request diagnostics
81
+
82
+ The adapter generates a request ID before network I/O and sends the same ID
83
+ in the outer `X-Request-ID` header and TFQ1 metadata. Use `onDiagnostic` for
84
+ failures that occur before a `Response` exists and for response body errors:
85
+
86
+ ```ts
87
+ import { createTianaFetch, diagnosisOf } from "@tianacloud/serverless";
88
+
89
+ const http = createTianaFetch({
90
+ origin: databaseOrigin,
91
+ tianaToken,
92
+ onDiagnostic(event) {
93
+ if (event.phase === "failed") console.error("Tiana request", event.requestId);
94
+ },
95
+ });
96
+
97
+ try {
98
+ const response = await http(`${databaseOrigin}/v1/sql`);
99
+ console.log(diagnosisOf(response)?.requestId);
100
+ await response.text();
101
+ } catch (error) {
102
+ console.error(diagnosisOf(error)?.requestId);
103
+ }
104
+ ```
105
+
106
+ `diagnosisOf` accepts the original `Request`, returned `Response`, or an
107
+ object-shaped error. A primitive Abort reason is available through
108
+ `onDiagnostic`. The latest phase becomes `completed` only after a streamed
109
+ body is fully read, or `cancelled`/`failed` when it stops early. Reading the
110
+ diagnostic does not consume the body. A callback exception does not change
111
+ the Fetch result.
112
+
113
+ ## Development
114
+
115
+ ```sh
116
+ corepack pnpm install --frozen-lockfile
117
+ corepack pnpm exec playwright install chromium
118
+ corepack pnpm check
119
+ ```
120
+
121
+ The runtime has no production dependencies and uses only standard Fetch,
122
+ Web Streams, URL, Encoding, and Web Crypto APIs. Node, Bun and Deno have local
123
+ runtime test coverage. Record the runtime version and executed checks when
124
+ reporting results.
125
+
126
+ With Deno installed, run the package smoke test and existing diagnostic suite:
127
+
128
+ ```sh
129
+ corepack pnpm build
130
+ deno run --allow-read --node-modules-dir=manual tests/runtime-smoke.mjs
131
+ deno test --allow-read --node-modules-dir=manual tests/adapter.test.mjs tests/conformance.test.mjs tests/provenance.test.mjs
132
+ ```
133
+
134
+ These checks use local transport fixtures. Deployed Gateway, network failures
135
+ and hosted edge environments need their own runtime evidence.
136
+
137
+ `pnpm test:browser` exercises request diagnostics in Chromium against a local
138
+ cross-origin HTTPS/H2 fixture. It covers buffered and streamed requests,
139
+ outer and inner errors, truncated bodies, socket reset, DNS/TLS failure,
140
+ AbortSignal before and after headers, body cancellation, CORS rejection,
141
+ observer failures, and concurrent identities.
142
+ The test needs OpenSSL to create a temporary certificate and removes its
143
+ temporary files when finished. It does not contact a deployed Tiana environment.
144
+
145
+ The SDK owns its codec, limits, and behavior tests. The byte vectors under
146
+ `tests/fixtures` retain their historical provenance and remain local regression
147
+ inputs. Build, test, and packaging do not read a Contracts or Specifications
148
+ checkout, fetch a historical distribution, or validate a central Schema.
149
+
150
+ For cross-implementation testing, `tests/gateway-interop.mjs` accepts an
151
+ unpacked SDK package's `dist/index.js` and a Gateway loopback fixture JSON as
152
+ explicit arguments. It imports the packaged adapter and exchanges requests
153
+ with the real Rust ingress over TLS H1/H2. Its Node HTTP transport preserves
154
+ SDK-produced frame bytes and maps the configured Endpoint to loopback using
155
+ the fixture certificate. Gateway's `docs/fetch-interop.md` describes the
156
+ fixture lifecycle and backend test doubles. This optional test does not run
157
+ as part of the standalone SDK suite.
158
+
159
+ The optional `tests/run-http-data-interop.py` takes explicit Agent/Gateway
160
+ checkouts, a built SQLite binary and an output directory. It runs the real
161
+ data path with fixture policy/binding inputs, including 100 warm H1/H2 calls.
162
+ `--playwright-module` adds real Chromium/Firefox/WebKit cross-origin calls.
163
+ This is separate from standard cold activation and deployed edge acceptance.
164
+
165
+ ## Account sessions and automatic refresh
166
+
167
+ Existing `createTianaFetch({origin, tianaToken})` callers remain supported. For
168
+ account credentials, share one auth provider across every adapter for that login:
169
+
170
+ ```ts
171
+ import { createTianaFetch, createTianaSessionAuth } from "@tianacloud/serverless";
172
+
173
+ const auth = createTianaSessionAuth({
174
+ managementOrigin: "https://console.example.test",
175
+ credentials: {
176
+ accessToken: login.access_token,
177
+ refreshToken: login.refresh_token,
178
+ expiresAt: loginRequestStartedAt + login.expires_in * 1000,
179
+ refreshExpiresAt: Date.parse(login.refresh_expires_at),
180
+ syncStatus: login.sync_status,
181
+ },
182
+ // Optional: atomically replace the complete credential snapshot in your store.
183
+ persist: async credentials => credentialStore.replace(credentials),
184
+ });
185
+ const tianaFetch = createTianaFetch({ origin: databaseOrigin, auth });
186
+ ```
187
+
188
+ `expiresAt` and `refreshExpiresAt` use Unix **milliseconds**. The login response,
189
+ store and database origin in this example are supplied by your application; this
190
+ package does not initiate login or read environment variables/files. Configure
191
+ management routing outside the skill/application (for example pass the process's
192
+ `TIANA_API_ORIGIN` when starting a Node host). Only HTTPS management origins are
193
+ accepted. The management transport is independent of the data adapter.
194
+
195
+ Before expiry (30 seconds by default), the provider lazily rotates both tokens
196
+ through `POST /api/v1/auth/refresh`. It saves the full replacement, then waits for
197
+ `GET /api/v1/auth/transactions/whoami` to report `sync_status: complete`. Omit
198
+ `syncStatus` when readiness is unknown; the provider checks it. One provider
199
+ shares one refresh/save/readiness operation. Cancelling a caller stops only that
200
+ waiter; the shared operation has its own 15-second bound. Synchronization polling
201
+ backs off from 250 ms to 2 seconds. Options `refreshBeforeMs`, `timeoutMs` and
202
+ `pollIntervalMs` override these defaults. No idle timer refreshes credentials.
203
+
204
+ The refresh token is sent only to the management refresh endpoint. The access
205
+ token becomes the outer Gateway `Authorization` credential, never an inner SQL
206
+ credential. Data requests are sent once: a Gateway 401/403, network failure or
207
+ truncated response never causes automatic refresh or SQL replay.
208
+
209
+ `TianaAuthError.code` identifies recovery:
210
+
211
+ - `AUTH_LOGIN_REQUIRED`: obtain a new login session.
212
+ - `AUTH_REFRESH_UNCERTAIN`: the refresh may have committed; do not retry the old
213
+ refresh token. Obtain a new session. Current MGR has no idempotent recovery API.
214
+ - `AUTH_PERSIST_FAILED`: retry the provider after repairing the store. The new
215
+ credentials stay in memory, and only persistence is retried. An unresolved save
216
+ is joined, never duplicated. A process crash before a successful atomic save
217
+ can require login again.
218
+ - `AUTH_NOT_READY`: no data request was sent. A later call can recheck grant sync.
219
+
220
+ The concurrency boundary is **one provider**, not all processes/tabs. Use an
221
+ external broker/lock when multiple hosts share a rotating refresh token. Account
222
+ access tokens have tenant/account data permissions rather than one-instance
223
+ scope; run browser application code only within the intended trust boundary.
224
+
225
+ For browser previews, keep refresh credentials in a broker. CLI `web serve`
226
+ provides the compatible `window.tiana.auth` access-token provider:
227
+
228
+ ```ts
229
+ const connection = await window.tiana.connection();
230
+ const tianaFetch = createTianaFetch({
231
+ origin: connection.origin,
232
+ auth: window.tiana.auth,
233
+ requestBodyMode: "buffered",
234
+ });
235
+ ```
236
+
237
+ Do not also pass `tianaToken` when using `auth`. The connection's `sql_api` still
238
+ selects your SQL client, not the optional `protocol: "tiana-http"` data socket.
239
+ Direct browser calls to MGR require an explicitly supported same-origin/CORS
240
+ setup; this SDK does not add MGR CORS or persist refresh tokens in browser storage.
241
+
242
+ Account session providers also accept `onDiagnostic`. Each refresh and whoami
243
+ request gets its own request ID before transport starts. The same safe diagnostic
244
+ fields are available through `diagnosisOf(error)` for authorization failures,
245
+ including when the provider is used by `createTianaFetch`. A cancelled caller
246
+ retains its diagnostic without cancelling a refresh shared with other callers.
247
+ The callback receives no tokens or response bodies; callback errors do not change
248
+ authorization results.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { type TianaDiagnostic } from "./diagnostics.js";
2
+ /** Account credentials are held only by the auth provider, never by data frames. */
3
+ export interface TianaSessionCredentials {
4
+ readonly accessToken: string;
5
+ readonly refreshToken: string;
6
+ /** Unix milliseconds. Tokens are opaque; the SDK never decodes their expiry. */
7
+ readonly expiresAt: number;
8
+ readonly refreshExpiresAt: number;
9
+ readonly syncStatus?: "pending" | "complete" | "failed";
10
+ }
11
+ /** Share one provider across endpoints using the same login session. */
12
+ export interface TianaAuthProvider {
13
+ getAccessToken(options?: {
14
+ readonly signal?: AbortSignal;
15
+ }): Promise<string>;
16
+ }
17
+ export type TianaAuthErrorCode = "AUTH_LOGIN_REQUIRED" | "AUTH_REFRESH_UNCERTAIN" | "AUTH_PERSIST_FAILED" | "AUTH_NOT_READY";
18
+ export declare class TianaAuthError extends Error {
19
+ readonly code: TianaAuthErrorCode;
20
+ constructor(code: TianaAuthErrorCode);
21
+ }
22
+ export interface TianaSessionAuthOptions {
23
+ readonly managementOrigin: string | URL;
24
+ readonly credentials: TianaSessionCredentials;
25
+ /** Save the entire replacement atomically. Failures never restore old tokens. */
26
+ readonly persist?: (credentials: TianaSessionCredentials) => void | Promise<void>;
27
+ /** Independent management transport; never the Tiana data adapter itself. */
28
+ readonly fetch?: typeof globalThis.fetch;
29
+ readonly refreshBeforeMs?: number;
30
+ readonly timeoutMs?: number;
31
+ readonly pollIntervalMs?: number;
32
+ /** Management request diagnostics; callback failures do not affect auth. */
33
+ readonly onDiagnostic?: (diagnostic: TianaDiagnostic) => void;
34
+ }
35
+ /** Cancelling a waiter never cancels a shared refresh or credential save. */
36
+ export declare function waitFor<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T>;
37
+ /** Lazy, single-flight account rotation. Data requests are never retried here. */
38
+ export declare function createTianaSessionAuth(options: TianaSessionAuthOptions): TianaAuthProvider;
39
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,eAAe,EACrB,MAAM,kBAAkB,CAAC;AAE1B,oFAAoF;AACpF,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,gFAAgF;IAChF,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,GAAG,UAAU,GAAG,QAAQ,CAAC;CACzD;AAED,wEAAwE;AACxE,MAAM,WAAW,iBAAiB;IAChC,cAAc,CAAC,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC9E;AAED,MAAM,MAAM,kBAAkB,GAC1B,qBAAqB,GACrB,wBAAwB,GACxB,qBAAqB,GACrB,gBAAgB,CAAC;AAErB,qBAAa,cAAe,SAAQ,KAAK;IACvC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,YAAY,IAAI,EAAE,kBAAkB,EAYnC;CACF;AAED,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,GAAG,GAAG,CAAC;IACxC,QAAQ,CAAC,WAAW,EAAE,uBAAuB,CAAC;IAC9C,iFAAiF;IACjF,QAAQ,CAAC,OAAO,CAAC,EAAE,CACjB,WAAW,EAAE,uBAAuB,KACjC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,6EAA6E;IAC7E,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IACzC,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,4EAA4E;IAC5E,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,KAAK,IAAI,CAAC;CAC/D;AAsED,6EAA6E;AAC7E,wBAAgB,OAAO,CAAC,CAAC,EACvB,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EACnB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,CAAC,CAAC,CAuBZ;AAqCD,kFAAkF;AAClF,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,uBAAuB,GAC/B,iBAAiB,CA2RnB"}
package/dist/auth.js ADDED
@@ -0,0 +1,391 @@
1
+ import { diagnostics, createRequestId, } from "./diagnostics.js";
2
+ export class TianaAuthError extends Error {
3
+ code;
4
+ constructor(code) {
5
+ super({
6
+ AUTH_LOGIN_REQUIRED: "Sign in again to obtain account credentials",
7
+ AUTH_REFRESH_UNCERTAIN: "Refresh outcome is unknown; obtain new credentials before continuing",
8
+ AUTH_PERSIST_FAILED: "New credentials could not be saved",
9
+ AUTH_NOT_READY: "Account authorization is not ready for data requests",
10
+ }[code]);
11
+ this.name = "TianaAuthError";
12
+ this.code = code;
13
+ }
14
+ }
15
+ const maxResponseBytes = 64 * 1024;
16
+ function originOf(value) {
17
+ let url;
18
+ try {
19
+ url = new URL(value);
20
+ }
21
+ catch {
22
+ throw new TypeError("managementOrigin must be an HTTPS origin");
23
+ }
24
+ if (url.protocol !== "https:" ||
25
+ url.username ||
26
+ url.password ||
27
+ url.pathname !== "/" ||
28
+ url.search ||
29
+ url.hash) {
30
+ throw new TypeError("managementOrigin must be an HTTPS origin");
31
+ }
32
+ return url.origin;
33
+ }
34
+ function secret(value) {
35
+ return (typeof value === "string" &&
36
+ value.length > 0 &&
37
+ value.length <= 16384 &&
38
+ !/[\s\x00-\x1f\x7f]/u.test(value));
39
+ }
40
+ function timestamp(value) {
41
+ return (typeof value === "number" &&
42
+ Number.isSafeInteger(value) &&
43
+ value > 0 &&
44
+ value <= 8640000000000000);
45
+ }
46
+ function copyCredentials(value) {
47
+ if (!value ||
48
+ !secret(value.accessToken) ||
49
+ !secret(value.refreshToken) ||
50
+ !timestamp(value.expiresAt) ||
51
+ !timestamp(value.refreshExpiresAt) ||
52
+ (value.syncStatus !== undefined &&
53
+ !["pending", "complete", "failed"].includes(value.syncStatus))) {
54
+ throw new TypeError("Invalid session credentials");
55
+ }
56
+ return Object.freeze({
57
+ accessToken: value.accessToken,
58
+ refreshToken: value.refreshToken,
59
+ expiresAt: value.expiresAt,
60
+ refreshExpiresAt: value.refreshExpiresAt,
61
+ ...(value.syncStatus === undefined ? {} : { syncStatus: value.syncStatus }),
62
+ });
63
+ }
64
+ function positive(value, maximum, name) {
65
+ if (!Number.isSafeInteger(value) || value <= 0 || value > maximum)
66
+ throw new TypeError(`Invalid ${name}`);
67
+ return value;
68
+ }
69
+ function abortReason(signal) {
70
+ return (signal.reason ?? new DOMException("The operation was aborted", "AbortError"));
71
+ }
72
+ /** Cancelling a waiter never cancels a shared refresh or credential save. */
73
+ export function waitFor(promise, signal) {
74
+ if (!signal)
75
+ return promise;
76
+ if (signal.aborted) {
77
+ void promise.catch(() => undefined);
78
+ return Promise.reject(abortReason(signal));
79
+ }
80
+ return new Promise((resolve, reject) => {
81
+ const abort = () => {
82
+ signal.removeEventListener("abort", abort);
83
+ reject(abortReason(signal));
84
+ };
85
+ signal.addEventListener("abort", abort, { once: true });
86
+ promise.then((value) => {
87
+ signal.removeEventListener("abort", abort);
88
+ resolve(value);
89
+ }, (error) => {
90
+ signal.removeEventListener("abort", abort);
91
+ reject(error);
92
+ });
93
+ });
94
+ }
95
+ async function readJSON(response, signal) {
96
+ if (!response.body)
97
+ throw new Error("Missing response");
98
+ const reader = response.body.getReader();
99
+ const chunks = [];
100
+ let size = 0;
101
+ try {
102
+ for (;;) {
103
+ const next = await waitFor(reader.read(), signal);
104
+ if (next.done)
105
+ break;
106
+ size += next.value.byteLength;
107
+ if (size > maxResponseBytes)
108
+ throw new Error("Response limit");
109
+ chunks.push(next.value);
110
+ }
111
+ const bytes = new Uint8Array(size);
112
+ let offset = 0;
113
+ for (const chunk of chunks) {
114
+ bytes.set(chunk, offset);
115
+ offset += chunk.byteLength;
116
+ }
117
+ const result = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
118
+ if (!result || typeof result !== "object" || Array.isArray(result))
119
+ throw new Error("Invalid response");
120
+ return result;
121
+ }
122
+ catch (error) {
123
+ void reader.cancel().catch(() => undefined);
124
+ throw error;
125
+ }
126
+ finally {
127
+ reader.releaseLock();
128
+ }
129
+ }
130
+ /** Lazy, single-flight account rotation. Data requests are never retried here. */
131
+ export function createTianaSessionAuth(options) {
132
+ const origin = originOf(options.managementOrigin);
133
+ let credentials = copyCredentials(options.credentials);
134
+ const transport = options.fetch ?? globalThis.fetch?.bind(globalThis);
135
+ if (typeof transport !== "function")
136
+ throw new TypeError("Fetch is required");
137
+ if (options.persist !== undefined && typeof options.persist !== "function")
138
+ throw new TypeError("Invalid persist callback");
139
+ const refreshBeforeMs = positive(options.refreshBeforeMs ?? 30000, 3600000, "refreshBeforeMs");
140
+ const timeoutMs = positive(options.timeoutMs ?? 15000, 300000, "timeoutMs");
141
+ const pollIntervalMs = positive(options.pollIntervalMs ?? 250, 10000, "pollIntervalMs");
142
+ let ready = credentials.syncStatus === "complete";
143
+ let savePending = false;
144
+ const save = options.persist;
145
+ let saving;
146
+ let stopped;
147
+ let work;
148
+ let currentDiagnostic;
149
+ let diagnosticPending = false;
150
+ function emitDiagnostic(phase, fields = {}) {
151
+ if (!currentDiagnostic)
152
+ return;
153
+ currentDiagnostic = {
154
+ ...currentDiagnostic,
155
+ phase,
156
+ time: new Date().toISOString(),
157
+ ...fields,
158
+ };
159
+ try {
160
+ options.onDiagnostic?.(currentDiagnostic);
161
+ }
162
+ catch {
163
+ /* Observation does not change authentication. */
164
+ }
165
+ }
166
+ function beginRequest() {
167
+ const requestId = createRequestId();
168
+ currentDiagnostic = {
169
+ requestId,
170
+ phase: "request_started",
171
+ time: new Date().toISOString(),
172
+ };
173
+ diagnosticPending = true;
174
+ emitDiagnostic("request_started");
175
+ return requestId;
176
+ }
177
+ function completeRequest() {
178
+ emitDiagnostic("completed");
179
+ diagnosticPending = false;
180
+ }
181
+ async function run() {
182
+ if (stopped)
183
+ throw stopped;
184
+ // Saving a successful rotation takes precedence over any later rotation.
185
+ const controller = new AbortController();
186
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
187
+ const signal = controller.signal;
188
+ try {
189
+ if (savePending)
190
+ await persist(signal);
191
+ if (credentials.expiresAt <= Date.now() + refreshBeforeMs) {
192
+ if (credentials.refreshExpiresAt <= Date.now()) {
193
+ stopped = new TianaAuthError("AUTH_LOGIN_REQUIRED");
194
+ throw stopped;
195
+ }
196
+ const startedAt = Date.now();
197
+ const requestId = beginRequest();
198
+ let response;
199
+ let body;
200
+ try {
201
+ response = await waitFor(transport(`${origin}/api/v1/auth/refresh`, {
202
+ method: "POST",
203
+ headers: {
204
+ "content-type": "application/json",
205
+ "x-request-id": requestId,
206
+ "cache-control": "no-store",
207
+ },
208
+ body: JSON.stringify({ refresh_token: credentials.refreshToken }),
209
+ signal,
210
+ credentials: "omit",
211
+ cache: "no-store",
212
+ redirect: "error",
213
+ }), signal);
214
+ emitDiagnostic("response_started", { outerStatus: response.status });
215
+ if (response.status === 400) {
216
+ const failure = await readJSON(response, signal);
217
+ if (failure.error === "invalid_grant" ||
218
+ failure.error === "expired" ||
219
+ failure.error === "denied") {
220
+ stopped = new TianaAuthError("AUTH_LOGIN_REQUIRED");
221
+ throw stopped;
222
+ }
223
+ throw new Error("Unknown rotation outcome");
224
+ }
225
+ if (response.status === 401 || response.status === 403) {
226
+ void response.body?.cancel().catch(() => undefined);
227
+ stopped = new TianaAuthError("AUTH_LOGIN_REQUIRED");
228
+ throw stopped;
229
+ }
230
+ if (response.status !== 200 || response.redirected) {
231
+ void response.body?.cancel().catch(() => undefined);
232
+ throw new Error("Unknown rotation outcome");
233
+ }
234
+ body = await readJSON(response, signal);
235
+ if (body.token_type !== "Bearer" ||
236
+ !Number.isSafeInteger(body.expires_in) ||
237
+ body.expires_in <= 0 ||
238
+ typeof body.refresh_expires_at !== "string" ||
239
+ !["pending", "complete", "failed"].includes(body.sync_status))
240
+ throw new Error("Invalid rotation response");
241
+ credentials = copyCredentials({
242
+ accessToken: body.access_token,
243
+ refreshToken: body.refresh_token,
244
+ expiresAt: startedAt + body.expires_in * 1000,
245
+ refreshExpiresAt: Date.parse(body.refresh_expires_at),
246
+ syncStatus: body.sync_status,
247
+ });
248
+ }
249
+ catch {
250
+ stopped ??= new TianaAuthError("AUTH_REFRESH_UNCERTAIN");
251
+ throw stopped;
252
+ }
253
+ completeRequest();
254
+ ready = credentials.syncStatus === "complete";
255
+ savePending = true;
256
+ await persist(signal);
257
+ }
258
+ let pollDelay = pollIntervalMs;
259
+ while (!ready) {
260
+ const requestId = beginRequest();
261
+ const response = await waitFor(transport(`${origin}/api/v1/auth/transactions/whoami`, {
262
+ headers: {
263
+ authorization: `Bearer ${credentials.accessToken}`,
264
+ "x-request-id": requestId,
265
+ "cache-control": "no-store",
266
+ },
267
+ signal,
268
+ credentials: "omit",
269
+ cache: "no-store",
270
+ redirect: "error",
271
+ }), signal);
272
+ emitDiagnostic("response_started", { outerStatus: response.status });
273
+ if (response.status !== 200 || response.redirected) {
274
+ void response.body?.cancel().catch(() => undefined);
275
+ throw new TianaAuthError("AUTH_NOT_READY");
276
+ }
277
+ const body = await readJSON(response, signal);
278
+ if (body.sync_status === "complete") {
279
+ completeRequest();
280
+ ready = true;
281
+ break;
282
+ }
283
+ if (body.sync_status !== "pending")
284
+ throw new TianaAuthError("AUTH_NOT_READY");
285
+ completeRequest();
286
+ await new Promise((resolve, reject) => {
287
+ const onAbort = () => {
288
+ clearTimeout(poll);
289
+ signal.removeEventListener("abort", onAbort);
290
+ reject(new TianaAuthError("AUTH_NOT_READY"));
291
+ };
292
+ const poll = setTimeout(() => {
293
+ signal.removeEventListener("abort", onAbort);
294
+ resolve();
295
+ }, pollDelay);
296
+ signal.addEventListener("abort", onAbort, { once: true });
297
+ if (signal.aborted)
298
+ onAbort();
299
+ });
300
+ pollDelay = Math.min(pollDelay * 2, Math.max(pollIntervalMs, 2000));
301
+ }
302
+ if (credentials.expiresAt <= Date.now())
303
+ throw new TianaAuthError("AUTH_NOT_READY");
304
+ }
305
+ catch (error) {
306
+ const reported = error instanceof TianaAuthError
307
+ ? error
308
+ : new TianaAuthError("AUTH_NOT_READY");
309
+ const phase = signal.aborted ? "cancelled" : "failed";
310
+ if (diagnosticPending) {
311
+ emitDiagnostic(phase, { reason: reported.name });
312
+ diagnosticPending = false;
313
+ }
314
+ if (currentDiagnostic)
315
+ diagnostics.set(reported, {
316
+ ...currentDiagnostic,
317
+ phase,
318
+ reason: reported.name,
319
+ });
320
+ throw reported;
321
+ }
322
+ finally {
323
+ clearTimeout(timer);
324
+ }
325
+ }
326
+ async function persist(signal) {
327
+ if (!saving) {
328
+ const snapshot = copyCredentials(credentials);
329
+ const started = Promise.resolve()
330
+ .then(() => save?.(snapshot))
331
+ .then(() => {
332
+ savePending = false;
333
+ });
334
+ saving = started;
335
+ void started.then(() => {
336
+ saving = undefined;
337
+ }, () => {
338
+ saving = undefined;
339
+ });
340
+ }
341
+ // A timed out save may still finish. Join it on the next call rather than
342
+ // starting a second save or rotating credentials while it is unresolved.
343
+ try {
344
+ await waitFor(saving, signal);
345
+ }
346
+ catch {
347
+ throw new TianaAuthError("AUTH_PERSIST_FAILED");
348
+ }
349
+ }
350
+ return Object.freeze({
351
+ async getAccessToken(input) {
352
+ if (input?.signal?.aborted)
353
+ throw abortReason(input.signal);
354
+ if (stopped)
355
+ throw stopped;
356
+ if (!work &&
357
+ !savePending &&
358
+ ready &&
359
+ credentials.expiresAt > Date.now() + refreshBeforeMs)
360
+ return credentials.accessToken;
361
+ if (!work) {
362
+ const started = Promise.resolve().then(run);
363
+ work = started;
364
+ void started.then(() => {
365
+ work = undefined;
366
+ }, () => {
367
+ work = undefined;
368
+ });
369
+ }
370
+ try {
371
+ await waitFor(work, input?.signal);
372
+ }
373
+ catch (error) {
374
+ // A cancelled waiter is distinct from the shared management request.
375
+ if (input?.signal?.aborted &&
376
+ currentDiagnostic &&
377
+ typeof error === "object" &&
378
+ error !== null) {
379
+ diagnostics.set(error, {
380
+ ...currentDiagnostic,
381
+ phase: "cancelled",
382
+ reason: "AbortError",
383
+ });
384
+ }
385
+ throw error;
386
+ }
387
+ return credentials.accessToken;
388
+ },
389
+ });
390
+ }
391
+ //# sourceMappingURL=auth.js.map