@base44-preview/sdk 0.8.44-pr.264.d98f3ac → 0.8.44-pr.265.8da157e

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.
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The OAuth client id every service-principal token is issued under.
3
+ *
4
+ * Deliberately not one of Base44's MCP client prefixes — a token whose client id
5
+ * starts with one of those is rejected everywhere except `/mcp`.
6
+ */
7
+ export const SERVICE_CLIENT_ID = "svc_delegate";
8
+ /**
9
+ * Re-mint this long before a token's stated expiry.
10
+ *
11
+ * Access tokens are vended with an explicit one-hour lifetime, so this is a few
12
+ * percent of the token's life — enough that a slow call cannot land after the
13
+ * token it was authorized with has expired.
14
+ */
15
+ export const REFRESH_SKEW_MS = 5 * 60 * 1000;
16
+ /**
17
+ * Caches one vended token per principal, and renews it before it lapses.
18
+ *
19
+ * Caching is not an optimization here. Minting is rate-limited **per workspace**,
20
+ * so a platform that mints on every request spends one shared budget on behalf of
21
+ * every user at once and starts failing under exactly the load it was built for.
22
+ * A vended token is good for an hour; this holds it for that hour.
23
+ *
24
+ * @internal
25
+ */
26
+ export function createPrincipalTokenStore({ mintAxios, oauthAxios, refreshSkewMs = REFRESH_SKEW_MS, }) {
27
+ const cache = new Map();
28
+ // One entry per principal currently being fetched. Without this, N concurrent
29
+ // requests for a user whose token just lapsed each fire their own mint — a
30
+ // self-inflicted burst against the very limit the cache exists to respect.
31
+ const inFlight = new Map();
32
+ const toVended = (response) => {
33
+ var _a;
34
+ const lifetimeMs = Math.max(Number(response.expires_in) || 0, 0) * 1000;
35
+ // Never let the skew consume the whole lifetime: a token considered stale on
36
+ // arrival would mint again on the next call, and again, turning the cache
37
+ // into a mint-per-request loop against a shared budget.
38
+ const skew = Math.min(refreshSkewMs, lifetimeMs / 2);
39
+ return {
40
+ accessToken: response.access_token,
41
+ refreshToken: (_a = response.refresh_token) !== null && _a !== void 0 ? _a : undefined,
42
+ expiresAt: Date.now() + lifetimeMs - skew,
43
+ };
44
+ };
45
+ const mint = async (externalId) => {
46
+ const response = await mintAxios.post("/api/service/user-tokens", { service_external_id: externalId });
47
+ return toVended(response);
48
+ };
49
+ const renew = async (refreshToken) => {
50
+ const response = await oauthAxios.post("/oauth/token", new URLSearchParams({
51
+ grant_type: "refresh_token",
52
+ refresh_token: refreshToken,
53
+ client_id: SERVICE_CLIENT_ID,
54
+ }), { headers: { "Content-Type": "application/x-www-form-urlencoded" } });
55
+ return toVended(response);
56
+ };
57
+ const fetchToken = async (externalId) => {
58
+ const held = cache.get(externalId);
59
+ if (held === null || held === void 0 ? void 0 : held.refreshToken) {
60
+ try {
61
+ return await renew(held.refreshToken);
62
+ }
63
+ catch (_a) {
64
+ // A refresh token can be revoked, expired, or invalidated by a role
65
+ // change. Minting is the recovery, and it re-checks everything the
66
+ // refresh would have — so falling through is not a way around a
67
+ // revocation, it just costs one extra round trip.
68
+ }
69
+ }
70
+ return mint(externalId);
71
+ };
72
+ return {
73
+ /**
74
+ * A currently-valid token for the principal, minting or renewing only when
75
+ * the held one is spent.
76
+ */
77
+ async get(externalId) {
78
+ const held = cache.get(externalId);
79
+ if (held && held.expiresAt > Date.now())
80
+ return held;
81
+ const pending = inFlight.get(externalId);
82
+ if (pending)
83
+ return pending;
84
+ const request = fetchToken(externalId)
85
+ .then((token) => {
86
+ cache.set(externalId, token);
87
+ return token;
88
+ })
89
+ .finally(() => {
90
+ inFlight.delete(externalId);
91
+ });
92
+ inFlight.set(externalId, request);
93
+ return request;
94
+ },
95
+ /**
96
+ * Drops the held token and asks Base44 to revoke its refresh token.
97
+ *
98
+ * Only the refresh half is revocable — the access token is self-contained and
99
+ * stays valid until it expires. To cut a principal off *now*, deprovision it:
100
+ * the workspace membership is re-checked on every request.
101
+ */
102
+ async revoke(externalId) {
103
+ const held = cache.get(externalId);
104
+ cache.delete(externalId);
105
+ if (!(held === null || held === void 0 ? void 0 : held.refreshToken))
106
+ return;
107
+ // Best effort: a failed revoke must not leave a caller unable to forget a
108
+ // principal locally.
109
+ try {
110
+ await oauthAxios.post("/oauth/revoke", new URLSearchParams({
111
+ token: held.refreshToken,
112
+ client_id: SERVICE_CLIENT_ID,
113
+ }), { headers: { "Content-Type": "application/x-www-form-urlencoded" } });
114
+ }
115
+ catch (_a) {
116
+ /* the local record is already gone, which is the part that matters */
117
+ }
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A Server-Sent Events reader over `fetch`.
3
+ *
4
+ * The SDK's first streaming transport, and deliberately not `EventSource`.
5
+ * `EventSource` cannot set request headers, which is why the build API also
6
+ * accepts a single-use ticket in the query string — a workaround for a browser
7
+ * limitation, not a shape to build on. Reading the stream with `fetch` lets the
8
+ * credential stay in an `Authorization` header, where it does not land in
9
+ * referrers, proxy logs or browser history, and the ticket exchange never has to
10
+ * happen. `fetch` with a streaming body works in browsers, Node 18+, Deno and
11
+ * Bun; `EventSource` is browser-only.
12
+ *
13
+ * @internal
14
+ */
15
+ /** One dispatched SSE event. */
16
+ export interface SseFrame {
17
+ /** The `id:` field — the resume cursor a client echoes back as `Last-Event-ID`. */
18
+ id?: string;
19
+ /** The `event:` field, naming the event type. */
20
+ event?: string;
21
+ /** The `data:` field. Multiple `data:` lines are joined with newlines, per spec. */
22
+ data: string;
23
+ }
24
+ /**
25
+ * Yields SSE frames from a fetch response body until the stream ends.
26
+ *
27
+ * @param stream - The response body.
28
+ * @returns Each dispatched event, in order.
29
+ * @internal
30
+ */
31
+ export declare function readSseFrames(stream: ReadableStream<Uint8Array>): AsyncGenerator<SseFrame, void, undefined>;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * A Server-Sent Events reader over `fetch`.
3
+ *
4
+ * The SDK's first streaming transport, and deliberately not `EventSource`.
5
+ * `EventSource` cannot set request headers, which is why the build API also
6
+ * accepts a single-use ticket in the query string — a workaround for a browser
7
+ * limitation, not a shape to build on. Reading the stream with `fetch` lets the
8
+ * credential stay in an `Authorization` header, where it does not land in
9
+ * referrers, proxy logs or browser history, and the ticket exchange never has to
10
+ * happen. `fetch` with a streaming body works in browsers, Node 18+, Deno and
11
+ * Bun; `EventSource` is browser-only.
12
+ *
13
+ * @internal
14
+ */
15
+ // A blank line ends an event. Any of the three terminators the spec allows may
16
+ // arrive, and a CRLF can be split across two network chunks — matching on the
17
+ // accumulated buffer rather than per chunk is what makes that harmless.
18
+ const FRAME_BOUNDARY = /\r\n\r\n|\n\n|\r\r/;
19
+ const LINE_BREAK = /\r\n|\n|\r/;
20
+ function parseFrame(block) {
21
+ const data = [];
22
+ let id;
23
+ let event;
24
+ for (const line of block.split(LINE_BREAK)) {
25
+ // A line starting with a colon is a comment. That is what a keepalive is,
26
+ // so this is the branch that keeps an idle build from looking like an event.
27
+ if (!line || line.startsWith(":"))
28
+ continue;
29
+ const separator = line.indexOf(":");
30
+ const field = separator === -1 ? line : line.slice(0, separator);
31
+ let value = separator === -1 ? "" : line.slice(separator + 1);
32
+ if (value.startsWith(" "))
33
+ value = value.slice(1);
34
+ if (field === "data")
35
+ data.push(value);
36
+ else if (field === "event")
37
+ event = value;
38
+ else if (field === "id")
39
+ id = value;
40
+ }
41
+ // No payload, nothing to dispatch. The build stream always sends `data:`, so
42
+ // this only drops frames that carry a bare `id:` or an unknown field.
43
+ return data.length ? { id, event, data: data.join("\n") } : null;
44
+ }
45
+ /**
46
+ * Yields SSE frames from a fetch response body until the stream ends.
47
+ *
48
+ * @param stream - The response body.
49
+ * @returns Each dispatched event, in order.
50
+ * @internal
51
+ */
52
+ export async function* readSseFrames(stream) {
53
+ const reader = stream.getReader();
54
+ const decoder = new TextDecoder();
55
+ let buffer = "";
56
+ try {
57
+ for (;;) {
58
+ const { done, value } = await reader.read();
59
+ if (done)
60
+ break;
61
+ buffer += decoder.decode(value, { stream: true });
62
+ for (;;) {
63
+ const match = FRAME_BOUNDARY.exec(buffer);
64
+ if (!match)
65
+ break;
66
+ const block = buffer.slice(0, match.index);
67
+ buffer = buffer.slice(match.index + match[0].length);
68
+ const frame = parseFrame(block);
69
+ if (frame)
70
+ yield frame;
71
+ }
72
+ }
73
+ }
74
+ finally {
75
+ // Abandoning the iterator mid-stream (a `break` in the consumer, or an
76
+ // unsubscribe) has to release the underlying connection, or a long-lived
77
+ // process leaks one socket per build it stopped watching.
78
+ await reader.cancel().catch(() => { });
79
+ }
80
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.44-pr.264.d98f3ac",
3
+ "version": "0.8.44-pr.265.8da157e",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",