@tangle-network/agent-runtime 0.314.1 → 0.316.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/README.md +6 -0
- package/dist/{activation-BpMnOlw5.d.ts → activation-BFDmjaKP.d.ts} +2 -2
- package/dist/{activation-Ci20OAsG.js → activation-CvdE2HIU.js} +3 -3
- package/dist/{activation-Ci20OAsG.js.map → activation-CvdE2HIU.js.map} +1 -1
- package/dist/agent.d.ts +2 -1
- package/dist/agent.js +2 -2
- package/dist/{bundle-BK3XBY6q.js → bundle-RgHpAFDY.js} +2 -2
- package/dist/{bundle-BK3XBY6q.js.map → bundle-RgHpAFDY.js.map} +1 -1
- package/dist/candidate-execution/index.js +5 -5
- package/dist/{coordination-driver-CyJF37L8.js → coordination-driver-DGhN8GO9.js} +3 -3
- package/dist/{coordination-driver-CyJF37L8.js.map → coordination-driver-DGhN8GO9.js.map} +1 -1
- package/dist/{delegate-CTezpiM2.js → delegate-B5pmSbQa.js} +2 -2
- package/dist/{delegate-CTezpiM2.js.map → delegate-B5pmSbQa.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +4 -4
- package/dist/{graph-DGDrO_ZW.js → graph-G0j1ysqe.js} +4 -4
- package/dist/{graph-DGDrO_ZW.js.map → graph-G0j1ysqe.js.map} +1 -1
- package/dist/{improvement-cycle-DReg-Qi4.js → improvement-cycle-D7yR6GC2.js} +6 -6
- package/dist/{improvement-cycle-DReg-Qi4.js.map → improvement-cycle-D7yR6GC2.js.map} +1 -1
- package/dist/{index-B89bMKhD.d.ts → index-CUh40yUJ.d.ts} +13 -90
- package/dist/index.d.ts +4 -4
- package/dist/index.js +9 -9
- package/dist/integrations-DopfCC2a.d.ts +190 -0
- package/dist/integrations-dFi-ALk7.js +132 -0
- package/dist/integrations-dFi-ALk7.js.map +1 -0
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +7 -7
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +9 -9
- package/dist/{loop-runner-bin-eoycPwY3.js → loop-runner-bin-CFVX4oi0.js} +3 -3
- package/dist/{loop-runner-bin-eoycPwY3.js.map → loop-runner-bin-CFVX4oi0.js.map} +1 -1
- package/dist/{loop-runner-bin-BM1in-RT.d.ts → loop-runner-bin-DQKLUt0l.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +74 -33
- package/dist/mcp/index.js +129 -6
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-xPO6dzf4.d.ts → openai-tools-u3gWBi3x.d.ts} +2 -2
- package/dist/placement.d.ts +132 -0
- package/dist/placement.js +319 -0
- package/dist/placement.js.map +1 -0
- package/dist/platform.d.ts +1 -188
- package/dist/platform.js +1 -129
- package/dist/platform.js.map +1 -1
- package/dist/{prepare-8A1CAWG8.js → prepare-CD9kR0gS.js} +3 -3
- package/dist/{prepare-8A1CAWG8.js.map → prepare-CD9kR0gS.js.map} +1 -1
- package/dist/{profile-BhQShsM1.js → profile-CHXYmpGd.js} +2 -2
- package/dist/{profile-BhQShsM1.js.map → profile-CHXYmpGd.js.map} +1 -1
- package/dist/profile-materialization-Cca615eu.d.ts +90 -0
- package/dist/profiles.d.ts +1 -1
- package/dist/{protected-model-port-ug52OmvB.js → protected-model-port-B0pHd65J.js} +4 -4
- package/dist/{protected-model-port-ug52OmvB.js.map → protected-model-port-B0pHd65J.js.map} +1 -1
- package/dist/{provision-supervisor-B6D3XRbL.js → provision-supervisor-BQLLrUtn.js} +4 -4
- package/dist/{provision-supervisor-B6D3XRbL.js.map → provision-supervisor-BQLLrUtn.js.map} +1 -1
- package/dist/{runtime-NlIVxRXu.js → runtime-B9BOFyEp.js} +10 -9
- package/dist/runtime-B9BOFyEp.js.map +1 -0
- package/dist/{search-executor-DFs-79tK.js → search-executor-B5ZVFsDV.js} +3 -3
- package/dist/{search-executor-DFs-79tK.js.map → search-executor-B5ZVFsDV.js.map} +1 -1
- package/dist/{server-B8ubWXpW.js → server-TwpH9aik.js} +4 -4
- package/dist/{server-B8ubWXpW.js.map → server-TwpH9aik.js.map} +1 -1
- package/dist/{supervise-BE9ta8bl.js → supervise-CU6AuxWY.js} +119 -29
- package/dist/supervise-CU6AuxWY.js.map +1 -0
- package/dist/{supervisor-DmSuKksw.js → supervisor-CbFyf48U.js} +3 -3
- package/dist/{supervisor-DmSuKksw.js.map → supervisor-CbFyf48U.js.map} +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +14 -14
- package/dist/tool-loop.d.ts +35 -5
- package/dist/tool-loop.js +48 -21
- package/dist/tool-loop.js.map +1 -1
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/workspace-store/index.d.ts +206 -0
- package/dist/workspace-store/index.js +855 -0
- package/dist/workspace-store/index.js.map +1 -0
- package/dist/{workspace-streams-BEvSX97P.js → workspace-streams-DkijayqX.js} +16 -3
- package/dist/workspace-streams-DkijayqX.js.map +1 -0
- package/package.json +14 -4
- package/skills/profile-authoring/SKILL.md +114 -171
- package/dist/runtime-NlIVxRXu.js.map +0 -1
- package/dist/supervise-BE9ta8bl.js.map +0 -1
- package/dist/workspace-streams-BEvSX97P.js.map +0 -1
package/dist/platform.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { a as HealthCheck, c as PlatformCatalogProvider, d as PlatformHubClientOptions, f as PlatformHubError, h as StartAuthResult, i as ExecInput, l as PlatformConnection, m as StartAuthInput, n as ConnectionHealth, o as MintTokenInput, p as PlatformHubStatus, r as ConnectionHealthResult, s as MintTokenResult, t as CatalogResult, u as PlatformHubClient } from "./integrations-DopfCC2a.js";
|
|
1
2
|
//#region src/platform/auth.d.ts
|
|
2
3
|
/**
|
|
3
4
|
* Server-side client for the Tangle platform's cross-site SSO bridge.
|
|
@@ -72,194 +73,6 @@ declare class PlatformAuthClient {
|
|
|
72
73
|
exchange(code: string): Promise<ExchangeCodeResult>;
|
|
73
74
|
}
|
|
74
75
|
//#endregion
|
|
75
|
-
//#region src/platform/integrations.d.ts
|
|
76
|
-
/**
|
|
77
|
-
* Server-side client for the Tangle platform's integration hub
|
|
78
|
-
* (`/v1/hub/*`). Consumer apps use this instead of rolling their own
|
|
79
|
-
* OAuth + connection tables.
|
|
80
|
-
*
|
|
81
|
-
* Auth: the caller supplies a bearer (either the user's API key from
|
|
82
|
-
* cross-site exchange, or a platform service token) on construction.
|
|
83
|
-
*
|
|
84
|
-
* Endpoint contract (authoritative): the platform's `src/lib/hub-contract.ts`
|
|
85
|
-
* + `src/routes/hub.ts`. The platform wraps every response in
|
|
86
|
-
* `{ success, data }`; non-2xx or `success:false` surfaces as `PlatformHubError`
|
|
87
|
-
* carrying the real upstream status.
|
|
88
|
-
*/
|
|
89
|
-
interface PlatformHubClientOptions {
|
|
90
|
-
/** Platform base URL, e.g. `https://id.tangle.tools`. */
|
|
91
|
-
baseUrl: string;
|
|
92
|
-
/** Bearer credential — user API key or service token. */
|
|
93
|
-
bearer: string;
|
|
94
|
-
/** Override fetch (tests + edge runtimes). */
|
|
95
|
-
fetchImpl?: typeof fetch;
|
|
96
|
-
}
|
|
97
|
-
/** A live integration connection, as returned by `/v1/hub/connections`. */
|
|
98
|
-
interface PlatformConnection {
|
|
99
|
-
id: string;
|
|
100
|
-
providerId: string;
|
|
101
|
-
displayName: string;
|
|
102
|
-
accountDisplay: string | null;
|
|
103
|
-
scopes: string[];
|
|
104
|
-
status: 'active' | 'revoked' | 'unhealthy' | 'reconnect_required' | (string & {});
|
|
105
|
-
health: 'unknown' | 'healthy' | 'unhealthy' | 'rate_limited' | (string & {});
|
|
106
|
-
createdAt: string;
|
|
107
|
-
updatedAt: string;
|
|
108
|
-
lastUsedAt: string | null;
|
|
109
|
-
}
|
|
110
|
-
/** A connectable provider in the catalog (`/v1/hub/providers`). */
|
|
111
|
-
interface PlatformCatalogProvider {
|
|
112
|
-
providerId: string;
|
|
113
|
-
title?: string;
|
|
114
|
-
authKind?: string;
|
|
115
|
-
category?: string;
|
|
116
|
-
scopes?: string[];
|
|
117
|
-
capabilityCount?: number;
|
|
118
|
-
native?: boolean;
|
|
119
|
-
/** Whether the OAuth app's credentials are wired — the UI offers Connect
|
|
120
|
-
* only when true. */
|
|
121
|
-
configured?: boolean;
|
|
122
|
-
[k: string]: unknown;
|
|
123
|
-
}
|
|
124
|
-
interface CatalogResult {
|
|
125
|
-
providers: PlatformCatalogProvider[];
|
|
126
|
-
/** Count of substrate-bundled connectors behind the catalog. */
|
|
127
|
-
substrateBundled?: number;
|
|
128
|
-
[k: string]: unknown;
|
|
129
|
-
}
|
|
130
|
-
interface StartAuthInput {
|
|
131
|
-
/** The provider to connect (goes in the URL path). */
|
|
132
|
-
providerId: string;
|
|
133
|
-
/** Accepted for interface compatibility; the platform's start endpoint is
|
|
134
|
-
* provider-level and does not consume a connector id. */
|
|
135
|
-
connectorId?: string;
|
|
136
|
-
/** Where the platform redirects the user back to after OAuth. */
|
|
137
|
-
returnUrl: string;
|
|
138
|
-
/** Accepted for interface compatibility; not consumed by the start endpoint. */
|
|
139
|
-
requestedScopes?: string[];
|
|
140
|
-
/** CLI flow flag — affects the platform's post-auth redirect handling. */
|
|
141
|
-
cli?: boolean;
|
|
142
|
-
}
|
|
143
|
-
interface StartAuthResult {
|
|
144
|
-
/** The URL to send the user to. Normalized across the platform's two start
|
|
145
|
-
* branches: github returns `authorizationUrl`, substrate returns
|
|
146
|
-
* `redirectUrl`. */
|
|
147
|
-
authorizationUrl: string;
|
|
148
|
-
state: string;
|
|
149
|
-
expiresAt?: string;
|
|
150
|
-
scopes?: string[];
|
|
151
|
-
}
|
|
152
|
-
interface ConnectionHealth {
|
|
153
|
-
status: 'unknown' | 'healthy' | 'unhealthy' | 'rate_limited' | (string & {});
|
|
154
|
-
checkedAt: string;
|
|
155
|
-
error?: {
|
|
156
|
-
code: string;
|
|
157
|
-
message: string;
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
interface ConnectionHealthResult {
|
|
161
|
-
connection: PlatformConnection;
|
|
162
|
-
health: ConnectionHealth;
|
|
163
|
-
}
|
|
164
|
-
/** Last-known health for a connection, derived from the connection row. */
|
|
165
|
-
interface HealthCheck {
|
|
166
|
-
connectionId: string;
|
|
167
|
-
providerId: string;
|
|
168
|
-
/** Mirrors `PlatformConnection.health`. */
|
|
169
|
-
status: ConnectionHealth['status'];
|
|
170
|
-
checkedAt?: string;
|
|
171
|
-
}
|
|
172
|
-
interface MintTokenInput {
|
|
173
|
-
/** The hub action the token authorizes (e.g. `slack.chat.postMessage`). */
|
|
174
|
-
actionPath: string;
|
|
175
|
-
/** Bind to a specific connection, or … */
|
|
176
|
-
connectionId?: string;
|
|
177
|
-
/** … resolve the connection by provider for the calling user. */
|
|
178
|
-
provider?: string;
|
|
179
|
-
}
|
|
180
|
-
interface MintTokenResult {
|
|
181
|
-
tokenId: string;
|
|
182
|
-
token: string;
|
|
183
|
-
expiresAt: string;
|
|
184
|
-
}
|
|
185
|
-
interface ExecInput {
|
|
186
|
-
/** The hub action path to execute. */
|
|
187
|
-
path: string;
|
|
188
|
-
input?: unknown;
|
|
189
|
-
connectionId?: string;
|
|
190
|
-
}
|
|
191
|
-
interface PlatformHubStatus {
|
|
192
|
-
contract?: unknown;
|
|
193
|
-
principal: {
|
|
194
|
-
kind: string;
|
|
195
|
-
userId: string;
|
|
196
|
-
[k: string]: unknown;
|
|
197
|
-
};
|
|
198
|
-
connections: {
|
|
199
|
-
connectedProviderCount: number;
|
|
200
|
-
unhealthyProviderCount: number;
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
/** Thrown when a `PlatformHubClient` request returns a non-success status. */
|
|
204
|
-
declare class PlatformHubError extends Error {
|
|
205
|
-
readonly status: number;
|
|
206
|
-
readonly code: string | undefined;
|
|
207
|
-
readonly body: unknown;
|
|
208
|
-
constructor(message: string, status: number, code: string | undefined, body: unknown);
|
|
209
|
-
}
|
|
210
|
-
/** HTTP client for the Tangle Platform Hub API: provider catalog, connection flow, and status. */
|
|
211
|
-
declare class PlatformHubClient {
|
|
212
|
-
private readonly baseUrl;
|
|
213
|
-
private readonly bearer;
|
|
214
|
-
private readonly fetchImpl;
|
|
215
|
-
constructor(options: PlatformHubClientOptions);
|
|
216
|
-
/** GET /v1/hub/providers — the connectable provider catalog. */
|
|
217
|
-
catalog(): Promise<CatalogResult>;
|
|
218
|
-
/** GET /v1/hub/connections — the calling user's live connections. */
|
|
219
|
-
listConnections(): Promise<PlatformConnection[]>;
|
|
220
|
-
/** DELETE /v1/hub/connections/:connectionId — revoke + disable a connection. */
|
|
221
|
-
revokeConnection(connectionId: string): Promise<{
|
|
222
|
-
connection: PlatformConnection;
|
|
223
|
-
}>;
|
|
224
|
-
/**
|
|
225
|
-
* POST /v1/hub/connections/:provider/start — begin OAuth/grant. The provider
|
|
226
|
-
* is taken from the URL; the body carries `returnUrl` (+ `cli`). The platform's
|
|
227
|
-
* two start branches name the URL field differently (github → `authorizationUrl`,
|
|
228
|
-
* substrate → `redirectUrl`); this normalizes to `authorizationUrl`.
|
|
229
|
-
*/
|
|
230
|
-
startAuth(input: StartAuthInput): Promise<StartAuthResult>;
|
|
231
|
-
/**
|
|
232
|
-
* Last-known health for every connection. The platform has no global
|
|
233
|
-
* healthcheck listing — health rides on each connection row — so this derives
|
|
234
|
-
* the list from `listConnections()` (one request, no extra round-trips).
|
|
235
|
-
*/
|
|
236
|
-
listHealthchecks(): Promise<HealthCheck[]>;
|
|
237
|
-
/**
|
|
238
|
-
* POST /v1/hub/connections/:connectionId/health — trigger a fresh health
|
|
239
|
-
* probe for one connection and return its updated state.
|
|
240
|
-
*/
|
|
241
|
-
checkConnectionHealth(connectionId: string): Promise<ConnectionHealthResult>;
|
|
242
|
-
/**
|
|
243
|
-
* Trigger a fresh health probe across all of the user's connections. The
|
|
244
|
-
* platform exposes health per-connection only, so this fans out over
|
|
245
|
-
* `listConnections()`. `scheduled` is the number of probes dispatched.
|
|
246
|
-
*/
|
|
247
|
-
runHealthchecks(): Promise<{
|
|
248
|
-
scheduled: number;
|
|
249
|
-
}>;
|
|
250
|
-
/** GET /v1/hub/status — principal + aggregate connection counts. */
|
|
251
|
-
status(): Promise<PlatformHubStatus>;
|
|
252
|
-
/**
|
|
253
|
-
* POST /v1/hub/tokens — mint a short-lived, action-scoped capability token a
|
|
254
|
-
* sandbox can use to invoke one hub action on the user's behalf without
|
|
255
|
-
* seeing the underlying provider credential.
|
|
256
|
-
*/
|
|
257
|
-
mintToken(input: MintTokenInput): Promise<MintTokenResult>;
|
|
258
|
-
/** POST /v1/hub/exec — execute a hub action and return its result. */
|
|
259
|
-
exec(input: ExecInput): Promise<unknown>;
|
|
260
|
-
private request;
|
|
261
|
-
}
|
|
262
|
-
//#endregion
|
|
263
76
|
//#region src/platform/oidc.d.ts
|
|
264
77
|
interface PlatformOidcClientOptions {
|
|
265
78
|
baseUrl: string;
|
package/dist/platform.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { n as PlatformHubError, t as PlatformHubClient } from "./integrations-dFi-ALk7.js";
|
|
1
2
|
//#region src/platform/auth.ts
|
|
2
3
|
/** Thrown when a `PlatformAuthClient` request returns a non-success status. */
|
|
3
4
|
var PlatformAuthError = class extends Error {
|
|
@@ -91,135 +92,6 @@ var PlatformAuthClient = class {
|
|
|
91
92
|
}
|
|
92
93
|
};
|
|
93
94
|
//#endregion
|
|
94
|
-
//#region src/platform/integrations.ts
|
|
95
|
-
/** Thrown when a `PlatformHubClient` request returns a non-success status. */
|
|
96
|
-
var PlatformHubError = class extends Error {
|
|
97
|
-
status;
|
|
98
|
-
code;
|
|
99
|
-
body;
|
|
100
|
-
constructor(message, status, code, body) {
|
|
101
|
-
super(message);
|
|
102
|
-
this.status = status;
|
|
103
|
-
this.code = code;
|
|
104
|
-
this.body = body;
|
|
105
|
-
this.name = "PlatformHubError";
|
|
106
|
-
}
|
|
107
|
-
};
|
|
108
|
-
/** HTTP client for the Tangle Platform Hub API: provider catalog, connection flow, and status. */
|
|
109
|
-
var PlatformHubClient = class {
|
|
110
|
-
baseUrl;
|
|
111
|
-
bearer;
|
|
112
|
-
fetchImpl;
|
|
113
|
-
constructor(options) {
|
|
114
|
-
if (!options.baseUrl) throw new Error("PlatformHubClient: baseUrl is required");
|
|
115
|
-
if (!options.bearer) throw new Error("PlatformHubClient: bearer is required");
|
|
116
|
-
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
117
|
-
this.bearer = options.bearer;
|
|
118
|
-
this.fetchImpl = options.fetchImpl ?? ((url, init) => fetch(url, init));
|
|
119
|
-
}
|
|
120
|
-
/** GET /v1/hub/providers — the connectable provider catalog. */
|
|
121
|
-
catalog() {
|
|
122
|
-
return this.request("GET", "/v1/hub/providers");
|
|
123
|
-
}
|
|
124
|
-
/** GET /v1/hub/connections — the calling user's live connections. */
|
|
125
|
-
async listConnections() {
|
|
126
|
-
return (await this.request("GET", "/v1/hub/connections")).connections;
|
|
127
|
-
}
|
|
128
|
-
/** DELETE /v1/hub/connections/:connectionId — revoke + disable a connection. */
|
|
129
|
-
revokeConnection(connectionId) {
|
|
130
|
-
return this.request("DELETE", `/v1/hub/connections/${encodeURIComponent(connectionId)}`);
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* POST /v1/hub/connections/:provider/start — begin OAuth/grant. The provider
|
|
134
|
-
* is taken from the URL; the body carries `returnUrl` (+ `cli`). The platform's
|
|
135
|
-
* two start branches name the URL field differently (github → `authorizationUrl`,
|
|
136
|
-
* substrate → `redirectUrl`); this normalizes to `authorizationUrl`.
|
|
137
|
-
*/
|
|
138
|
-
async startAuth(input) {
|
|
139
|
-
const body = { returnUrl: input.returnUrl };
|
|
140
|
-
if (input.cli !== void 0) body.cli = input.cli;
|
|
141
|
-
const data = await this.request("POST", `/v1/hub/connections/${encodeURIComponent(input.providerId)}/start`, body);
|
|
142
|
-
const authorizationUrl = data.authorizationUrl ?? data.redirectUrl;
|
|
143
|
-
if (!authorizationUrl) throw new PlatformHubError("Platform hub start response missing an authorization URL", 502, "HUB_INVALID_START_RESPONSE", data);
|
|
144
|
-
return {
|
|
145
|
-
authorizationUrl,
|
|
146
|
-
state: data.state,
|
|
147
|
-
expiresAt: data.expiresAt,
|
|
148
|
-
scopes: data.scopes
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Last-known health for every connection. The platform has no global
|
|
153
|
-
* healthcheck listing — health rides on each connection row — so this derives
|
|
154
|
-
* the list from `listConnections()` (one request, no extra round-trips).
|
|
155
|
-
*/
|
|
156
|
-
async listHealthchecks() {
|
|
157
|
-
return (await this.listConnections()).map((c) => ({
|
|
158
|
-
connectionId: c.id,
|
|
159
|
-
providerId: c.providerId,
|
|
160
|
-
status: c.health,
|
|
161
|
-
checkedAt: c.updatedAt
|
|
162
|
-
}));
|
|
163
|
-
}
|
|
164
|
-
/**
|
|
165
|
-
* POST /v1/hub/connections/:connectionId/health — trigger a fresh health
|
|
166
|
-
* probe for one connection and return its updated state.
|
|
167
|
-
*/
|
|
168
|
-
checkConnectionHealth(connectionId) {
|
|
169
|
-
return this.request("POST", `/v1/hub/connections/${encodeURIComponent(connectionId)}/health`);
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Trigger a fresh health probe across all of the user's connections. The
|
|
173
|
-
* platform exposes health per-connection only, so this fans out over
|
|
174
|
-
* `listConnections()`. `scheduled` is the number of probes dispatched.
|
|
175
|
-
*/
|
|
176
|
-
async runHealthchecks() {
|
|
177
|
-
const connections = await this.listConnections();
|
|
178
|
-
await Promise.allSettled(connections.map((c) => this.checkConnectionHealth(c.id)));
|
|
179
|
-
return { scheduled: connections.length };
|
|
180
|
-
}
|
|
181
|
-
/** GET /v1/hub/status — principal + aggregate connection counts. */
|
|
182
|
-
status() {
|
|
183
|
-
return this.request("GET", "/v1/hub/status");
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* POST /v1/hub/tokens — mint a short-lived, action-scoped capability token a
|
|
187
|
-
* sandbox can use to invoke one hub action on the user's behalf without
|
|
188
|
-
* seeing the underlying provider credential.
|
|
189
|
-
*/
|
|
190
|
-
mintToken(input) {
|
|
191
|
-
return this.request("POST", "/v1/hub/tokens", input);
|
|
192
|
-
}
|
|
193
|
-
/** POST /v1/hub/exec — execute a hub action and return its result. */
|
|
194
|
-
async exec(input) {
|
|
195
|
-
return (await this.request("POST", "/v1/hub/exec", input)).result;
|
|
196
|
-
}
|
|
197
|
-
async request(method, path, body) {
|
|
198
|
-
const headers = {
|
|
199
|
-
authorization: `Bearer ${this.bearer}`,
|
|
200
|
-
accept: "application/json"
|
|
201
|
-
};
|
|
202
|
-
if (body !== void 0) headers["content-type"] = "application/json";
|
|
203
|
-
const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
204
|
-
method,
|
|
205
|
-
headers,
|
|
206
|
-
body: body !== void 0 ? JSON.stringify(body) : void 0
|
|
207
|
-
});
|
|
208
|
-
const text = await res.text();
|
|
209
|
-
let parsed = null;
|
|
210
|
-
if (text) try {
|
|
211
|
-
parsed = JSON.parse(text);
|
|
212
|
-
} catch {}
|
|
213
|
-
if (!res.ok || parsed && parsed.success === false) {
|
|
214
|
-
const code = parsed?.error && typeof parsed.error === "object" ? parsed.error.code : void 0;
|
|
215
|
-
throw new PlatformHubError(parsed?.error && typeof parsed.error === "object" && parsed.error.message || (typeof parsed?.error === "string" ? parsed.error : `Platform hub error (${res.status})`), res.status, code, parsed ?? text);
|
|
216
|
-
}
|
|
217
|
-
if (!parsed) throw new PlatformHubError(`Platform hub returned non-JSON success (${res.status})`, res.status, void 0, text);
|
|
218
|
-
if (parsed.data === void 0) throw new PlatformHubError("Platform hub envelope missing `data`", res.status, void 0, parsed);
|
|
219
|
-
return parsed.data;
|
|
220
|
-
}
|
|
221
|
-
};
|
|
222
|
-
//#endregion
|
|
223
95
|
//#region src/platform/oidc.ts
|
|
224
96
|
/**
|
|
225
97
|
* OpenID Connect client for the Tangle authorization server. Identity tokens
|
package/dist/platform.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform.js","names":["isRecord","isNonemptyString"],"sources":["../src/platform/auth.ts","../src/platform/integrations.ts","../src/platform/oidc.ts"],"sourcesContent":["/**\n * Server-side client for the Tangle platform's cross-site SSO bridge.\n *\n * Consumer apps (gtm-agent, tax-agent, legal-agent, creative-agent, …)\n * use this to:\n * 1. Build an /authorize URL that lands the user on id.tangle.tools\n * and brings them back with a single-use code.\n * 2. Exchange that code for an API key + the user's identity.\n *\n * The platform endpoint contract is documented in\n * `products/platform/api/src/routes/cross-site.ts`. This client only\n * speaks HTTP — no SDK weight, no transitive deps.\n */\n\nexport interface PlatformAuthClientOptions {\n /** Platform base URL, e.g. `https://id.tangle.tools`. */\n baseUrl: string\n /** App id as registered in the platform's TRUSTED_APPS registry. */\n appId: string\n /** Override the global fetch (useful for tests + edge runtimes). */\n fetchImpl?: typeof fetch\n}\n\nexport interface AuthorizeUrlOptions {\n /** Required CSRF token; the consumer verifies it on the callback. */\n state: string\n /**\n * Final redirect URI. Must be one of the URIs registered for `appId`\n * on the platform. Omit to use the first registered URI.\n */\n redirectUri?: string\n /** Force the login screen even if a session is already active. */\n prompt?: 'login'\n /** Pre-fill the email field on the login screen. */\n email?: string\n}\n\nexport interface ExchangeCodeResult {\n apiKey: string\n emailVerified: true\n user: {\n id: string\n email: string\n name?: string | null\n }\n /** Null when the platform could not provide a subscription. This is not a paid-access grant. */\n plan: {\n tier: string\n } | null\n}\n\n/** Thrown when a `PlatformAuthClient` request returns a non-success status. */\nexport class PlatformAuthError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: unknown,\n ) {\n super(message)\n this.name = 'PlatformAuthError'\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isNonemptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\n/** Validate the platform's verified identity before consumers create a local session. */\nfunction parseExchangeResult(body: unknown, status: number): ExchangeCodeResult {\n const invalid = (): never => {\n // A successful but malformed response can contain the one-time API secret.\n throw new PlatformAuthError(\n 'Platform exchange response has no valid verified identity',\n status,\n { code: 'INVALID_EXCHANGE_RESPONSE' },\n )\n }\n if (\n !isRecord(body) ||\n !isNonemptyString(body.apiKey) ||\n body.emailVerified !== true ||\n !isRecord(body.user)\n )\n return invalid()\n const user = body.user\n if (!isNonemptyString(user.id) || !isNonemptyString(user.email)) return invalid()\n const email = user.email.trim()\n if (\n email.length > 320 ||\n !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ||\n /(?:@users\\.noreply\\.tangle\\.tools$|^0x[a-f0-9]{40}@tangle\\.tools$)/i.test(email)\n )\n return invalid()\n if (user.name !== undefined && user.name !== null && typeof user.name !== 'string')\n return invalid()\n let plan: ExchangeCodeResult['plan'] = null\n if (body.subscription !== undefined) {\n if (!isRecord(body.subscription) || !isNonemptyString(body.subscription.plan)) return invalid()\n plan = { tier: body.subscription.plan }\n }\n return {\n apiKey: body.apiKey,\n emailVerified: true,\n user: { id: user.id, email, ...(user.name !== undefined ? { name: user.name } : {}) },\n plan,\n }\n}\n\n/** HTTP client for the Tangle Platform SSO: builds authorize URLs and exchanges auth codes for API keys. */\nexport class PlatformAuthClient {\n private readonly baseUrl: string\n private readonly appId: string\n private readonly fetchImpl: typeof fetch\n\n constructor(options: PlatformAuthClientOptions) {\n if (!options.baseUrl) throw new Error('PlatformAuthClient: baseUrl is required')\n if (!options.appId) throw new Error('PlatformAuthClient: appId is required')\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.appId = options.appId\n this.fetchImpl =\n options.fetchImpl ??\n ((url: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => fetch(url, init))\n }\n\n /**\n * Build the URL the user is redirected to in order to start SSO.\n * The platform redirects back to one of `appId`'s registered\n * `redirectUris` with `?code=...&app=...&state=...`.\n */\n authorizeUrl(options: AuthorizeUrlOptions): string {\n if (!options.state) {\n throw new Error('PlatformAuthClient.authorizeUrl: state is required for CSRF')\n }\n const url = new URL('/cross-site/authorize', this.baseUrl)\n url.searchParams.set('app', this.appId)\n url.searchParams.set('state', options.state)\n if (options.redirectUri) url.searchParams.set('redirect', options.redirectUri)\n if (options.prompt) url.searchParams.set('prompt', options.prompt)\n if (options.email) url.searchParams.set('email', options.email)\n return url.toString()\n }\n\n /**\n * Exchange a single-use auth code (delivered to the consumer's\n * callback by the platform) for an API key + the user's identity.\n * Codes are single-use and expire ~5 minutes after issue.\n */\n async exchange(code: string): Promise<ExchangeCodeResult> {\n if (!code) throw new Error('PlatformAuthClient.exchange: code is required')\n const res = await this.fetchImpl(`${this.baseUrl}/cross-site/exchange`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ code, app: this.appId }),\n })\n const body = await res.json().catch(() => null)\n if (!res.ok) {\n const message =\n body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'\n ? body.error\n : `Platform exchange failed (${res.status})`\n throw new PlatformAuthError(message, res.status, body)\n }\n return parseExchangeResult(body, res.status)\n }\n}\n","/**\n * Server-side client for the Tangle platform's integration hub\n * (`/v1/hub/*`). Consumer apps use this instead of rolling their own\n * OAuth + connection tables.\n *\n * Auth: the caller supplies a bearer (either the user's API key from\n * cross-site exchange, or a platform service token) on construction.\n *\n * Endpoint contract (authoritative): the platform's `src/lib/hub-contract.ts`\n * + `src/routes/hub.ts`. The platform wraps every response in\n * `{ success, data }`; non-2xx or `success:false` surfaces as `PlatformHubError`\n * carrying the real upstream status.\n */\n\nexport interface PlatformHubClientOptions {\n /** Platform base URL, e.g. `https://id.tangle.tools`. */\n baseUrl: string\n /** Bearer credential — user API key or service token. */\n bearer: string\n /** Override fetch (tests + edge runtimes). */\n fetchImpl?: typeof fetch\n}\n\n/** A live integration connection, as returned by `/v1/hub/connections`. */\nexport interface PlatformConnection {\n id: string\n providerId: string\n displayName: string\n accountDisplay: string | null\n scopes: string[]\n status: 'active' | 'revoked' | 'unhealthy' | 'reconnect_required' | (string & {})\n health: 'unknown' | 'healthy' | 'unhealthy' | 'rate_limited' | (string & {})\n createdAt: string\n updatedAt: string\n lastUsedAt: string | null\n}\n\n/** A connectable provider in the catalog (`/v1/hub/providers`). */\nexport interface PlatformCatalogProvider {\n providerId: string\n title?: string\n authKind?: string\n category?: string\n scopes?: string[]\n capabilityCount?: number\n native?: boolean\n /** Whether the OAuth app's credentials are wired — the UI offers Connect\n * only when true. */\n configured?: boolean\n [k: string]: unknown\n}\n\nexport interface CatalogResult {\n providers: PlatformCatalogProvider[]\n /** Count of substrate-bundled connectors behind the catalog. */\n substrateBundled?: number\n [k: string]: unknown\n}\n\nexport interface StartAuthInput {\n /** The provider to connect (goes in the URL path). */\n providerId: string\n /** Accepted for interface compatibility; the platform's start endpoint is\n * provider-level and does not consume a connector id. */\n connectorId?: string\n /** Where the platform redirects the user back to after OAuth. */\n returnUrl: string\n /** Accepted for interface compatibility; not consumed by the start endpoint. */\n requestedScopes?: string[]\n /** CLI flow flag — affects the platform's post-auth redirect handling. */\n cli?: boolean\n}\n\nexport interface StartAuthResult {\n /** The URL to send the user to. Normalized across the platform's two start\n * branches: github returns `authorizationUrl`, substrate returns\n * `redirectUrl`. */\n authorizationUrl: string\n state: string\n expiresAt?: string\n scopes?: string[]\n}\n\nexport interface ConnectionHealth {\n status: 'unknown' | 'healthy' | 'unhealthy' | 'rate_limited' | (string & {})\n checkedAt: string\n error?: { code: string; message: string }\n}\n\nexport interface ConnectionHealthResult {\n connection: PlatformConnection\n health: ConnectionHealth\n}\n\n/** Last-known health for a connection, derived from the connection row. */\nexport interface HealthCheck {\n connectionId: string\n providerId: string\n /** Mirrors `PlatformConnection.health`. */\n status: ConnectionHealth['status']\n checkedAt?: string\n}\n\nexport interface MintTokenInput {\n /** The hub action the token authorizes (e.g. `slack.chat.postMessage`). */\n actionPath: string\n /** Bind to a specific connection, or … */\n connectionId?: string\n /** … resolve the connection by provider for the calling user. */\n provider?: string\n}\n\nexport interface MintTokenResult {\n tokenId: string\n token: string\n expiresAt: string\n}\n\nexport interface ExecInput {\n /** The hub action path to execute. */\n path: string\n input?: unknown\n connectionId?: string\n}\n\nexport interface PlatformHubStatus {\n contract?: unknown\n principal: { kind: string; userId: string; [k: string]: unknown }\n connections: { connectedProviderCount: number; unhealthyProviderCount: number }\n}\n\n/** Thrown when a `PlatformHubClient` request returns a non-success status. */\nexport class PlatformHubError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string | undefined,\n public readonly body: unknown,\n ) {\n super(message)\n this.name = 'PlatformHubError'\n }\n}\n\ninterface PlatformEnvelope<T> {\n success: boolean\n data?: T\n error?: { code?: string; message?: string } | string\n}\n\n/** HTTP client for the Tangle Platform Hub API: provider catalog, connection flow, and status. */\nexport class PlatformHubClient {\n private readonly baseUrl: string\n private readonly bearer: string\n private readonly fetchImpl: typeof fetch\n\n constructor(options: PlatformHubClientOptions) {\n if (!options.baseUrl) throw new Error('PlatformHubClient: baseUrl is required')\n if (!options.bearer) throw new Error('PlatformHubClient: bearer is required')\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.bearer = options.bearer\n this.fetchImpl =\n options.fetchImpl ??\n ((url: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => fetch(url, init))\n }\n\n /** GET /v1/hub/providers — the connectable provider catalog. */\n catalog(): Promise<CatalogResult> {\n return this.request('GET', '/v1/hub/providers')\n }\n\n /** GET /v1/hub/connections — the calling user's live connections. */\n async listConnections(): Promise<PlatformConnection[]> {\n const data = await this.request<{ connections: PlatformConnection[] }>(\n 'GET',\n '/v1/hub/connections',\n )\n return data.connections\n }\n\n /** DELETE /v1/hub/connections/:connectionId — revoke + disable a connection. */\n revokeConnection(connectionId: string): Promise<{ connection: PlatformConnection }> {\n return this.request('DELETE', `/v1/hub/connections/${encodeURIComponent(connectionId)}`)\n }\n\n /**\n * POST /v1/hub/connections/:provider/start — begin OAuth/grant. The provider\n * is taken from the URL; the body carries `returnUrl` (+ `cli`). The platform's\n * two start branches name the URL field differently (github → `authorizationUrl`,\n * substrate → `redirectUrl`); this normalizes to `authorizationUrl`.\n */\n async startAuth(input: StartAuthInput): Promise<StartAuthResult> {\n const body: { returnUrl: string; cli?: boolean } = { returnUrl: input.returnUrl }\n if (input.cli !== undefined) body.cli = input.cli\n const data = await this.request<{\n authorizationUrl?: string\n redirectUrl?: string\n state: string\n expiresAt?: string\n scopes?: string[]\n }>('POST', `/v1/hub/connections/${encodeURIComponent(input.providerId)}/start`, body)\n const authorizationUrl = data.authorizationUrl ?? data.redirectUrl\n if (!authorizationUrl) {\n throw new PlatformHubError(\n 'Platform hub start response missing an authorization URL',\n 502,\n 'HUB_INVALID_START_RESPONSE',\n data,\n )\n }\n return { authorizationUrl, state: data.state, expiresAt: data.expiresAt, scopes: data.scopes }\n }\n\n /**\n * Last-known health for every connection. The platform has no global\n * healthcheck listing — health rides on each connection row — so this derives\n * the list from `listConnections()` (one request, no extra round-trips).\n */\n async listHealthchecks(): Promise<HealthCheck[]> {\n const connections = await this.listConnections()\n return connections.map((c) => ({\n connectionId: c.id,\n providerId: c.providerId,\n status: c.health,\n checkedAt: c.updatedAt,\n }))\n }\n\n /**\n * POST /v1/hub/connections/:connectionId/health — trigger a fresh health\n * probe for one connection and return its updated state.\n */\n checkConnectionHealth(connectionId: string): Promise<ConnectionHealthResult> {\n return this.request('POST', `/v1/hub/connections/${encodeURIComponent(connectionId)}/health`)\n }\n\n /**\n * Trigger a fresh health probe across all of the user's connections. The\n * platform exposes health per-connection only, so this fans out over\n * `listConnections()`. `scheduled` is the number of probes dispatched.\n */\n async runHealthchecks(): Promise<{ scheduled: number }> {\n const connections = await this.listConnections()\n await Promise.allSettled(connections.map((c) => this.checkConnectionHealth(c.id)))\n return { scheduled: connections.length }\n }\n\n /** GET /v1/hub/status — principal + aggregate connection counts. */\n status(): Promise<PlatformHubStatus> {\n return this.request('GET', '/v1/hub/status')\n }\n\n /**\n * POST /v1/hub/tokens — mint a short-lived, action-scoped capability token a\n * sandbox can use to invoke one hub action on the user's behalf without\n * seeing the underlying provider credential.\n */\n mintToken(input: MintTokenInput): Promise<MintTokenResult> {\n return this.request('POST', '/v1/hub/tokens', input)\n }\n\n /** POST /v1/hub/exec — execute a hub action and return its result. */\n async exec(input: ExecInput): Promise<unknown> {\n const data = await this.request<{ result: unknown }>('POST', '/v1/hub/exec', input)\n return data.result\n }\n\n private async request<T>(\n method: 'GET' | 'POST' | 'DELETE' | 'PUT',\n path: string,\n body?: unknown,\n ): Promise<T> {\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.bearer}`,\n accept: 'application/json',\n }\n if (body !== undefined) headers['content-type'] = 'application/json'\n\n const res = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n })\n const text = await res.text()\n let parsed: PlatformEnvelope<T> | null = null\n if (text) {\n try {\n parsed = JSON.parse(text)\n } catch {\n // fall through to error handling below\n }\n }\n if (!res.ok || (parsed && parsed.success === false)) {\n const code = parsed?.error && typeof parsed.error === 'object' ? parsed.error.code : undefined\n const message =\n (parsed?.error && typeof parsed.error === 'object' && parsed.error.message) ||\n (typeof parsed?.error === 'string' ? parsed.error : `Platform hub error (${res.status})`)\n throw new PlatformHubError(message, res.status, code, parsed ?? text)\n }\n if (!parsed) {\n throw new PlatformHubError(\n `Platform hub returned non-JSON success (${res.status})`,\n res.status,\n undefined,\n text,\n )\n }\n if (parsed.data === undefined) {\n throw new PlatformHubError(\n 'Platform hub envelope missing `data`',\n res.status,\n undefined,\n parsed,\n )\n }\n return parsed.data\n }\n}\n","/**\n * OpenID Connect client for the Tangle authorization server. Identity tokens\n * are not platform API keys. Resource scopes and audiences must be registered\n * by the provider before a consumer can use these tokens at a paid API.\n */\nimport { PlatformAuthError } from './auth.js'\n\nexport interface PlatformOidcClientOptions {\n baseUrl: string\n clientId: string\n /** Omit only for clients registered with token_endpoint_auth_method=none. */\n clientSecret?: string\n /** Required for authorization code; not required for the device grant. */\n redirectUri?: string\n scope?: string\n /** RFC 8707 resource identifiers registered at the authorization server. */\n resources?: readonly string[]\n fetchImpl?: typeof fetch\n}\n\nexport interface OidcAuthorizeUrlOptions {\n state: string\n codeChallenge: string\n /** Only supply a nonce when the consumer also validates the ID token. */\n nonce?: string\n prompt?: 'login' | 'consent' | 'none'\n loginHint?: string\n}\n\nexport interface OidcTokens {\n accessToken: string\n tokenType: string\n expiresIn?: number\n refreshToken?: string\n idToken?: string\n scope?: string\n}\n\nexport interface OidcUser {\n id: string\n email: string\n emailVerified: true\n name?: string\n}\n\nexport interface OidcExchangeResult {\n tokens: OidcTokens\n user: OidcUser\n}\n\n/** Keep deviceCode secret. Only userCode and the verification URLs are displayed. */\nexport interface OidcDeviceAuthorization {\n deviceCode: string\n userCode: string\n verificationUri: string\n verificationUriComplete?: string\n expiresIn: number\n /** Absolute deadline preserves expiry when a polling process resumes. */\n expiresAt: number\n interval: number\n}\n\nconst DEFAULT_SCOPE = 'openid profile email offline_access'\nconst DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isNonemptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/** Create an RFC 7636 verifier and its S256 challenge with Web Crypto. */\nexport async function createPkcePair(): Promise<{ verifier: string; challenge: string }> {\n const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)))\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))\n return { verifier, challenge: base64url(new Uint8Array(digest)) }\n}\n\nfunction oauthError(body: unknown, fallback: string): string {\n if (!isRecord(body)) return fallback\n if (isNonemptyString(body.error_description)) return body.error_description\n if (isNonemptyString(body.error)) return body.error\n return fallback\n}\n\nfunction parseTokens(body: unknown, status: number): OidcTokens {\n if (!isRecord(body) || !isNonemptyString(body.access_token)) {\n throw new PlatformAuthError('Platform token response is malformed', status, {\n code: 'INVALID_TOKEN_RESPONSE',\n })\n }\n return {\n accessToken: body.access_token,\n tokenType: isNonemptyString(body.token_type) ? body.token_type : 'Bearer',\n ...(typeof body.expires_in === 'number' ? { expiresIn: body.expires_in } : {}),\n ...(isNonemptyString(body.refresh_token) ? { refreshToken: body.refresh_token } : {}),\n ...(isNonemptyString(body.id_token) ? { idToken: body.id_token } : {}),\n ...(isNonemptyString(body.scope) ? { scope: body.scope } : {}),\n }\n}\n\nfunction formComponent(value: string): string {\n return new URLSearchParams({ v: value }).toString().slice(2)\n}\n\nfunction pause(ms: number, signal?: AbortSignal): Promise<void> {\n signal?.throwIfAborted()\n return new Promise((resolve, reject) => {\n const finish = () => {\n signal?.removeEventListener('abort', abort)\n resolve()\n }\n const timer = setTimeout(finish, ms)\n const abort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', abort)\n reject(signal?.reason ?? new Error('Device authorization cancelled'))\n }\n signal?.addEventListener('abort', abort, { once: true })\n })\n}\n\n/** OIDC code + PKCE, refresh/revoke and discovery-bound RFC 8628 device grants. */\nexport class PlatformOidcClient {\n private readonly baseUrl: string\n private readonly clientId: string\n private readonly clientSecret: string | undefined\n private readonly redirectUri: string | undefined\n private readonly scope: string\n private readonly resources: readonly string[]\n private readonly fetchImpl: typeof fetch\n\n constructor(options: PlatformOidcClientOptions) {\n if (!options.baseUrl) throw new Error('PlatformOidcClient: baseUrl is required')\n if (!options.clientId) throw new Error('PlatformOidcClient: clientId is required')\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.clientId = options.clientId\n this.clientSecret = options.clientSecret || undefined\n this.redirectUri = options.redirectUri\n this.scope = options.scope ?? DEFAULT_SCOPE\n this.resources = [...new Set(options.resources ?? [])]\n for (const resource of this.resources) {\n const url = new URL(resource)\n if (url.hash || url.username || url.password) {\n throw new Error('PlatformOidcClient: resource must not contain a fragment or credentials')\n }\n }\n this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init))\n }\n\n authorizeUrl(options: OidcAuthorizeUrlOptions): string {\n if (!this.redirectUri)\n throw new Error('PlatformOidcClient: redirectUri is required for authorization code')\n if (!options.state)\n throw new Error('PlatformOidcClient.authorizeUrl: state is required for CSRF')\n if (!options.codeChallenge)\n throw new Error('PlatformOidcClient.authorizeUrl: codeChallenge is required for PKCE')\n const url = new URL('/api/auth/oauth2/authorize', this.baseUrl)\n url.searchParams.set('client_id', this.clientId)\n url.searchParams.set('redirect_uri', this.redirectUri)\n url.searchParams.set('response_type', 'code')\n url.searchParams.set('scope', this.scope)\n url.searchParams.set('state', options.state)\n url.searchParams.set('code_challenge', options.codeChallenge)\n url.searchParams.set('code_challenge_method', 'S256')\n for (const resource of this.resources) url.searchParams.append('resource', resource)\n if (options.nonce) url.searchParams.set('nonce', options.nonce)\n if (options.prompt) url.searchParams.set('prompt', options.prompt)\n if (options.loginHint) url.searchParams.set('login_hint', options.loginHint)\n return url.toString()\n }\n\n async exchange(code: string, codeVerifier: string): Promise<OidcExchangeResult> {\n if (!this.redirectUri)\n throw new Error('PlatformOidcClient: redirectUri is required for authorization code')\n if (!code) throw new Error('PlatformOidcClient.exchange: code is required')\n if (!codeVerifier)\n throw new Error('PlatformOidcClient.exchange: codeVerifier is required for PKCE')\n const tokens = await this.token({\n grant_type: 'authorization_code',\n code,\n redirect_uri: this.redirectUri,\n code_verifier: codeVerifier,\n })\n return { tokens, user: await this.userinfo(tokens.accessToken) }\n }\n\n /** Save the replacement refresh token. Never retry an old token as a new grant. */\n async refresh(refreshToken: string): Promise<OidcTokens> {\n if (!refreshToken) throw new Error('PlatformOidcClient.refresh: refreshToken is required')\n return this.token({ grant_type: 'refresh_token', refresh_token: refreshToken })\n }\n\n async userinfo(accessToken: string): Promise<OidcUser> {\n if (!accessToken) throw new Error('PlatformOidcClient.userinfo: accessToken is required')\n const res = await this.fetchImpl(`${this.baseUrl}/api/auth/oauth2/userinfo`, {\n headers: { authorization: `Bearer ${accessToken}` },\n redirect: 'error',\n })\n const body: unknown = await res.json().catch(() => null)\n if (!res.ok)\n throw new PlatformAuthError(\n oauthError(body, `Platform userinfo failed (${res.status})`),\n res.status,\n body,\n )\n if (\n !isRecord(body) ||\n !isNonemptyString(body.sub) ||\n !isNonemptyString(body.email) ||\n body.email_verified !== true\n ) {\n throw new PlatformAuthError('Platform userinfo has no verified identity', res.status, {\n code: 'INVALID_USERINFO_RESPONSE',\n })\n }\n return {\n id: body.sub,\n email: body.email,\n emailVerified: true,\n ...(isNonemptyString(body.name) ? { name: body.name } : {}),\n }\n }\n\n /** RFC 7009. A local logout alone is not a provider disconnect. */\n async revoke(token: string, tokenTypeHint?: 'access_token' | 'refresh_token'): Promise<void> {\n if (!token) throw new Error('PlatformOidcClient.revoke: token is required')\n const res = await this.post(\n `${this.baseUrl}/api/auth/oauth2/revoke`,\n {\n token,\n ...(tokenTypeHint ? { token_type_hint: tokenTypeHint } : {}),\n },\n undefined,\n false,\n )\n if (!res.ok) {\n const body: unknown = await res.json().catch(() => null)\n throw new PlatformAuthError(\n oauthError(body, `Platform revoke failed (${res.status})`),\n res.status,\n body,\n )\n }\n }\n\n /**\n * Start a device grant only when this issuer advertises the OAuth-integrated\n * device endpoint. No fallback to /cross-site/device or a standalone session\n * device endpoint: those issue different credentials.\n */\n async deviceAuthorize(options: { signal?: AbortSignal } = {}): Promise<OidcDeviceAuthorization> {\n const discovery = await this.fetchImpl(\n `${this.baseUrl}/api/auth/.well-known/openid-configuration`,\n {\n redirect: 'error',\n signal: options.signal,\n },\n )\n const metadata: unknown = await discovery.json().catch(() => null)\n const issuer = `${this.baseUrl}/api/auth`\n if (\n !discovery.ok ||\n !isRecord(metadata) ||\n metadata.issuer !== issuer ||\n metadata.token_endpoint !== `${issuer}/oauth2/token` ||\n !Array.isArray(metadata.grant_types_supported) ||\n !metadata.grant_types_supported.includes(DEVICE_GRANT) ||\n !isNonemptyString(metadata.device_authorization_endpoint)\n ) {\n throw new PlatformAuthError(\n 'Issuer does not advertise an OAuth device grant',\n discovery.status,\n { code: 'OAUTH_DEVICE_GRANT_UNAVAILABLE' },\n )\n }\n const endpoint = new URL(metadata.device_authorization_endpoint)\n const origin = new URL(this.baseUrl).origin\n if (endpoint.origin !== origin || endpoint.username || endpoint.password || endpoint.hash) {\n throw new PlatformAuthError('Device endpoint is outside the configured issuer', 400, {\n code: 'INVALID_DEVICE_ENDPOINT',\n })\n }\n const startedAt = Date.now()\n const res = await this.post(endpoint.href, { scope: this.scope }, options.signal)\n const body: unknown = await res.json().catch(() => null)\n if (!res.ok)\n throw new PlatformAuthError(\n oauthError(body, `Device authorization failed (${res.status})`),\n res.status,\n body,\n )\n if (\n !isRecord(body) ||\n !isNonemptyString(body.device_code) ||\n !isNonemptyString(body.user_code) ||\n !isNonemptyString(body.verification_uri) ||\n typeof body.expires_in !== 'number' ||\n !Number.isSafeInteger(body.expires_in) ||\n body.expires_in <= 0 ||\n (body.interval !== undefined &&\n (typeof body.interval !== 'number' ||\n !Number.isSafeInteger(body.interval) ||\n body.interval <= 0))\n ) {\n throw new PlatformAuthError('Malformed device authorization response', res.status, {\n code: 'INVALID_DEVICE_RESPONSE',\n })\n }\n for (const value of [body.verification_uri, body.verification_uri_complete]) {\n if (value === undefined) continue\n if (!isNonemptyString(value))\n throw new PlatformAuthError('Invalid device verification URI', 400, {\n code: 'INVALID_DEVICE_RESPONSE',\n })\n const uri = new URL(value)\n if (uri.origin !== origin || uri.username || uri.password || uri.hash) {\n throw new PlatformAuthError('Device verification URI is outside the issuer', 400, {\n code: 'INVALID_DEVICE_RESPONSE',\n })\n }\n }\n return {\n deviceCode: body.device_code,\n userCode: body.user_code,\n verificationUri: body.verification_uri,\n ...(isNonemptyString(body.verification_uri_complete)\n ? { verificationUriComplete: body.verification_uri_complete }\n : {}),\n expiresIn: body.expires_in,\n expiresAt: startedAt + body.expires_in * 1000,\n interval: typeof body.interval === 'number' ? body.interval : 5,\n }\n }\n\n /** RFC 8628 pending/slow_down handling, expiry, cancellation and timeout backoff. */\n async pollDeviceAuthorization(\n grant: OidcDeviceAuthorization,\n options: { signal?: AbortSignal } = {},\n ): Promise<OidcTokens> {\n if (\n !grant.deviceCode ||\n !Number.isFinite(grant.expiresAt) ||\n !Number.isFinite(grant.interval) ||\n grant.interval <= 0\n ) {\n throw new Error('PlatformOidcClient.pollDeviceAuthorization: invalid device grant')\n }\n let intervalMs = grant.interval * 1000\n while (Date.now() < grant.expiresAt) {\n options.signal?.throwIfAborted()\n await pause(Math.min(intervalMs, Math.max(0, grant.expiresAt - Date.now())), options.signal)\n const remaining = grant.expiresAt - Date.now()\n if (remaining <= 0) break\n const timeout = AbortSignal.timeout(Math.max(1, Math.min(30_000, Math.floor(remaining))))\n const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout\n try {\n return await this.token({ grant_type: DEVICE_GRANT, device_code: grant.deviceCode }, signal)\n } catch (error) {\n options.signal?.throwIfAborted()\n if (timeout.aborted) {\n intervalMs *= 2\n continue\n }\n if (!(error instanceof PlatformAuthError) || !isRecord(error.body)) throw error\n if (error.body.error === 'authorization_pending') continue\n if (error.body.error === 'slow_down') {\n intervalMs += 5_000\n continue\n }\n throw error\n }\n }\n throw new PlatformAuthError('Device authorization expired', 400, { error: 'expired_token' })\n }\n\n private async token(params: Record<string, string>, signal?: AbortSignal): Promise<OidcTokens> {\n const res = await this.post(`${this.baseUrl}/api/auth/oauth2/token`, params, signal)\n const body: unknown = await res.json().catch(() => null)\n if (!res.ok)\n throw new PlatformAuthError(\n oauthError(body, `Platform token request failed (${res.status})`),\n res.status,\n body,\n )\n return parseTokens(body, res.status)\n }\n\n private post(\n url: string,\n params: Record<string, string>,\n signal?: AbortSignal,\n includeResources = true,\n ): Promise<Response> {\n const body = new URLSearchParams(params)\n const headers: Record<string, string> = { 'content-type': 'application/x-www-form-urlencoded' }\n if (this.clientSecret) {\n // RFC 6749 section 2.3.1: form-encode each component before HTTP Basic.\n headers.authorization = `Basic ${btoa(`${formComponent(this.clientId)}:${formComponent(this.clientSecret)}`)}`\n } else body.set('client_id', this.clientId)\n if (includeResources) for (const resource of this.resources) body.append('resource', resource)\n return this.fetchImpl(url, { method: 'POST', headers, body, redirect: 'error', signal })\n }\n}\n"],"mappings":";;AAoDA,IAAa,oBAAb,cAAuC,MAAM;CAGzB;CACA;CAHlB,YACE,SACA,QACA,MACA;EACA,MAAM,OAAO;EAHG,KAAA,SAAA;EACA,KAAA,OAAA;EAGhB,KAAK,OAAO;CACd;AACF;AAEA,SAASA,WAAS,OAAkD;CAClE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAASC,mBAAiB,OAAiC;CACzD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS;AAC5D;;AAGA,SAAS,oBAAoB,MAAe,QAAoC;CAC9E,MAAM,gBAAuB;EAE3B,MAAM,IAAI,kBACR,6DACA,QACA,EAAE,MAAM,4BAA4B,CACtC;CACF;CACA,IACE,CAACD,WAAS,IAAI,KACd,CAACC,mBAAiB,KAAK,MAAM,KAC7B,KAAK,kBAAkB,QACvB,CAACD,WAAS,KAAK,IAAI,GAEnB,OAAO,QAAQ;CACjB,MAAM,OAAO,KAAK;CAClB,IAAI,CAACC,mBAAiB,KAAK,EAAE,KAAK,CAACA,mBAAiB,KAAK,KAAK,GAAG,OAAO,QAAQ;CAChF,MAAM,QAAQ,KAAK,MAAM,KAAK;CAC9B,IACE,MAAM,SAAS,OACf,CAAC,6BAA6B,KAAK,KAAK,KACxC,sEAAsE,KAAK,KAAK,GAEhF,OAAO,QAAQ;CACjB,IAAI,KAAK,SAAS,KAA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;GAAS;GAAM,UAAU;GAAS;EAAO,CAAC;CACzF;AACF"}
|
|
1
|
+
{"version":3,"file":"platform.js","names":["isRecord","isNonemptyString"],"sources":["../src/platform/auth.ts","../src/platform/oidc.ts"],"sourcesContent":["/**\n * Server-side client for the Tangle platform's cross-site SSO bridge.\n *\n * Consumer apps (gtm-agent, tax-agent, legal-agent, creative-agent, …)\n * use this to:\n * 1. Build an /authorize URL that lands the user on id.tangle.tools\n * and brings them back with a single-use code.\n * 2. Exchange that code for an API key + the user's identity.\n *\n * The platform endpoint contract is documented in\n * `products/platform/api/src/routes/cross-site.ts`. This client only\n * speaks HTTP — no SDK weight, no transitive deps.\n */\n\nexport interface PlatformAuthClientOptions {\n /** Platform base URL, e.g. `https://id.tangle.tools`. */\n baseUrl: string\n /** App id as registered in the platform's TRUSTED_APPS registry. */\n appId: string\n /** Override the global fetch (useful for tests + edge runtimes). */\n fetchImpl?: typeof fetch\n}\n\nexport interface AuthorizeUrlOptions {\n /** Required CSRF token; the consumer verifies it on the callback. */\n state: string\n /**\n * Final redirect URI. Must be one of the URIs registered for `appId`\n * on the platform. Omit to use the first registered URI.\n */\n redirectUri?: string\n /** Force the login screen even if a session is already active. */\n prompt?: 'login'\n /** Pre-fill the email field on the login screen. */\n email?: string\n}\n\nexport interface ExchangeCodeResult {\n apiKey: string\n emailVerified: true\n user: {\n id: string\n email: string\n name?: string | null\n }\n /** Null when the platform could not provide a subscription. This is not a paid-access grant. */\n plan: {\n tier: string\n } | null\n}\n\n/** Thrown when a `PlatformAuthClient` request returns a non-success status. */\nexport class PlatformAuthError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: unknown,\n ) {\n super(message)\n this.name = 'PlatformAuthError'\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isNonemptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\n/** Validate the platform's verified identity before consumers create a local session. */\nfunction parseExchangeResult(body: unknown, status: number): ExchangeCodeResult {\n const invalid = (): never => {\n // A successful but malformed response can contain the one-time API secret.\n throw new PlatformAuthError(\n 'Platform exchange response has no valid verified identity',\n status,\n { code: 'INVALID_EXCHANGE_RESPONSE' },\n )\n }\n if (\n !isRecord(body) ||\n !isNonemptyString(body.apiKey) ||\n body.emailVerified !== true ||\n !isRecord(body.user)\n )\n return invalid()\n const user = body.user\n if (!isNonemptyString(user.id) || !isNonemptyString(user.email)) return invalid()\n const email = user.email.trim()\n if (\n email.length > 320 ||\n !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ||\n /(?:@users\\.noreply\\.tangle\\.tools$|^0x[a-f0-9]{40}@tangle\\.tools$)/i.test(email)\n )\n return invalid()\n if (user.name !== undefined && user.name !== null && typeof user.name !== 'string')\n return invalid()\n let plan: ExchangeCodeResult['plan'] = null\n if (body.subscription !== undefined) {\n if (!isRecord(body.subscription) || !isNonemptyString(body.subscription.plan)) return invalid()\n plan = { tier: body.subscription.plan }\n }\n return {\n apiKey: body.apiKey,\n emailVerified: true,\n user: { id: user.id, email, ...(user.name !== undefined ? { name: user.name } : {}) },\n plan,\n }\n}\n\n/** HTTP client for the Tangle Platform SSO: builds authorize URLs and exchanges auth codes for API keys. */\nexport class PlatformAuthClient {\n private readonly baseUrl: string\n private readonly appId: string\n private readonly fetchImpl: typeof fetch\n\n constructor(options: PlatformAuthClientOptions) {\n if (!options.baseUrl) throw new Error('PlatformAuthClient: baseUrl is required')\n if (!options.appId) throw new Error('PlatformAuthClient: appId is required')\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.appId = options.appId\n this.fetchImpl =\n options.fetchImpl ??\n ((url: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => fetch(url, init))\n }\n\n /**\n * Build the URL the user is redirected to in order to start SSO.\n * The platform redirects back to one of `appId`'s registered\n * `redirectUris` with `?code=...&app=...&state=...`.\n */\n authorizeUrl(options: AuthorizeUrlOptions): string {\n if (!options.state) {\n throw new Error('PlatformAuthClient.authorizeUrl: state is required for CSRF')\n }\n const url = new URL('/cross-site/authorize', this.baseUrl)\n url.searchParams.set('app', this.appId)\n url.searchParams.set('state', options.state)\n if (options.redirectUri) url.searchParams.set('redirect', options.redirectUri)\n if (options.prompt) url.searchParams.set('prompt', options.prompt)\n if (options.email) url.searchParams.set('email', options.email)\n return url.toString()\n }\n\n /**\n * Exchange a single-use auth code (delivered to the consumer's\n * callback by the platform) for an API key + the user's identity.\n * Codes are single-use and expire ~5 minutes after issue.\n */\n async exchange(code: string): Promise<ExchangeCodeResult> {\n if (!code) throw new Error('PlatformAuthClient.exchange: code is required')\n const res = await this.fetchImpl(`${this.baseUrl}/cross-site/exchange`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ code, app: this.appId }),\n })\n const body = await res.json().catch(() => null)\n if (!res.ok) {\n const message =\n body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'\n ? body.error\n : `Platform exchange failed (${res.status})`\n throw new PlatformAuthError(message, res.status, body)\n }\n return parseExchangeResult(body, res.status)\n }\n}\n","/**\n * OpenID Connect client for the Tangle authorization server. Identity tokens\n * are not platform API keys. Resource scopes and audiences must be registered\n * by the provider before a consumer can use these tokens at a paid API.\n */\nimport { PlatformAuthError } from './auth.js'\n\nexport interface PlatformOidcClientOptions {\n baseUrl: string\n clientId: string\n /** Omit only for clients registered with token_endpoint_auth_method=none. */\n clientSecret?: string\n /** Required for authorization code; not required for the device grant. */\n redirectUri?: string\n scope?: string\n /** RFC 8707 resource identifiers registered at the authorization server. */\n resources?: readonly string[]\n fetchImpl?: typeof fetch\n}\n\nexport interface OidcAuthorizeUrlOptions {\n state: string\n codeChallenge: string\n /** Only supply a nonce when the consumer also validates the ID token. */\n nonce?: string\n prompt?: 'login' | 'consent' | 'none'\n loginHint?: string\n}\n\nexport interface OidcTokens {\n accessToken: string\n tokenType: string\n expiresIn?: number\n refreshToken?: string\n idToken?: string\n scope?: string\n}\n\nexport interface OidcUser {\n id: string\n email: string\n emailVerified: true\n name?: string\n}\n\nexport interface OidcExchangeResult {\n tokens: OidcTokens\n user: OidcUser\n}\n\n/** Keep deviceCode secret. Only userCode and the verification URLs are displayed. */\nexport interface OidcDeviceAuthorization {\n deviceCode: string\n userCode: string\n verificationUri: string\n verificationUriComplete?: string\n expiresIn: number\n /** Absolute deadline preserves expiry when a polling process resumes. */\n expiresAt: number\n interval: number\n}\n\nconst DEFAULT_SCOPE = 'openid profile email offline_access'\nconst DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isNonemptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/** Create an RFC 7636 verifier and its S256 challenge with Web Crypto. */\nexport async function createPkcePair(): Promise<{ verifier: string; challenge: string }> {\n const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)))\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))\n return { verifier, challenge: base64url(new Uint8Array(digest)) }\n}\n\nfunction oauthError(body: unknown, fallback: string): string {\n if (!isRecord(body)) return fallback\n if (isNonemptyString(body.error_description)) return body.error_description\n if (isNonemptyString(body.error)) return body.error\n return fallback\n}\n\nfunction parseTokens(body: unknown, status: number): OidcTokens {\n if (!isRecord(body) || !isNonemptyString(body.access_token)) {\n throw new PlatformAuthError('Platform token response is malformed', status, {\n code: 'INVALID_TOKEN_RESPONSE',\n })\n }\n return {\n accessToken: body.access_token,\n tokenType: isNonemptyString(body.token_type) ? body.token_type : 'Bearer',\n ...(typeof body.expires_in === 'number' ? { expiresIn: body.expires_in } : {}),\n ...(isNonemptyString(body.refresh_token) ? { refreshToken: body.refresh_token } : {}),\n ...(isNonemptyString(body.id_token) ? { idToken: body.id_token } : {}),\n ...(isNonemptyString(body.scope) ? { scope: body.scope } : {}),\n }\n}\n\nfunction formComponent(value: string): string {\n return new URLSearchParams({ v: value }).toString().slice(2)\n}\n\nfunction pause(ms: number, signal?: AbortSignal): Promise<void> {\n signal?.throwIfAborted()\n return new Promise((resolve, reject) => {\n const finish = () => {\n signal?.removeEventListener('abort', abort)\n resolve()\n }\n const timer = setTimeout(finish, ms)\n const abort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', abort)\n reject(signal?.reason ?? new Error('Device authorization cancelled'))\n }\n signal?.addEventListener('abort', abort, { once: true })\n })\n}\n\n/** OIDC code + PKCE, refresh/revoke and discovery-bound RFC 8628 device grants. */\nexport class PlatformOidcClient {\n private readonly baseUrl: string\n private readonly clientId: string\n private readonly clientSecret: string | undefined\n private readonly redirectUri: string | undefined\n private readonly scope: string\n private readonly resources: readonly string[]\n private readonly fetchImpl: typeof fetch\n\n constructor(options: PlatformOidcClientOptions) {\n if (!options.baseUrl) throw new Error('PlatformOidcClient: baseUrl is required')\n if (!options.clientId) throw new Error('PlatformOidcClient: clientId is required')\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.clientId = options.clientId\n this.clientSecret = options.clientSecret || undefined\n this.redirectUri = options.redirectUri\n this.scope = options.scope ?? DEFAULT_SCOPE\n this.resources = [...new Set(options.resources ?? [])]\n for (const resource of this.resources) {\n const url = new URL(resource)\n if (url.hash || url.username || url.password) {\n throw new Error('PlatformOidcClient: resource must not contain a fragment or credentials')\n }\n }\n this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init))\n }\n\n authorizeUrl(options: OidcAuthorizeUrlOptions): string {\n if (!this.redirectUri)\n throw new Error('PlatformOidcClient: redirectUri is required for authorization code')\n if (!options.state)\n throw new Error('PlatformOidcClient.authorizeUrl: state is required for CSRF')\n if (!options.codeChallenge)\n throw new Error('PlatformOidcClient.authorizeUrl: codeChallenge is required for PKCE')\n const url = new URL('/api/auth/oauth2/authorize', this.baseUrl)\n url.searchParams.set('client_id', this.clientId)\n url.searchParams.set('redirect_uri', this.redirectUri)\n url.searchParams.set('response_type', 'code')\n url.searchParams.set('scope', this.scope)\n url.searchParams.set('state', options.state)\n url.searchParams.set('code_challenge', options.codeChallenge)\n url.searchParams.set('code_challenge_method', 'S256')\n for (const resource of this.resources) url.searchParams.append('resource', resource)\n if (options.nonce) url.searchParams.set('nonce', options.nonce)\n if (options.prompt) url.searchParams.set('prompt', options.prompt)\n if (options.loginHint) url.searchParams.set('login_hint', options.loginHint)\n return url.toString()\n }\n\n async exchange(code: string, codeVerifier: string): Promise<OidcExchangeResult> {\n if (!this.redirectUri)\n throw new Error('PlatformOidcClient: redirectUri is required for authorization code')\n if (!code) throw new Error('PlatformOidcClient.exchange: code is required')\n if (!codeVerifier)\n throw new Error('PlatformOidcClient.exchange: codeVerifier is required for PKCE')\n const tokens = await this.token({\n grant_type: 'authorization_code',\n code,\n redirect_uri: this.redirectUri,\n code_verifier: codeVerifier,\n })\n return { tokens, user: await this.userinfo(tokens.accessToken) }\n }\n\n /** Save the replacement refresh token. Never retry an old token as a new grant. */\n async refresh(refreshToken: string): Promise<OidcTokens> {\n if (!refreshToken) throw new Error('PlatformOidcClient.refresh: refreshToken is required')\n return this.token({ grant_type: 'refresh_token', refresh_token: refreshToken })\n }\n\n async userinfo(accessToken: string): Promise<OidcUser> {\n if (!accessToken) throw new Error('PlatformOidcClient.userinfo: accessToken is required')\n const res = await this.fetchImpl(`${this.baseUrl}/api/auth/oauth2/userinfo`, {\n headers: { authorization: `Bearer ${accessToken}` },\n redirect: 'error',\n })\n const body: unknown = await res.json().catch(() => null)\n if (!res.ok)\n throw new PlatformAuthError(\n oauthError(body, `Platform userinfo failed (${res.status})`),\n res.status,\n body,\n )\n if (\n !isRecord(body) ||\n !isNonemptyString(body.sub) ||\n !isNonemptyString(body.email) ||\n body.email_verified !== true\n ) {\n throw new PlatformAuthError('Platform userinfo has no verified identity', res.status, {\n code: 'INVALID_USERINFO_RESPONSE',\n })\n }\n return {\n id: body.sub,\n email: body.email,\n emailVerified: true,\n ...(isNonemptyString(body.name) ? { name: body.name } : {}),\n }\n }\n\n /** RFC 7009. A local logout alone is not a provider disconnect. */\n async revoke(token: string, tokenTypeHint?: 'access_token' | 'refresh_token'): Promise<void> {\n if (!token) throw new Error('PlatformOidcClient.revoke: token is required')\n const res = await this.post(\n `${this.baseUrl}/api/auth/oauth2/revoke`,\n {\n token,\n ...(tokenTypeHint ? { token_type_hint: tokenTypeHint } : {}),\n },\n undefined,\n false,\n )\n if (!res.ok) {\n const body: unknown = await res.json().catch(() => null)\n throw new PlatformAuthError(\n oauthError(body, `Platform revoke failed (${res.status})`),\n res.status,\n body,\n )\n }\n }\n\n /**\n * Start a device grant only when this issuer advertises the OAuth-integrated\n * device endpoint. No fallback to /cross-site/device or a standalone session\n * device endpoint: those issue different credentials.\n */\n async deviceAuthorize(options: { signal?: AbortSignal } = {}): Promise<OidcDeviceAuthorization> {\n const discovery = await this.fetchImpl(\n `${this.baseUrl}/api/auth/.well-known/openid-configuration`,\n {\n redirect: 'error',\n signal: options.signal,\n },\n )\n const metadata: unknown = await discovery.json().catch(() => null)\n const issuer = `${this.baseUrl}/api/auth`\n if (\n !discovery.ok ||\n !isRecord(metadata) ||\n metadata.issuer !== issuer ||\n metadata.token_endpoint !== `${issuer}/oauth2/token` ||\n !Array.isArray(metadata.grant_types_supported) ||\n !metadata.grant_types_supported.includes(DEVICE_GRANT) ||\n !isNonemptyString(metadata.device_authorization_endpoint)\n ) {\n throw new PlatformAuthError(\n 'Issuer does not advertise an OAuth device grant',\n discovery.status,\n { code: 'OAUTH_DEVICE_GRANT_UNAVAILABLE' },\n )\n }\n const endpoint = new URL(metadata.device_authorization_endpoint)\n const origin = new URL(this.baseUrl).origin\n if (endpoint.origin !== origin || endpoint.username || endpoint.password || endpoint.hash) {\n throw new PlatformAuthError('Device endpoint is outside the configured issuer', 400, {\n code: 'INVALID_DEVICE_ENDPOINT',\n })\n }\n const startedAt = Date.now()\n const res = await this.post(endpoint.href, { scope: this.scope }, options.signal)\n const body: unknown = await res.json().catch(() => null)\n if (!res.ok)\n throw new PlatformAuthError(\n oauthError(body, `Device authorization failed (${res.status})`),\n res.status,\n body,\n )\n if (\n !isRecord(body) ||\n !isNonemptyString(body.device_code) ||\n !isNonemptyString(body.user_code) ||\n !isNonemptyString(body.verification_uri) ||\n typeof body.expires_in !== 'number' ||\n !Number.isSafeInteger(body.expires_in) ||\n body.expires_in <= 0 ||\n (body.interval !== undefined &&\n (typeof body.interval !== 'number' ||\n !Number.isSafeInteger(body.interval) ||\n body.interval <= 0))\n ) {\n throw new PlatformAuthError('Malformed device authorization response', res.status, {\n code: 'INVALID_DEVICE_RESPONSE',\n })\n }\n for (const value of [body.verification_uri, body.verification_uri_complete]) {\n if (value === undefined) continue\n if (!isNonemptyString(value))\n throw new PlatformAuthError('Invalid device verification URI', 400, {\n code: 'INVALID_DEVICE_RESPONSE',\n })\n const uri = new URL(value)\n if (uri.origin !== origin || uri.username || uri.password || uri.hash) {\n throw new PlatformAuthError('Device verification URI is outside the issuer', 400, {\n code: 'INVALID_DEVICE_RESPONSE',\n })\n }\n }\n return {\n deviceCode: body.device_code,\n userCode: body.user_code,\n verificationUri: body.verification_uri,\n ...(isNonemptyString(body.verification_uri_complete)\n ? { verificationUriComplete: body.verification_uri_complete }\n : {}),\n expiresIn: body.expires_in,\n expiresAt: startedAt + body.expires_in * 1000,\n interval: typeof body.interval === 'number' ? body.interval : 5,\n }\n }\n\n /** RFC 8628 pending/slow_down handling, expiry, cancellation and timeout backoff. */\n async pollDeviceAuthorization(\n grant: OidcDeviceAuthorization,\n options: { signal?: AbortSignal } = {},\n ): Promise<OidcTokens> {\n if (\n !grant.deviceCode ||\n !Number.isFinite(grant.expiresAt) ||\n !Number.isFinite(grant.interval) ||\n grant.interval <= 0\n ) {\n throw new Error('PlatformOidcClient.pollDeviceAuthorization: invalid device grant')\n }\n let intervalMs = grant.interval * 1000\n while (Date.now() < grant.expiresAt) {\n options.signal?.throwIfAborted()\n await pause(Math.min(intervalMs, Math.max(0, grant.expiresAt - Date.now())), options.signal)\n const remaining = grant.expiresAt - Date.now()\n if (remaining <= 0) break\n const timeout = AbortSignal.timeout(Math.max(1, Math.min(30_000, Math.floor(remaining))))\n const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout\n try {\n return await this.token({ grant_type: DEVICE_GRANT, device_code: grant.deviceCode }, signal)\n } catch (error) {\n options.signal?.throwIfAborted()\n if (timeout.aborted) {\n intervalMs *= 2\n continue\n }\n if (!(error instanceof PlatformAuthError) || !isRecord(error.body)) throw error\n if (error.body.error === 'authorization_pending') continue\n if (error.body.error === 'slow_down') {\n intervalMs += 5_000\n continue\n }\n throw error\n }\n }\n throw new PlatformAuthError('Device authorization expired', 400, { error: 'expired_token' })\n }\n\n private async token(params: Record<string, string>, signal?: AbortSignal): Promise<OidcTokens> {\n const res = await this.post(`${this.baseUrl}/api/auth/oauth2/token`, params, signal)\n const body: unknown = await res.json().catch(() => null)\n if (!res.ok)\n throw new PlatformAuthError(\n oauthError(body, `Platform token request failed (${res.status})`),\n res.status,\n body,\n )\n return parseTokens(body, res.status)\n }\n\n private post(\n url: string,\n params: Record<string, string>,\n signal?: AbortSignal,\n includeResources = true,\n ): Promise<Response> {\n const body = new URLSearchParams(params)\n const headers: Record<string, string> = { 'content-type': 'application/x-www-form-urlencoded' }\n if (this.clientSecret) {\n // RFC 6749 section 2.3.1: form-encode each component before HTTP Basic.\n headers.authorization = `Basic ${btoa(`${formComponent(this.clientId)}:${formComponent(this.clientSecret)}`)}`\n } else body.set('client_id', this.clientId)\n if (includeResources) for (const resource of this.resources) body.append('resource', resource)\n return this.fetchImpl(url, { method: 'POST', headers, body, redirect: 'error', signal })\n }\n}\n"],"mappings":";;;AAoDA,IAAa,oBAAb,cAAuC,MAAM;CAGzB;C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kBACR,WAAW,MAAM,kCAAkC,IAAI,OAAO,EAAE,GAChE,IAAI,QACJ,IACF;EACF,OAAO,YAAY,MAAM,IAAI,MAAM;CACrC;CAEA,KACE,KACA,QACA,QACA,mBAAmB,MACA;EACnB,MAAM,OAAO,IAAI,gBAAgB,MAAM;EACvC,MAAM,UAAkC,EAAE,gBAAgB,oCAAoC;EAC9F,IAAI,KAAK,cAEP,QAAQ,gBAAgB,SAAS,KAAK,GAAG,cAAc,KAAK,QAAQ,EAAE,GAAG,cAAc,KAAK,YAAY,GAAG;OACtG,KAAK,IAAI,aAAa,KAAK,QAAQ;EAC1C,IAAI,kBAAkB,KAAK,MAAM,YAAY,KAAK,WAAW,KAAK,OAAO,YAAY,QAAQ;EAC7F,OAAO,KAAK,UAAU,KAAK;GAAE,QAAQ;GAAQ;GAAS;GAAM,UAAU;GAAS;EAAO,CAAC;CACzF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as readVerifiedArtifact, D as verifyMaterializedWorkspace, E as verifyMaterializedProfileWorkspace, F as embeddedCandidateArtifact, I as immutableCandidateValue, K as errorMessage, L as omitTopLevelDigest, M as canonicalCandidateDigest$1, N as canonicalCandidateDocument, O as verifyWorkspaceSnapshotArtifacts, P as deepFreezeCandidate, R as sha256Bytes$1, S as readMaterializedWorkspaceFiles, T as verifyBytes, _ as isWellFormedUnicode, d as persistCandidateOutputArtifact, f as readCandidateGitHubResource, g as assertExactObjectKeys, h as verifyTaskOutcomePatch, j as canonicalCandidateBytes$1, m as verifyTaskCheckout, p as verifyCandidateCode, y as artifactCacheKey } from "./workspace-streams-DkijayqX.js";
|
|
2
2
|
import { i as redactProtectedValue, n as createProtectedRecordRedactor, r as redactProtectedReason, t as assertNoProtectedBytes } from "./protected-redaction-DylCC_ot.js";
|
|
3
|
-
import { f as parseAgentCandidateProfileActivation, n as PI_CANDIDATE_SESSION_DIR_ENV, o as assertCandidateProfileExecutionSupport, s as candidateProfileAgentPaths, t as PI_CANDIDATE_AGENT_DIR_ENV, u as materializeAgentCandidateProfilePlan } from "./profile-
|
|
3
|
+
import { f as parseAgentCandidateProfileActivation, n as PI_CANDIDATE_SESSION_DIR_ENV, o as assertCandidateProfileExecutionSupport, s as candidateProfileAgentPaths, t as PI_CANDIDATE_AGENT_DIR_ENV, u as materializeAgentCandidateProfilePlan } from "./profile-CHXYmpGd.js";
|
|
4
4
|
import { agentCandidateArtifactRefSchema, agentCandidateBenchmarkResultEvidenceSchema, agentCandidateBenchmarkSuiteSchema, agentCandidateBenchmarkTaskSchema, agentCandidateBundleSchema, agentCandidateContainerSchema, agentCandidateExecutionLimitsSchema, agentCandidateExecutionPlanEvidenceSchema, agentCandidateExecutionPlanMaterialSchema, agentCandidateMaterializationReceiptSchema, agentCandidateModelAccessNetworkSchema, agentCandidateModelSettlementEvidenceSchema, agentCandidateProfilePlanEvidenceSchema, agentCandidateResolvedModelSchema, agentCandidateRunCellSchema, agentCandidateRunReceiptSchema, agentCandidateTaskOutcomeEvidenceSchema, agentCandidateTaskOutcomeSpecSchema, agentCandidateTerminationSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema, sha256DigestSchema } from "@tangle-network/agent-interface";
|
|
5
5
|
import { REDACTION_VERSION, isLlmSpan } from "@tangle-network/agent-eval";
|
|
6
6
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
@@ -3581,4 +3581,4 @@ function profileFileIdentity(root, relPath) {
|
|
|
3581
3581
|
//#endregion
|
|
3582
3582
|
export { recoveredTerminalRecord as A, candidateCleanupDeadline as C, assertTerminalAllowedInPhase as D, assertRecoveryMatchesStaged as E, terminalRecord as F, rejectedStage as M, requireStagedTerminal as N, assertTerminalMatchesClaim as O, sealTerminalDigest as P, candidateClaimFileInternals as S, withinCandidateCleanupDeadline as T, consumePreparedCandidateExecution as _, AGENT_CANDIDATE_EXECUTION_SUPPORT as a, assertAgentCandidateExecutionRoots as b, executePreparedAgentCandidate as c, sealAgentCandidateModelSettlement as d, usdToNanos as f, beginPreparedCandidateDisposal as g, assertPreparedCandidateIntegrity as h, candidateKnowledgeExecutionPaths as i, rejectedFinish as j, assertTerminalMatchesStaged as k, RecoveryAgentCandidateTraceStore as l, candidateExecutionClaim as m, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV as n, verifiedResourceTextByDigest as o, sealAgentCandidateExecutorStopAcknowledgement as p, CANDIDATE_KNOWLEDGE_ROOT_ENV as r, verifyAgentCandidateBundle as s, prepareAgentCandidateExecution as t, persistCandidateModelSettlementEvidence as u, CANDIDATE_TRACE_ENV as v, candidateCleanupTimeout as w, InMemoryAgentCandidateExecutionClaimStore as x, CANDIDATE_TRACE_TAGS as y };
|
|
3583
3583
|
|
|
3584
|
-
//# sourceMappingURL=prepare-
|
|
3584
|
+
//# sourceMappingURL=prepare-CD9kR0gS.js.map
|