@collective-intelligence/external-apps-server-sdk 0.2.3 → 0.2.4

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
@@ -169,7 +169,9 @@ path, query, or fragment. Mount `createExternalApplicationBff` (or
169
169
  `createExternalApplicationBffNextHandlers`) once for federated auth, Resource
170
170
  proxy, and dedicated Capability forwarding. Pass `ciResources` to bind one
171
171
  Resource proxy mount per entity contract by `schemaFqn`; the BFF authorizes
172
- those mounts with `authorizeWithUserAuth`. Dedicated Capability forwarding sends
172
+ those mounts with `authorizeWithUserAuth`, whose `read` and `write` Access
173
+ Requirements are checked against the app's slice of the user's access
174
+ (default: `core.platform.knowledge` for both; CI decides each record again). Dedicated Capability forwarding sends
173
175
  the signed-in user's delegated token and the caller's `x-organization-id` by
174
176
  default. For an application without federated CI users, pass
175
177
  `capabilities: { authentication: { mode: "service", credentials },
@@ -184,10 +186,15 @@ so the backend runs only the Agent's own bindings and never the application's
184
186
  service authority. An Audit subject with `mappedUserId` is refused with `401`
185
187
  for a visitor caller. Forwarding covers `context`, `knowledge`, `agents`,
186
188
  `conversations` (continue and history), `skills`, `workflows`, and `runs/*`.
189
+ In user-token mode, and for each `ciResources` mount, the BFF passes CI's
190
+ answer to `auth.observeCiResponse`: a `401` or a changed `x-access-version`
191
+ drops the identity that lookups of that Access token reuse, so the next
192
+ lookup reads CI again at once.
187
193
  Reconstruct the public origin from
188
194
  `x-forwarded-host` / `x-forwarded-proto`. Compose a Fixed workflow route with
189
195
  `createFixedWorkflowRoute`: it rewrites that public origin, authorizes
190
- `getEntityContext` plus `requiredScopes`, stamps `x-organization-id` from the
196
+ `getEntityContext` plus an optional `requirement` (an Access Requirement on
197
+ the app's slice of the user's access), stamps `x-organization-id` from the
191
198
  session, POSTs `/application/v1/workflows/:id/runs`, and returns `{ runId }`.
192
199
  Configure exactly one server-owned target: `workflowId` for a workflow UUID or
193
200
  `workflowFqn` for its stable fully qualified name. The route rejects either
@@ -214,7 +221,6 @@ import {
214
221
  const { accessToken, expiresAt } = await exchangeMemberSession({
215
222
  credentials: { clientId, clientSecret },
216
223
  organizationId,
217
- scopes: ["context:read", "knowledge:write"],
218
224
  sessionToken: member.ciSessionToken,
219
225
  tenantUrl: "https://ci.example.com"
220
226
  })
@@ -228,8 +234,9 @@ await ci.context.get({ organizationId })
228
234
  Only a confidential application can exchange, with its client secret. CI
229
235
  applies the same checks as the browser login: the session is live, the member
230
236
  is not banned and belongs to the Organization, the application is enabled and
231
- allowed in that Organization, and the requested scopes are a non-empty subset
232
- of the application's scopes. The token acts as the member (`detached_user`),
237
+ allowed in that Organization, and the member enters the app: one of its grants
238
+ holds the app gate. The token acts as the member (`detached_user`), cut to the
239
+ app's Max Privileges,
233
240
  lasts 300 seconds, has no refresh token, and stops working when the member's
234
241
  CI session ends. `expiresAt` is counted from before the request and set 30
235
242
  seconds early, so exchange again once it passes; never send either token to
@@ -243,13 +250,13 @@ with a retryable `MemberSessionExchangeError`.
243
250
  A refusal throws `MemberSessionExchangeError`. `code` is CI's OAuth error:
244
251
  `invalid_grant` means the CI session ended or the member cannot act in the
245
252
  Organization, so sign the member in again. `invalid_client`,
246
- `unauthorized_client`, `invalid_scope` and `invalid_target` point at the
247
- application's credentials, type, scopes or allowed Organizations.
253
+ `unauthorized_client` and `invalid_target` point at the application's
254
+ credentials, type or allowed Organizations.
248
255
  `temporarily_unavailable` is retryable. On the wire this is the RFC 8693 grant
249
256
  `urn:ietf:params:oauth:grant-type:token-exchange` on `POST /oauth/token`, with
250
257
  `subject_token_type`
251
- `urn:collective-intelligence:params:oauth:token-type:session_token`, `scope`
252
- and `organization_id`.
258
+ `urn:collective-intelligence:params:oauth:token-type:session_token` and
259
+ `organization_id`; an external app sends no `scope`.
253
260
 
254
261
  ## Reuse Nest operations and local AI tools
255
262
 
@@ -503,7 +510,7 @@ succeeded before the new turn started count. A turn is
503
510
  retried message replay the same turn instead of adding one. Use each key for
504
511
  one message only; reusing it for a different message or conversation returns
505
512
  `conflict`.
506
- - The `ai:invoke` scope gates conversations.
513
+ - `core.platform.conversations` in the caller's grants gates conversations.
507
514
  - The Agent's current audience gates every turn and every `history` read. When
508
515
  an administrator removes the caller from the audience, the same caller gets
509
516
  `not_found` for its own conversations too.
@@ -511,14 +518,14 @@ succeeded before the new turn started count. A turn is
511
518
  visitor's `auditSubject` (no `mappedUserId`). Only a declared Agent with
512
519
  `audience: { anonymous: true }` that lists this application admits it. The
513
520
  visitor's turns run with the Agent's own bindings under an anonymous visitor
514
- subject, never with the application's scopes. Visitors are separate owners:
521
+ subject, never with the application's grants. Visitors are separate owners:
515
522
  one visitor never reads another visitor's conversation.
516
523
 
517
524
  ## Messages
518
525
 
519
526
  `messages.send` sends one message through a messaging connection of the
520
527
  Organization, for example a Telegram bot or a WhatsApp Business Account. The
521
- application needs the `messaging:send` scope, and an administrator must grant
528
+ caller needs `core.platform.messaging` in its grants, and an administrator must grant
522
529
  the connection to the application on its administration page.
523
530
 
524
531
  ```ts
@@ -562,46 +569,70 @@ const sent = await ci.messages.send({
562
569
  reached its rate limit; it is retryable, and the client repeats it with the
563
570
  same key.
564
571
 
565
- ## Application users and roles
572
+ ## Members, guests, grants and Groups (`ci.access`)
566
573
 
567
- Use `ci.users` and `ci.roles` with a delegated user token or service
568
- credentials. CI checks the caller's current `users.create` and `assignRoles`
569
- permissions. These methods replace the former `ci.members` API.
574
+ `ci.access` manages the access of one Organization from your server. Call it
575
+ with the app's server credentials (`mode: "service"`), which act with the
576
+ grants an administrator gave the app's server, or with a service principal's
577
+ API key as the delegated token. CI authorizes each call with the caller's
578
+ Tuples: members and invitations need `admin.users`, guests `admin.guests`,
579
+ grants `admin.grants`, Groups `admin.groups`, and the read-only model
580
+ `admin.profiles`. A refused call rejects with `ServerAccessError` (`status`
581
+ and CI's error `body`). Calls are not retried.
570
582
 
571
583
  ```ts
572
- const created = await ci.users.createOrGet({
573
- email: "info@rossi.example",
574
- name: "Rossi Srl",
575
- organizationId,
576
- roles: ["patient"],
577
- serverRole: "onboarding" // Optional for service calls; omission uses the credential default.
584
+ const created = await ci.access.members.create({
585
+ email: "ada@example.test",
586
+ grants: [{ profile: "clinic.profiles.patient" }],
587
+ kind: "guest",
588
+ mode: "direct",
589
+ organizationId
590
+ })
591
+
592
+ const result = await ci.access.grants.sync({
593
+ grants: [
594
+ {
595
+ fqn: "clinic.patients.ada",
596
+ grantee: { user: { email: "ada@example.test" } },
597
+ profile: "clinic.profiles.patient"
598
+ }
599
+ ],
600
+ namespace: "clinic.patients",
601
+ organizationId
578
602
  })
579
- // On success: created.value.result = { userId, email, name, created, kind }
580
- // kind is "member" or "external_app_user".
603
+ // result = { created, updated, deleted, unchanged }: Access Grant FQNs.
581
604
  ```
582
605
 
583
- - `createOrGet` reuses the person's auth identity. A new app user has no
584
- Organization membership. An existing member remains a member.
585
- - `checkEmail({ organizationId, email })` asks whether `createOrGet` would
586
- accept the email, without creating anything. The result is
587
- `{ usable: true }` or `{ usable: false, reason }`, with `user_unavailable`
588
- or `target_inactive` as `createOrGet` would refuse. An unknown email is
589
- usable. It needs service credentials and `users.create`.
590
- - `get({ organizationId, userId })` and
591
- `list({ organizationId, page?, pageSize? })` read users accessible to this
592
- app. A list result contains `items`.
593
- - `deactivate({ organizationId, userId })` ends access to the calling app for
594
- an app user it may deactivate; it does not remove Organization membership.
595
- - `roles.list({ organizationId })` returns `items` with role `id` and `key`.
596
- `roles.assign({ organizationId, userId, roles })` and `roles.revoke(...)`
597
- change this app's assignments within the caller's `assignRoles` permission.
598
- They cannot write Organization Roles, Groups, or another app's roles.
599
- - Pass `serverRole` on a service request to select an allowed Server Role via
600
- `x-external-server-role`. It applies only to that request; credentials and
601
- subsequent calls retain their default. It does not impersonate a user.
602
- - Refusals preserve the structured error, including a reason such as
603
- `role_not_assignable`. Non-retryable refusals are returned without retrying.
604
- CI records the actual user, or application and Server Role, as the actor.
606
+ - `members`: `create` (directly or by invitation, with at least one grant;
607
+ Grant Authority decides each grant), `get`, `list` (`after`, `email`,
608
+ `limit`), `findByEmail`, `suspend`, `resume` and `remove`. An app server
609
+ creates, reads and changes only its own guests.
610
+ - `invitations`: `list` (`status`, `page`, `limit`) and `revoke`. Only a
611
+ service principal invites, so an app server is refused.
612
+ - `grants`: `create`, `get`, `update` and `delete` by `grantId` or `fqn`,
613
+ `list` by `userId`, `groupId` or `namespace`, and `sync` of a namespace.
614
+ A grant names its grantee as `{ user: { email } }`,
615
+ `{ group: { fqn }, coverage }`, `{ servicePrincipal: "<fqn>" }`, or an
616
+ app's `{ applicationServer: "<app fqn>" }` (a `server` profile) or
617
+ `{ applicationVisitors: "<app fqn>" }` (an `anonymous` profile). Every
618
+ grant has an Access Grant FQN; a Group without an FQN gets grants only in
619
+ the Dashboard.
620
+ - `groups`: `create`, `get`, `list` (`page`, `limit`), `update`, `delete`,
621
+ `addMember` and `removeMember` by `userId`. A member change of a Group
622
+ that a holders-only grant reaches also needs Grant Authority over that
623
+ grant. An app server reads Groups but writes none.
624
+ - `profiles.list`, `profiles.get`, `catalog.list`, `axes.list`,
625
+ `maxPrivileges.list`, `maxPrivileges.get`, `knowledgePolicies.list` and
626
+ `knowledgePolicies.forSchema({ organizationId, schemaFqn })` read the
627
+ declared model; the core and packages stay its source of truth.
628
+ `forSchema` answers the policies that decide the reads and the writes of
629
+ the schema, as CI fills its Policy Slots.
630
+ - A paged list answers `{ items, next }`: pass `next` back as `after`
631
+ (members) or `page` (Groups, invitations) to read the page after it.
632
+ - `snapshot({ organizationId, userId })` reads a user's Access Snapshot;
633
+ `explain` tells why a principal may use a capability or act on a record.
634
+ - There is no `ci.users` or `ci.roles`: app users became guests, and roles
635
+ became Access Grants of profiles.
605
636
 
606
637
  ## Durable files
607
638
 
@@ -634,7 +665,7 @@ await ci.workflows.invoke({
634
665
  public URL, and another Organization cannot read it.
635
666
  - `attachments.upload` is different: its file belongs to one run and expires
636
667
  after 24 hours.
637
- - It needs the `ai:attachments` scope. Only service credentials may call it: a
668
+ - It needs `core.platform.attachments` in the app server's grants. Only service credentials may call it: a
638
669
  delegated user token or an anonymous visitor gets `operation_not_allowed`.
639
670
 
640
671
  ### Entity File fields
@@ -785,9 +816,8 @@ A schema declares its accounts field to name the users that act for each of its
785
816
  records (see the [Knowledge User fields](../../../docs/reference/knowledge-user-fields.md)
786
817
  reference). CI stores no other link between a user and a record, and offers no
787
818
  operation that lists or changes one: write the accounts field as an
788
- administrator, with the workflow account step or with the Default Server Role
789
- credential. A policy reads the field as `resource` path `["data", "accounts"]`
790
- and the caller as `subject` path `["user", "id"]`.
819
+ administrator or with the workflow account step. A Knowledge Data Condition
820
+ reads it with `isMe("accounts")` or `includesMe("accounts")`.
791
821
 
792
822
  - A delegated user's `/application/v1/resources` and `knowledge_*` calls, and
793
823
  the Agents, Skills and workflows the user runs, decide under the user's
@@ -1570,13 +1600,16 @@ const handle = createResourceHttpHandler({
1570
1600
  ```
1571
1601
 
1572
1602
  `auth` is the existing `createFederatedAuth(...)` instance. Its server-only
1573
- `getEntityContext` resolves current CI application, user, organization, scopes,
1574
- the user's effective app roles and App Permissions. CI never sends Group IDs or
1575
- Platform Permissions. The browser session JSON at `<basePath>/session` carries
1576
- `expiresAt` and an `identity` with `userId`, `organizationId`, `appId`, `kind`
1577
- (`member` or `external_app_user`), `roles`, `appPermissions`, `email` and
1578
- `name`; it never carries the Access token. A user without a role on the app has
1579
- no session and no entity access. Local Better Auth sessions do
1603
+ `getEntityContext` resolves the CI application, user, organization and the
1604
+ app's slice of the user's capabilities (`capabilities`) for the session's
1605
+ Access token; CI is asked for that identity once per Access
1606
+ token, and again only after an observed CI answer shows a change. CI never sends Group IDs. The browser session JSON at
1607
+ `<basePath>/session` carries `expiresAt` and an `identity` with `userId`,
1608
+ `organizationId`, `appId`, `kind` (`member`, `guest`, or `null` for a tenant
1609
+ user without a membership), `access` (the app's slice of the user's access),
1610
+ `email` and `name`; it never carries the Access token. A user that does not
1611
+ enter the app (no capability at or below the app gate) has no session and no
1612
+ entity access. Local Better Auth sessions do
1580
1613
  not establish CI entity authority. Browser framework adapters require this
1581
1614
  verified context instead of boolean authorization. Machine gateway calls retain
1582
1615
  their separate caller policy.
@@ -1652,7 +1685,7 @@ pagination, predicates, grouping, aggregates or managed extraction.
1652
1685
  Import `createFederatedAuth` from
1653
1686
  `@collective-intelligence/external-apps-server-sdk/auth/federated`. Supply the
1654
1687
  browser-visible HTTPS application origin, CI issuer, OAuth client, organization,
1655
- audience, scopes, and an application-owned atomic session store. The facade owns
1688
+ audience, and an application-owned atomic session store. The facade owns
1656
1689
  PKCE login, callback, session inspection and logout under `/api/auth` by default.
1657
1690
 
1658
1691
  `applicationOrigin` accepts one HTTPS origin or a list. Use a list when one
@@ -1665,7 +1698,6 @@ const auth = createFederatedAuth({
1665
1698
  clientId,
1666
1699
  issuer,
1667
1700
  organizationId,
1668
- scopes: ["knowledge:read"],
1669
1701
  session: { kind: "sealed_cookie", secrets }
1670
1702
  })
1671
1703
  ```
@@ -1692,9 +1724,12 @@ authorization code to its `redirect_uri`, so an unregistered callback fails at
1692
1724
  authorization.
1693
1725
 
1694
1726
  The store persists only hashed opaque-cookie state, token grants and revisions;
1695
- the browser receives a `Secure`, `HttpOnly`, `SameSite=Lax` host cookie. Every
1696
- session lookup revalidates the short-lived CI identity. Revoked or expired CI
1697
- access ends application authorization on the next validation. A confidential
1727
+ the browser receives a `Secure`, `HttpOnly`, `SameSite=Lax` host cookie. A
1728
+ session lookup reads the CI identity of its Access token once per token and
1729
+ again after a `401` or a changed `x-access-version` that
1730
+ `auth.observeCiResponse` sees. A revocation therefore ends application
1731
+ authorization at the next token renewal (at most 300 seconds) or at once when a
1732
+ forwarded CI answer reports it. A confidential
1698
1733
  OAuth client may supply `clientSecret`; a public PKCE client omits it. The
1699
1734
  client type decides how long the User session lasts; see
1700
1735
  [Session lifetime and renewal](#session-lifetime-and-renewal).
@@ -1732,8 +1767,9 @@ each `sessionTtlSeconds` value in the range and gives no warning.
1732
1767
  `getSession`, `getAccessToken`, `getEntityContext` and
1733
1768
  `GET <basePath>/session` are the session lookups. With renewal, each lookup
1734
1769
  first gets a new Access token when the current one is expired or expires in 30
1735
- seconds or less. Then it checks the current identity at `/oauth/identity`. A
1736
- lookup never returns an expired Access token. Lookups at the same time share
1770
+ seconds or less. Then it reads the identity of that token at
1771
+ `/oauth/identity`, once per token. A lookup never returns an expired Access
1772
+ token. Lookups at the same time share
1737
1773
  one renewal request.
1738
1774
 
1739
1775
  The SDK writes the cookie or the store record one time, at sign-in. A renewal
@@ -1772,10 +1808,8 @@ A renewal applies the same admission rule as `/oauth/identity`:
1772
1808
 
1773
1809
  - the external Application is enabled;
1774
1810
  - the CI session is live;
1775
- - the user is not banned, is a member or an active External App User of the
1776
- Organization, and holds at least one role on the app other than
1777
- `anonymous` (Direct Role Assignments replace the roles that Groups give);
1778
- - the scopes of the sign-in are still allowed.
1811
+ - the user is not banned and enters the app: its Tuples hold the app gate
1812
+ or a capability below it.
1779
1813
 
1780
1814
  A refusal ends nothing. When the condition is corrected, the same Renewal
1781
1815
  credential renews again. A Federated authorization ends for good only by one
@@ -1853,10 +1887,10 @@ import {
1853
1887
  const tokens = createAccessTokenVerifier(readApplicationEnrollment(process.env))
1854
1888
 
1855
1889
  const caller = await tokens.verify(bearerToken)
1856
- // userId, organizationId, applicationId, clientId, scopes, sessionId, expiresAt
1890
+ // userId, organizationId, applicationId, clientId, sessionId, expiresAt
1857
1891
 
1858
1892
  const identity = await tokens.identity(bearerToken, { signal: request.signal })
1859
- // the same fields, and user { id, email, name }, kind, roles, appPermissions
1893
+ // the same fields, and user { id, email, name }, kind, access
1860
1894
  ```
1861
1895
 
1862
1896
  - `verify` is offline against the issuer key set: ES256 signature, issuer,
@@ -1864,10 +1898,10 @@ const identity = await tokens.identity(bearerToken, { signal: request.signal })
1864
1898
  It does not see a revocation before the token expires.
1865
1899
  - `identity` runs `verify`, then reads CI's current identity for the token and
1866
1900
  checks that it describes the same grant. Use it when the API needs the
1867
- user's app roles or App Permissions, or must stop at once when CI revokes
1868
- the token or a role. It
1901
+ app's slice of the user's access (`access.capabilities`), or must stop at
1902
+ once when CI revokes the token or the user leaves the app. It
1869
1903
  is one CI request for each call, with a 10-second limit; cache the result
1870
- for as long as a role change may take to reach your API. Pass the `signal`
1904
+ for as long as an access change may take to reach your API. Pass the `signal`
1871
1905
  of the request you serve: when it aborts, the CI request ends and the call
1872
1906
  rejects with the abort reason.
1873
1907
 
@@ -1885,7 +1919,8 @@ const resource = defineCiEntityResource({
1885
1919
  definition: leadDefinition,
1886
1920
  tenantUrl: "https://ci.example.com",
1887
1921
  organizationId,
1888
- schemaFqn
1922
+ schemaFqn,
1923
+ observeCiResponse: auth.observeCiResponse
1889
1924
  })
1890
1925
  ```
1891
1926
 
@@ -2105,7 +2140,7 @@ CI-backed resources created by `defineCiEntityResource` accept the common client
2105
2140
  mounts `POST /records/:parentId/relation-members/search` below the resource base
2106
2141
  path and forwards `{ field, ...query }` to the bound CI schema route. Existing
2107
2142
  verified tenant, organization, resource and user-grant checks still apply;
2108
- `authorizeWithUserAuth` classifies this operation under `readScope`.
2143
+ `authorizeWithUserAuth` classifies this operation under its `read` Requirement.
2109
2144
 
2110
2145
  The page envelope and exact totals remain unchanged. Member records are JSON
2111
2146
  objects validated independently of the parent schema, as are member query field