@tangle-network/hub-sdk 0.23.0-develop.20260814095115.1610dd0 → 0.23.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 CHANGED
@@ -30,9 +30,7 @@ SaaS vs on-prem flips via env only — there is no per-client default URL.
30
30
  | `TANGLE_API_KEY` | One of | Long-lived API key (Bearer). User / API key principal. |
31
31
  | `TANGLE_HUB_CAPABILITY_TOKEN` | One of | Short-lived capability token (Bearer). Sandbox-runtime principal. Auto-minted server-side per action. |
32
32
 
33
- The two auth credentials are mutually exclusive — set exactly one. This
34
- mirrors the platform-api `hubSandboxEnvironmentSchema` rule
35
- (`exactly-one-api-key-or-capability-token`).
33
+ The two auth credentials are mutually exclusive — set exactly one.
36
34
 
37
35
  ### Examples
38
36
 
@@ -126,6 +124,29 @@ const hub = HubClient.fromEnv({
126
124
  });
127
125
  ```
128
126
 
127
+ ## Tool approvals
128
+
129
+ `tools.invoke()` preserves an existing `HUB_APPROVAL_REQUIRED` error instead of requesting another token.
130
+ The error retains the original approval ID and the server's action details.
131
+ Present that approval through the product's decision flow.
132
+ Set `approve: true` only after the caller has authorized that action.
133
+ Automatic capability-token minting remains available when the server returns no concrete approval.
134
+
135
+ ## GitHub OAuth scopes
136
+
137
+ Pass the exact scope set when the caller needs GitHub repository selection.
138
+ Platform accepts `read:user`, `repo`, and `read:org` together for this request.
139
+ It rejects a callback if GitHub grants a different set.
140
+ Omitting `requestedScopes` retains the existing default GitHub flow.
141
+ The SDK refuses a start response with different scopes, including responses from an older Platform deployment.
142
+
143
+ ```ts
144
+ const hub = HubClient.fromEnv();
145
+ await hub.connections.start("github", {
146
+ requestedScopes: ["read:user", "repo", "read:org"],
147
+ });
148
+ ```
149
+
129
150
  ## Workflows
130
151
 
131
152
  `hub.workflows` covers the `/v1/workflows` surface — the same resource the
@@ -218,19 +239,128 @@ product does not need a second workflow-run request.
218
239
  Callbacks may be retried; use `delivery.runId` as the durable idempotency key
219
240
  before starting product work.
220
241
 
242
+ ## Allowances and the paywall decision
243
+
244
+ A product that bills its end users sets a free allowance, and optionally a paid one, on a meter.
245
+ Hub admits every turn against it, counts turns per member and per line, and reads each payer's dollars from the ledger.
246
+ The product keeps only its checkout: after a payment it records the member as paid until the period ends.
247
+
248
+ ```ts
249
+ await hub.allowances.setPlan(`agent:${agentId}`, {
250
+ free: { turnsPerDay: 20, usdPerDay: 2 },
251
+ paid: { turnsPerDay: 200, usdPerDay: 5, priceUsdMonthly: 10 },
252
+ spendResourceType: "hosted_enrollment",
253
+ });
254
+
255
+ const turn = await hub.allowances.admit(`agent:${agentId}`, {
256
+ member: enrollmentId,
257
+ turnId: messageId,
258
+ line: lineId,
259
+ });
260
+ if (turn.decision === "paywall") return sendCheckoutLink();
261
+ if (turn.decision === "allowance_reached") return sendComeBackTomorrow();
262
+
263
+ // From the checkout webhook:
264
+ await hub.allowances.grant(`agent:${agentId}`, enrollmentId, {
265
+ expiresAt: periodEnd.toISOString(),
266
+ reference: subscriptionId,
267
+ });
268
+ ```
269
+
270
+ `admit` is idempotent by `turnId`, so a retried turn is never counted twice.
271
+ A member's dollars are the sum of today's ledger charges on keys bound to `(spendResourceType, member)` and on every key delegated below them, so delegate each member's key with that resource.
272
+ A paid member also has a funded capacity for the period: the price less Tangle's 10% fee, plus the free daily dollars for the period's 31 days.
273
+ With the plan above, that is $9 + $62 = $71 against the $155 that $5 a day would allow.
274
+ Past it, `admit` answers `allowance_reached`, and `turn.period` shows `spent`, `funded` and `remaining`.
275
+ Only the meter's owner may call these, signed in or with a root key of their own.
276
+ A delegated or resource-bound key is refused, so an end user's sandbox cannot grant itself the paid tier.
277
+
278
+ ## Shared-Line application dispatch
279
+
280
+ Before admitting a shared-Line callback, check its current Hub authority:
281
+
282
+ ```ts
283
+ const current = await hub.lines.applicationDispatchCurrent(
284
+ lineId,
285
+ messageId,
286
+ { attachmentId, memberId, memberRevision, senderAddress, binding, dispatchFence, dispatchDeadline },
287
+ callbackBearer,
288
+ );
289
+ ```
290
+
291
+ This uses the callback bearer alone; account credentials, cookies, and redirects are excluded.
292
+ It returns a boolean only from a successful, valid Hub response and makes no retry.
293
+ HTTP failures retain their status and code without response bodies or credential details.
294
+ Configure the client's injected `fetch` to enforce the caller's request deadline.
295
+ A current result authorizes this observation; native admission must still enforce its own expiry and deduplication contract.
296
+
221
297
  ## Exports
222
298
 
223
299
  - `HubClient`, `HubClient.fromEnv(options?)`
224
300
  - `HubConnectionsClient`, `HubPermissionsClient`, `HubTokensClient`,
225
301
  `HubChannelsClient`, `HubEventSubscriptionsClient`, `HubToolsClient`,
226
- `HubApprovalsClient`, `HubAuditClient`, `HubWorkflowsClient`
302
+ `HubApprovalsClient`, `HubAuditClient`, `HubWorkflowsClient`,
303
+ `HubAllowancesClient`
227
304
  - `deriveHubEventCallbackSecret`, `authenticateHubEventRequest`,
228
305
  `verifyHubEventSignature`, `parseHubEventDelivery`, `HubEventDeliveryError`
229
306
  - `HubSdkError` — typed `code: HubErrorCode`, redacted `details`, optional
230
307
  HTTP `status`
231
308
  - `HUB_URL_ENV_VAR`, `HUB_API_KEY_ENV_VAR`, `HUB_CAPABILITY_TOKEN_ENV_VAR` —
232
- string constants for the env-var names (mirrored by the platform-api
233
- `hub-sandbox-contract.ts` `z.literal(...)`)
309
+ string constants for the env-var names
234
310
  - `resolveHubBaseUrl(env?)`, `resolveHubAuth(env?)` — standalone resolvers
235
311
  with the same fail-loud contract as `fromEnv`
236
312
  - All request/response types from the `/v1/hub/*` contract
313
+
314
+
315
+ ## Link application login to explicit Hub permissions
316
+
317
+ Use the same `HubClient` for application management; do not add a product-local
318
+ HTTP client. These operations require the authenticated developer account, not
319
+ an app's OIDC access token. Customer grants are created only by the existing
320
+ session-authenticated `/cross-site/app-consent` flow.
321
+
322
+ ```ts
323
+ import { HubClient } from "@tangle-network/hub-sdk";
324
+
325
+ const hub = HubClient.fromEnv(); // developer account for app administration
326
+ const { app, clientSecret } = await hub.apps.create({
327
+ name: "Support assistant",
328
+ redirectUris: ["https://assistant.example/hub/callback"],
329
+ allowedScopes: ["github.issues.create"],
330
+ });
331
+ // Save clientSecret once in the application's server-side secret store.
332
+ await hub.apps.linkOAuthClient(app.id, oidcClientId);
333
+ const apps = await hub.apps.list(); // includes oauthClientId; never the secret
334
+ ```
335
+
336
+ `oidcClientId` is the application's already-registered Sign in with Tangle client.
337
+ Linking requires the same owner on both records and is immutable and one-to-one.
338
+ It does not reuse the two clients' secrets, change their IDs, create a user grant,
339
+ or authorize spending. Use separate app/client pairs for separate deployments.
340
+ Existing unlinked broker apps remain compatible. There is no automatic link by
341
+ name, callback domain, email, or ownership alone.
342
+
343
+ With a customer's authenticated Hub client, `hub.apps.grants.list()` returns only
344
+ that customer's active resource grants and `hub.apps.grants.revoke(grantId)`
345
+ revokes one idempotently. App administrators use `hub.apps.revoke(appId)` to
346
+ suspend the app, revoke all its customer grants, and disable its owned linked
347
+ OIDC client. An app's broker credential cannot call these management methods.
348
+
349
+ An app broker can create `new HubLineGrantsClient(options)` for a line approved by its owner.
350
+ Pass an `authHeaders` provider that mints a fresh scoped broker token for each call.
351
+ Pass the exact `workspaceId` and `workspaceAgentId` binding to every method.
352
+ The `current` response includes `intakeMode`, `priorAttachmentId`, and `priorAttachmentActive`.
353
+ An `owner_only` grant attaches one declared owner sender and rejects unknown senders.
354
+ The app cannot choose its own sender or change the approved intake mode in `attach`.
355
+
356
+ Broker execution keeps the one approved connection even when the invocation
357
+ omits `connectionId`; it never substitutes another account. Each one-shot broker
358
+ token is checked against current app policy and the exact active grant when
359
+ minted and consumed. Changing consent revokes the old binding, tokens and codes;
360
+ the fresh consent response supplies a new grant ID. Login disconnect revokes the
361
+ linked app's existing grants for that customer, not other customers or apps.
362
+ An operation already admitted to a provider may finish; revocation blocks new
363
+ admissions and minting, not external side effects already underway.
364
+
365
+ This is identity and resource delegation, **not** generalized spending delegation.
366
+ Existing product billing checks and action approvals continue to apply.