@pontive/server 0.0.0-stage → 1.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +146 -2
  2. package/dist/auth.d.cts +34 -0
  3. package/dist/auth.d.ts +34 -0
  4. package/dist/authorization.cjs +2 -0
  5. package/dist/authorization.cjs.map +1 -0
  6. package/dist/authorization.d.cts +222 -0
  7. package/dist/authorization.d.ts +222 -0
  8. package/dist/authorization.js +153 -0
  9. package/dist/authorization.js.map +1 -0
  10. package/dist/browser-mode.d.cts +23 -0
  11. package/dist/browser-mode.d.ts +23 -0
  12. package/dist/config.d.cts +131 -0
  13. package/dist/config.d.ts +131 -0
  14. package/dist/cookies.d.cts +50 -0
  15. package/dist/cookies.d.ts +50 -0
  16. package/dist/env.d.cts +44 -0
  17. package/dist/env.d.ts +44 -0
  18. package/dist/index.cjs +5 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +20 -0
  21. package/dist/index.d.ts +20 -0
  22. package/dist/index.js +700 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/keyless.cjs +16 -0
  25. package/dist/keyless.cjs.map +1 -0
  26. package/dist/keyless.d.cts +244 -0
  27. package/dist/keyless.d.ts +244 -0
  28. package/dist/keyless.js +355 -0
  29. package/dist/keyless.js.map +1 -0
  30. package/dist/management-credential-BNyhHagG.cjs +2 -0
  31. package/dist/management-credential-BNyhHagG.cjs.map +1 -0
  32. package/dist/management-credential-VhmMzGDl.js +39 -0
  33. package/dist/management-credential-VhmMzGDl.js.map +1 -0
  34. package/dist/management-credential.d.cts +40 -0
  35. package/dist/management-credential.d.ts +40 -0
  36. package/dist/mcp-auth-info-BGyWua_9.js +19 -0
  37. package/dist/mcp-auth-info-BGyWua_9.js.map +1 -0
  38. package/dist/mcp-auth-info-jblMsSJo.cjs +2 -0
  39. package/dist/mcp-auth-info-jblMsSJo.cjs.map +1 -0
  40. package/dist/mcp-auth-info.d.cts +17 -0
  41. package/dist/mcp-auth-info.d.ts +17 -0
  42. package/dist/oidc--We55Nrh.cjs +2 -0
  43. package/dist/oidc--We55Nrh.cjs.map +1 -0
  44. package/dist/oidc-CB0FqjFz.js +131 -0
  45. package/dist/oidc-CB0FqjFz.js.map +1 -0
  46. package/dist/oidc.d.cts +80 -0
  47. package/dist/oidc.d.ts +80 -0
  48. package/dist/organization.d.cts +35 -0
  49. package/dist/organization.d.ts +35 -0
  50. package/dist/preview-hosts.d.cts +33 -0
  51. package/dist/preview-hosts.d.ts +33 -0
  52. package/dist/refresh.d.cts +28 -0
  53. package/dist/refresh.d.ts +28 -0
  54. package/dist/resource-server-express.cjs +2 -0
  55. package/dist/resource-server-express.cjs.map +1 -0
  56. package/dist/resource-server-express.d.cts +73 -0
  57. package/dist/resource-server-express.d.ts +73 -0
  58. package/dist/resource-server-express.js +57 -0
  59. package/dist/resource-server-express.js.map +1 -0
  60. package/dist/resource-server-mcp.cjs +2 -0
  61. package/dist/resource-server-mcp.cjs.map +1 -0
  62. package/dist/resource-server-mcp.d.cts +70 -0
  63. package/dist/resource-server-mcp.d.ts +70 -0
  64. package/dist/resource-server-mcp.js +59 -0
  65. package/dist/resource-server-mcp.js.map +1 -0
  66. package/dist/resource-server.cjs +2 -0
  67. package/dist/resource-server.cjs.map +1 -0
  68. package/dist/resource-server.d.cts +290 -0
  69. package/dist/resource-server.d.ts +290 -0
  70. package/dist/resource-server.js +301 -0
  71. package/dist/resource-server.js.map +1 -0
  72. package/dist/seal.d.cts +3 -0
  73. package/dist/seal.d.ts +3 -0
  74. package/dist/server-auth.d.cts +100 -0
  75. package/dist/server-auth.d.ts +100 -0
  76. package/package.json +96 -4
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # @pontive/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Pontive SDK for TypeScript servers, on Web `Request`/`Response`. The same SDK
4
+ for Python is [`pontive`](https://pypi.org/project/pontive/) and for Go
5
+ [`github.com/pontivehq/pontive-go`](https://github.com/pontivehq/pontive-go).
6
+
7
+ ```sh
8
+ npm install @pontive/server
9
+ ```
10
+
11
+ | Entry | For |
12
+ | --- | --- |
13
+ | `@pontive/server` | Apps: sign-in routes, the session and safe token refresh. See [server sessions](https://www.pontive.com/docs/sdk/server-sessions). |
14
+ | `@pontive/server/resource-server` | APIs and MCP servers that accept Pontive access tokens. |
15
+ | `@pontive/server/authorization` | Permission checks and listings for a verified principal, delegated or not. |
16
+ | `@pontive/server/resource-server/express` | Its Express (and Node `http`) adapter. |
17
+ | `@pontive/server/resource-server/mcp` | Its MCP TypeScript SDK adapter. Needs `@modelcontextprotocol/sdk`. |
18
+
19
+ ## Resource server
20
+
21
+ Protect an API or an MCP server with tokens your Pontive instance issued for
22
+ it. Tokens are verified locally against the issuer's cached keys; missing or
23
+ failing tokens get the `401`/`403` challenges MCP clients follow; and the API's
24
+ protected resource metadata (RFC 9728) is served for you.
25
+
26
+ ```ts
27
+ import { createResourceServer } from "@pontive/server/resource-server";
28
+
29
+ const rs = createResourceServer({
30
+ issuer: "https://acme.auth.us.pontive.app", // or a list, for several auth domains
31
+ resource: "https://mcp.acme.com/mcp", // the API's identifier
32
+ scopes: ["files:read", "files:write"],
33
+ });
34
+
35
+ // Any Web-standard handler (Next route handlers, Hono, Workers):
36
+ const guard = rs.requireBearer({ scopes: ["files:read"] });
37
+ export async function POST(request: Request) {
38
+ const caller = await guard(request);
39
+ if (caller instanceof Response) return caller; // 401 or 403, with WWW-Authenticate
40
+ return Response.json({ hello: caller.sub, kind: caller.kind });
41
+ }
42
+
43
+ // The metadata routes, with CORS preflight:
44
+ // app/.well-known/oauth-protected-resource/mcp/route.ts
45
+ export const { GET, OPTIONS } = rs.metadataRoute;
46
+ ```
47
+
48
+ ```ts
49
+ // Express
50
+ import { requireBearer, wellKnown } from "@pontive/server/resource-server/express";
51
+
52
+ app.use(wellKnown(rs));
53
+ app.post("/mcp", requireBearer(rs, { scopes: ["files:read"] }), (req, res) => {
54
+ // req.principal, and req.auth for the MCP SDK's transport
55
+ });
56
+ ```
57
+
58
+ ```ts
59
+ // The MCP SDK's own bearer middleware
60
+ import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
61
+ import { bearerAuthOptions, principalOf } from "@pontive/server/resource-server/mcp";
62
+
63
+ app.post("/mcp", requireBearerAuth(bearerAuthOptions(rs, { scopes: ["files:read"] })), handler);
64
+ // in a tool: principalOf(extra.authInfo)
65
+ ```
66
+
67
+ ```ts
68
+ // Per-tool scopes (tool import, pontive-spec 44 §12): a token holding any scope that lists the tool may call it
69
+ import { requireToolScopes } from "@pontive/server/resource-server/express";
70
+ import { withToolScopes } from "@pontive/server/resource-server/mcp";
71
+
72
+ const rs = createResourceServer({ issuer, resource, scopes: api.scopes }); // the dashboard's scopes, with their tools
73
+ app.post("/mcp", requireBearer(rs), requireToolScopes(rs), handler); // 403 insufficient_scope before the transport
74
+ const server = withToolScopes(new McpServer({ name: "acme-files", version: "1.0.0" }), rs); // and in every handler
75
+ // Web-standard: rs.authorizeToolCalls(principal, body), or rs.requireTool(name) for a one-tool route
76
+ ```
77
+
78
+ The full guide: [Protect an MCP server with Pontive](https://www.pontive.com/docs/sdk/mcp-server).
79
+
80
+ ## Authorization checks
81
+
82
+ `createAuthorizationClient` checks permissions for the `Principal` the
83
+ resource server verified. For a **delegated** principal (an agent acting for a
84
+ user: `principal.isDelegated`, `principal.actor.kind === "agent"`), `sub` is
85
+ the user but the caller is the agent: never read or write by `principal.sub`
86
+ alone. The client sends the token, and Pontive answers for the intersection of
87
+ the user and the agent. Any other principal is checked as itself.
88
+
89
+ The client speaks AuthZEN (OpenID AuthZEN Authorization API 1.0) to the
90
+ instance's region's authz host — `POST /access/v1/evaluation`,
91
+ `/access/v1/evaluations` and `/access/v1/search/resource` on
92
+ `https://authz.{region}.pontive.com`, derived from `managementUrl` (its
93
+ `api.` label becomes `authz.`), or `authzUrl` when you set it. `managementUrl`
94
+ is read as the management API's origin: a `/v1`, `/mgmt` or `/mgmt/v1` suffix
95
+ is dropped, so the routes are `{origin}/v1/…`, and the token audience is the
96
+ origin itself, `https://api.us.pontive.com` (route review D51).
97
+
98
+ ```ts
99
+ import { createAuthorizationClient } from "@pontive/server/authorization";
100
+
101
+ const authz = createAuthorizationClient({
102
+ managementUrl: "https://api.us.pontive.com", // the authz host is https://authz.us.pontive.com
103
+ issuer: "https://acme.auth.us.pontive.app", // to exchange client credentials
104
+ credential: { clientId: "svc_…", clientSecret: "…" }, // holds sys:authz:check; or a key, or () => token
105
+ });
106
+
107
+ await authz.check(principal, "doc:write", { type: "doc", id: "doc_1" }, { scopes: ["files:write"] });
108
+ await authz.checkBatch(principal, items); // one answer per item, 100 per request
109
+ await authz.listAccessible(principal, { resourceType: "doc", permission: "doc:read" }); // permission required when delegated; { data, nextPageToken, total }
110
+ await authz.filterAccessible(principal, chunks, (c) => c.docId, { resourceType: "doc", permission: "doc:read" });
111
+ ```
112
+
113
+ `filterAccessible` keeps the items the principal may access, in order: up to
114
+ `threshold` distinct ids (default 100, one batch request) are checked by
115
+ batch, more by listing the principal's reach (capped at 10,000 resources,
116
+ `ListingTooLargeError` beyond). The guide:
117
+ [Permission-aware RAG with Pontive](https://www.pontive.com/docs/sdk/permission-aware-rag).
118
+
119
+ Pontive does not interpret scopes in a check: pass `scopes` and the answer is
120
+ also held to the token's granted scopes. A refused request throws
121
+ `AuthorizationError` with `status` and the authz host's `error.code`
122
+ (`invalid_token` means the token must be obtained again; `actor_invalid`,
123
+ `actor_refused` and `delegated_permission_required` are the delegated
124
+ refusals); a denial resolves `false`. A token is never put in a URL: every
125
+ call is a `POST`, and a delegated principal is the subject
126
+ `{ "type": "token", "id": <token> }` in the body.
127
+
128
+ ## Using Pontive with a coding agent
129
+
130
+ Copy this block into your app's `AGENTS.md` (read by Codex, Cursor, Lovable, Claude Code and others).
131
+
132
+ <!-- BEGIN:pontive-agents -->
133
+ ### Using Pontive
134
+
135
+ This app uses [Pontive](https://www.pontive.com) for sign-in, sessions, organizations, roles and permissions.
136
+
137
+ - **Docs:** https://www.pontive.com/docs. Add `.md` to any page for Markdown; the index for agents is https://www.pontive.com/llms.txt. Read the page before writing Pontive code, and do not invent options, routes or claims it does not show.
138
+ - **MCP servers:** the docs, no sign-in: `https://www.pontive.com/docs/mcp`. Configuring the instance (apps, APIs, roles, organizations, users), with OAuth or a secret key: `https://mcp.pontive.com/mcp`.
139
+ - **Skills and plugins:** `npx skills add pontivehq/skills`, or the plugins at https://github.com/pontivehq/skills.
140
+ - **Packages:** `@pontive/nextjs` (Next.js), `@pontive/react` (React SPA), `@pontive/vue` (Vue), `@pontive/server` (Node servers, APIs and MCP servers: `/resource-server`, `/authorization`), `@pontive/pontkit-loader` (the Vite dev proxy), `@pontive/oidc-client` (the browser client). Never install or pin `@pontive/pontkit-core`. CLI: `npx pontive@latest` (`init`, `claim`, `status`, `migrate`).
141
+ - **Rules:**
142
+ - Secret keys (`pontive_sk_…`), client secrets and session secrets live only in server-side environment variables: never in browser code, a `NEXT_PUBLIC_` or `VITE_` variable, a log or a committed file. The app id (`app_…`) and auth domain are public.
143
+ - Build against a development instance (`…-<instance>.auth.<region>.pontive.dev`), never production.
144
+ - An API accepts only access tokens issued for it: check `typ` `at+jwt`, `iss`, `aud` (the API's identifier) and the scope.
145
+ - `roles` and `permissions` are arrays; check the permission you need. Tenant data keys on `org_id`, never `sub`.
146
+ - A delegated token (`act` claim) is an agent acting for the user: never act on `sub` alone.
147
+ <!-- END:pontive-agents -->
@@ -0,0 +1,34 @@
1
+ import { ServerAuthConfig } from './config.cjs';
2
+ import { KeylessRecord } from './keyless.cjs';
3
+ import { ServerAuth } from './server-auth.cjs';
4
+ /** This package's version, sent as `client.version` when keyless mode provisions. */
5
+ export declare const PONTIVE_SERVER_VERSION: string;
6
+ /** Options for framework packages built on this one (@pontive/nextjs). */
7
+ export interface ServerAuthOptions {
8
+ /** `client.name` when keyless mode provisions an instance. Default `@pontive/server`. */
9
+ clientName?: string;
10
+ /** The project root, where `.env.local` and `.pontive/` live. Default `process.cwd()`. */
11
+ projectDir?: string;
12
+ }
13
+ /** The route, under `basePath`, that sends the browser to a claim link (keyless mode). */
14
+ export declare const CLAIM_ROUTE = "claim";
15
+ /**
16
+ * Server-side sessions on Web `Request`/`Response`.
17
+ *
18
+ * Every field of `config` the app leaves out falls back to its `PONTIVE_*`
19
+ * variable (pontive-spec 47 §6.1), so `createServerAuth()` with nothing is a
20
+ * complete setup when the environment holds them. With no issuer anywhere, in
21
+ * development, it runs in **keyless mode** (§6.2): on first use it creates an
22
+ * unclaimed development instance, writes its settings to `.env.local` and
23
+ * `.pontive/keyless.json`, and uses them at once. Outside development a missing
24
+ * issuer is an error, as ever.
25
+ */
26
+ export declare function createServerAuth(config?: ServerAuthConfig, options?: ServerAuthOptions): ServerAuth;
27
+ /** Forgets the per-process keyless state. For tests. */
28
+ export declare function resetKeylessState(): void;
29
+ /**
30
+ * Says so, once, when the instance refuses the app's credentials (`401` from
31
+ * the token endpoint): it expired, or was claimed and its keys rotated. Keyless
32
+ * mode never creates another instance over it.
33
+ */
34
+ export declare function watchForRefusal(base: typeof fetch | undefined, record: KeylessRecord, logger: Pick<Console, "warn">): typeof fetch;
package/dist/auth.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { ServerAuthConfig } from './config.js';
2
+ import { KeylessRecord } from './keyless.js';
3
+ import { ServerAuth } from './server-auth.js';
4
+ /** This package's version, sent as `client.version` when keyless mode provisions. */
5
+ export declare const PONTIVE_SERVER_VERSION: string;
6
+ /** Options for framework packages built on this one (@pontive/nextjs). */
7
+ export interface ServerAuthOptions {
8
+ /** `client.name` when keyless mode provisions an instance. Default `@pontive/server`. */
9
+ clientName?: string;
10
+ /** The project root, where `.env.local` and `.pontive/` live. Default `process.cwd()`. */
11
+ projectDir?: string;
12
+ }
13
+ /** The route, under `basePath`, that sends the browser to a claim link (keyless mode). */
14
+ export declare const CLAIM_ROUTE = "claim";
15
+ /**
16
+ * Server-side sessions on Web `Request`/`Response`.
17
+ *
18
+ * Every field of `config` the app leaves out falls back to its `PONTIVE_*`
19
+ * variable (pontive-spec 47 §6.1), so `createServerAuth()` with nothing is a
20
+ * complete setup when the environment holds them. With no issuer anywhere, in
21
+ * development, it runs in **keyless mode** (§6.2): on first use it creates an
22
+ * unclaimed development instance, writes its settings to `.env.local` and
23
+ * `.pontive/keyless.json`, and uses them at once. Outside development a missing
24
+ * issuer is an error, as ever.
25
+ */
26
+ export declare function createServerAuth(config?: ServerAuthConfig, options?: ServerAuthOptions): ServerAuth;
27
+ /** Forgets the per-process keyless state. For tests. */
28
+ export declare function resetKeylessState(): void;
29
+ /**
30
+ * Says so, once, when the instance refuses the app's credentials (`401` from
31
+ * the token endpoint): it expired, or was claimed and its keys rotated. Keyless
32
+ * mode never creates another instance over it.
33
+ */
34
+ export declare function watchForRefusal(base: typeof fetch | undefined, record: KeylessRecord, logger: Pick<Console, "warn">): typeof fetch;
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("./management-credential-BNyhHagG.cjs");class T extends Error{constructor(t,r,d){super(d),this.status=t,this.code=r,this.name="AuthorizationError"}status;code}class _ extends Error{constructor(t,r){super(`filterAccessible: the principal reaches more than ${r} ${t} resources; filter fewer candidates, or pass threshold: Infinity to check them by batch`),this.resourceType=t,this.maxListed=r,this.name="ListingTooLargeError"}resourceType;maxListed}const w=100,I=w,x=1e4,q=100,L=e=>e.replace(/\/+$/,""),A=(e,t)=>{if(!t?.length)return!0;const r=new Set(e);return t.every(d=>r.has(d))},j=(e,t)=>e.isDelegated&&t?(t.scope??"").split(" ").filter(Boolean):e.scopes;function D(e){const t=k.managementBase(e);try{const r=new URL(t);return r.hostname.toLowerCase().startsWith("api.")?(r.hostname=`authz.${r.hostname.slice(4)}`,L(`${r.origin}${r.pathname}`)):t}catch{return t}}const U=e=>({action:{name:e.permission},resource:{type:e.resource.type,id:e.resource.id}}),$=e=>{const t=e&&typeof e=="object"?e.principal:void 0;return t&&typeof t=="object"?t:void 0},f=e=>typeof e=="string"&&e?e:void 0;async function M(e){let t;try{t=await e.json()}catch{return{}}if(!t||typeof t!="object")return{};const r=t;if(r.error&&typeof r.error=="object"){const d=r.error;return{code:f(d.code),message:f(d.message)}}return{code:f(r.error)??f(r.code),message:f(r.error_description)??f(r.message)}}function B(e){if(!e.managementUrl)throw new Error("authorization client: managementUrl is required");const t=e.fetch??((...n)=>fetch(...n)),r=`${e.authzUrl?L(e.authzUrl):D(e.managementUrl)}/access/v1`,d=k.managementTokenSource({credential:e.credential,managementUrl:e.managementUrl,issuer:e.issuer&&L(e.issuer),fetch:t}),b=async(n,s)=>{const i=await t(n,{method:"POST",headers:{authorization:`Bearer ${await d()}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(s)});if(!i.ok){const{code:o,message:a}=await M(i);throw new T(i.status,o,a??`authorization request failed: ${i.status}`)}return await i.json()},E=n=>n.isDelegated?{type:"token",id:n.token}:{type:n.kind,id:n.sub},F=async(n,s,i,o)=>{const a=await b(`${r}/evaluation`,{subject:E(n),...U({permission:s,resource:i})});return a.decision===!0&&A(j(n,$(a.context)),o?.scopes)},S=async(n,s,i)=>{const o=[];for(let a=0;a<s.length;a+=w){const u=s.slice(a,a+w),h=(await b(`${r}/evaluations`,{subject:E(n),evaluations:u.map(U),options:{evaluations_semantic:"execute_all"}})).evaluations??[];if(h.length!==u.length)throw new T(502,void 0,`evaluations answered ${h.length} of ${u.length} items`);for(const p of h)o.push(p.decision===!0&&A(j(n,$(p.context)),i?.scopes))}return o},v=async(n,s,i)=>{if(!s.resourceType)throw new Error("listAccessible: resourceType is required");if(n.isDelegated&&!s.permission)throw new T(400,"delegated_permission_required","a delegated listing needs a permission");if(!A(n.scopes,i?.scopes))return{data:[]};const o={...s.pageToken?{token:s.pageToken}:{},...s.limit!==void 0?{limit:s.limit}:{}},a=await b(`${r}/search/resource`,{subject:E(n),...s.permission?{action:{name:s.permission}}:{},resource:{type:s.resourceType},...s.organizationId?{context:{organization_id:s.organizationId}}:{},...Object.keys(o).length?{page:o}:{}});return{data:(a.results??[]).filter(c=>typeof c.id=="string"&&c.id).map(c=>({roles:[],name:"",...c.properties,id:c.id,resource_type:c.type??s.resourceType})),...a.page?.next_token?{nextPageToken:a.page.next_token}:{},...typeof a.page?.total=="number"?{total:a.page.total}:{}}};return{check:F,checkBatch:S,listAccessible:v,filterAccessible:async(n,s,i,o)=>{if(!o?.resourceType)throw new Error("filterAccessible: resourceType is required");if(!o.permission)throw new Error("filterAccessible: permission is required");const a=o.threshold??I,u=o.maxListed??x,c=o.scopes?{scopes:o.scopes}:void 0,h=[...new Set(s.map(i).filter(g=>typeof g=="string"&&g!==""))];if(!h.length)return[];const p=new Set;if(h.length<=a){const g=await S(n,h.map(l=>({permission:o.permission,resource:{type:o.resourceType,id:l}})),c);h.forEach((l,m)=>g[m]&&p.add(l))}else{const g={resourceType:o.resourceType,permission:o.permission,limit:q};let l=0,m;do{const y=await v(n,{...g,...m?{pageToken:m}:{}},c);if(y.total!==void 0&&y.total>u)throw new _(o.resourceType,u);if(l+=y.data.length,l>u)throw new _(o.resourceType,u);for(const z of y.data)z.via_descendant||p.add(z.id);m=y.data.length?y.nextPageToken:void 0}while(m)}return s.filter(g=>{const l=i(g);return typeof l=="string"&&p.has(l)})}}}exports.managementAudience=k.managementAudience;exports.AuthorizationError=T;exports.DEFAULT_FILTER_THRESHOLD=I;exports.DEFAULT_MAX_LISTED=x;exports.ListingTooLargeError=_;exports.MAX_BATCH_ITEMS=w;exports.authzUrlFor=D;exports.createAuthorizationClient=B;
2
+ //# sourceMappingURL=authorization.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authorization.cjs","sources":["../src/authorization.ts"],"sourcesContent":["import { managementBase, managementTokenSource, type ManagementCredential } from \"./management-credential\";\nimport type { Principal } from \"./resource-server\";\n\n/**\n * Authorization checks against Pontive for a verified principal (pontive-spec\n * 20 C3, G1, OD-21; agent-identity-implementation-plan §9.5), asked of the\n * authz host in the OpenID AuthZEN Authorization API 1.0's shapes\n * (`POST /access/v1/evaluation`, `/access/v1/evaluations`,\n * `/access/v1/search/resource`; pontive-spec api-route-review D11, D24).\n *\n * Pass the `Principal` the resource server verified, never an id you took\n * from it. For a delegated principal (an agent acting for a user,\n * `principal.isDelegated`) the client sends the raw token, and Pontive\n * derives the user and the agent from it and answers for the intersection of\n * the two. Checking by `principal.sub` would answer for the user alone, wider\n * than the agent may act; this client never does that.\n *\n * Any other principal is checked by subject, as itself.\n *\n * **Scopes.** Pontive does not interpret scopes in a check. Pass\n * `options.scopes` and the client applies your API's scope conjunct: the\n * answer is allowed only when the token was granted every one of them (from\n * the principal Pontive echoes for a check by token, or the verified token's\n * own scopes otherwise). A listing without them returns no rows and asks\n * nothing.\n *\n * ```ts\n * import { createAuthorizationClient } from \"@pontive/server/authorization\";\n *\n * const authz = createAuthorizationClient({\n * managementUrl: \"https://api.us.pontive.com\",\n * issuer: \"https://acme.auth.us.pontive.app\",\n * credential: { clientId: \"svc_…\", clientSecret: process.env.PONTIVE_SECRET! },\n * });\n *\n * if (!(await authz.check(principal, \"doc:write\", { type: \"doc\", id: docId }, { scopes: [\"docs:write\"] }))) {\n * return new Response(\"forbidden\", { status: 403 });\n * }\n * ```\n */\n\n/** The object a permission is checked on: an organization (`org`), a resource of a custom type, or the root. */\nexport interface ResourceRef {\n /** The resource type key, e.g. `doc`, or `org` for an organization. */\n type: string;\n /** The organization's or resource's id, or the instance id for the root. */\n id: string;\n}\n\nexport interface CheckItem {\n permission: string;\n resource: ResourceRef;\n}\n\nexport interface CheckOptions {\n /** Scopes the token must have been granted as well; the answer is a deny without any of them. */\n scopes?: string[];\n}\n\nexport interface ListAccessibleParams {\n /** The resource type key (`org` for organizations). */\n resourceType: string;\n /** Only resources where the principal holds this permission. Required for a delegated principal. */\n permission?: string;\n /** Only resources belonging to this organization. */\n organizationId?: string;\n /** The `nextPageToken` of the page before; none for the first page. */\n pageToken?: string;\n /** The page's size, 1 to 100. */\n limit?: number;\n}\n\n/** One resource the principal can reach: a resource search's result, its properties spread. */\nexport interface AccessibleResource {\n object?: string;\n id: string;\n resource_type: string;\n external_id?: string;\n name: string;\n metadata?: Record<string, string>;\n organization_id?: string;\n parent?: { resource_id: string; resource_type: string };\n slug?: string;\n status?: string;\n /** The role keys held there; for a delegated principal, the keys both the user and the agent hold. */\n roles: string[];\n via_descendant?: boolean;\n created_at?: string;\n updated_at?: string;\n}\n\nexport interface AccessibleResourcePage {\n data: AccessibleResource[];\n /** The token of the next page, for `pageToken`; none on the last page. */\n nextPageToken?: string;\n /** How many resources the principal reaches in all, when the server says. */\n total?: number;\n}\n\n/** The principal Pontive verified a token as, echoed by a check by token. */\nexport interface TokenPrincipal {\n sub: string;\n act?: { sub: string; agent_instance?: string };\n aud?: string[];\n scope?: string;\n client_id?: string;\n org_id?: string;\n}\n\n/**\n * A refused authorization request. `code` tells \"authenticate again\"\n * (`invalid_token`: the token expired, is another instance's, or does not\n * verify) from a configuration problem (`403`: the credential lacks\n * `sys:authz:check`) and from a bad request (`delegated_permission_required`).\n * A denied check is not an error: it resolves `false`.\n */\nexport class AuthorizationError extends Error {\n constructor(\n readonly status: number,\n readonly code: string | undefined,\n message: string,\n ) {\n super(message);\n this.name = \"AuthorizationError\";\n }\n}\n\nexport interface AuthorizationClientConfig {\n /**\n * The management API's origin in the instance's region, e.g.\n * `https://api.us.pontive.com`: the audience a client-credentials exchange\n * asks a management token for (the origin itself, api-route-review D51), and\n * where the authz host is derived from. A `/v1`, `/mgmt` or `/mgmt/v1`\n * suffix is dropped.\n */\n managementUrl: string;\n /**\n * The authz host, AuthZEN's decision point (`https://authz.us.pontive.com`).\n * Defaults to `managementUrl` with its leading `api.` label replaced by\n * `authz.`, or `managementUrl` itself when it has none (a local\n * management API serves `/access/v1` too).\n */\n authzUrl?: string;\n /**\n * A credential holding `sys:authz:check` in the instance: a secret key or\n * management token, a function returning one, or a service account's client\n * credentials (exchanged at `issuer`).\n */\n credential: ManagementCredential;\n /** The instance's issuer; required for client credentials. */\n issuer?: string;\n /** Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n}\n\nexport interface AuthorizationClient {\n /** Whether the principal holds `permission` on `resource`. */\n check(principal: Principal, permission: string, resource: ResourceRef, options?: CheckOptions): Promise<boolean>;\n /** One answer per item, in order. Sent 100 evaluations per request; each item counts as one check. */\n checkBatch(principal: Principal, items: CheckItem[], options?: CheckOptions): Promise<boolean[]>;\n /**\n * The resources of one type the principal can reach, a page at a time. A\n * delegated principal's listing needs `permission`.\n */\n listAccessible(principal: Principal, params: ListAccessibleParams, options?: CheckOptions): Promise<AccessibleResourcePage>;\n /**\n * The items the principal may access, in their order: a retrieval set\n * (documents or chunks for a RAG step) filtered to what the principal holds\n * `permission` on. `idOf` names each item's resource id; an item without\n * one is excluded, and items sharing an id (chunks of one document) are\n * checked once and kept or dropped together.\n *\n * Up to `threshold` distinct ids are checked with `checkBatch`; above it,\n * the principal's reach is listed with `listAccessible` and the items\n * filtered locally. A delegated principal is evaluated as the pair, by\n * token, either way.\n */\n filterAccessible<T>(\n principal: Principal,\n items: readonly T[],\n idOf: (item: T) => string | null | undefined,\n options: FilterAccessibleOptions,\n ): Promise<T[]>;\n}\n\nexport interface FilterAccessibleOptions extends CheckOptions {\n /** The items' resource type key, e.g. `doc`. */\n resourceType: string;\n /** The permission an item needs to be kept, e.g. `doc:read`. */\n permission: string;\n /**\n * The most distinct ids checked by batch; more are filtered by listing.\n * Defaults to {@link DEFAULT_FILTER_THRESHOLD}. `0` always lists;\n * `Infinity` always checks.\n */\n threshold?: number;\n /**\n * The most resources a listing may return before `filterAccessible` gives\n * up with a {@link ListingTooLargeError}. Defaults to\n * {@link DEFAULT_MAX_LISTED}.\n */\n maxListed?: number;\n}\n\n/**\n * A listing that reaches more resources than `filterAccessible` will page\n * through. Filter by batch check instead (a lower candidate count, or\n * `threshold: Infinity`).\n */\nexport class ListingTooLargeError extends Error {\n constructor(\n readonly resourceType: string,\n readonly maxListed: number,\n ) {\n super(\n `filterAccessible: the principal reaches more than ${maxListed} ${resourceType} resources; ` +\n `filter fewer candidates, or pass threshold: Infinity to check them by batch`,\n );\n this.name = \"ListingTooLargeError\";\n }\n}\n\n/** The most evaluations per AuthZEN evaluations request. */\nexport const MAX_BATCH_ITEMS = 100;\n\n/**\n * `filterAccessible`'s default: up to 100 distinct ids are checked by batch,\n * which is one request, as few as any listing takes, and costs one check per\n * id whatever the principal's reach. Above it a batch takes more requests,\n * while a listing's cost (one check and one request per page of 100) is set by\n * the principal's reach, not the candidate count.\n */\nexport const DEFAULT_FILTER_THRESHOLD = MAX_BATCH_ITEMS;\n\n/** `filterAccessible`'s default cap on a listing: 100 pages of 100. */\nexport const DEFAULT_MAX_LISTED = 10_000;\n\n/** The listing's largest page. */\nconst LIST_PAGE_SIZE = 100;\n\nconst trimSlash = (value: string) => value.replace(/\\/+$/, \"\");\n\nconst hasScopes = (granted: Iterable<string>, required: string[] | undefined): boolean => {\n if (!required?.length) return true;\n const set = new Set(granted);\n return required.every((scope) => set.has(scope));\n};\n\n// The scopes a check's answer is held to: for a check by token, those of the\n// principal Pontive verified and echoed (the verified token's own when the\n// answer echoes none); otherwise the verified token's.\nconst grantedScopes = (principal: Principal, verified: TokenPrincipal | undefined): string[] =>\n principal.isDelegated && verified ? (verified.scope ?? \"\").split(\" \").filter(Boolean) : principal.scopes;\n\n/**\n * The authz host for a management API origin (api-route-review D11): the\n * management API's base (`managementBase`, so a `/v1`, `/mgmt` or `/mgmt/v1`\n * suffix is dropped) with its leading `api.` label replaced by `authz.`\n * (`https://api.us.pontive.com/v1` → `https://authz.us.pontive.com`), or that\n * base itself when it has none (a local management API serves `/access/v1`\n * too).\n */\nexport function authzUrlFor(managementUrl: string): string {\n const base = managementBase(managementUrl);\n try {\n const url = new URL(base);\n if (!url.hostname.toLowerCase().startsWith(\"api.\")) return base;\n url.hostname = `authz.${url.hostname.slice(\"api.\".length)}`;\n return trimSlash(`${url.origin}${url.pathname}`);\n } catch {\n return base;\n }\n}\n\n// An evaluation's action and resource, AuthZEN's shapes.\nconst evaluation = (item: CheckItem) => ({\n action: { name: item.permission },\n resource: { type: item.resource.type, id: item.resource.id },\n});\n\n// The principal a decision's context echoes for a check by token.\nconst echoed = (context: unknown): TokenPrincipal | undefined => {\n const principal = context && typeof context === \"object\" ? (context as { principal?: unknown }).principal : undefined;\n return principal && typeof principal === \"object\" ? (principal as TokenPrincipal) : undefined;\n};\n\ninterface Decision {\n decision?: boolean;\n context?: Record<string, unknown>;\n}\n\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" && v ? v : undefined);\n\n// A refusal's code and message. The authz host answers\n// `{ error: { code, message, … } }`; an OAuth-style `{ error, error_description }`\n// and a flat `{ code, message }` are read too.\nasync function refusal(res: Response): Promise<{ code?: string; message?: string }> {\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n return {}; // No JSON body: the status is all there is.\n }\n if (!body || typeof body !== \"object\") return {};\n const b = body as Record<string, unknown>;\n if (b.error && typeof b.error === \"object\") {\n const e = b.error as Record<string, unknown>;\n return { code: str(e.code), message: str(e.message) };\n }\n return { code: str(b.error) ?? str(b.code), message: str(b.error_description) ?? str(b.message) };\n}\n\nexport function createAuthorizationClient(config: AuthorizationClientConfig): AuthorizationClient {\n if (!config.managementUrl) throw new Error(\"authorization client: managementUrl is required\");\n const fetchImpl = config.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const base = `${config.authzUrl ? trimSlash(config.authzUrl) : authzUrlFor(config.managementUrl)}/access/v1`;\n const credentialToken = managementTokenSource({\n credential: config.credential,\n managementUrl: config.managementUrl,\n issuer: config.issuer && trimSlash(config.issuer),\n fetch: fetchImpl,\n });\n\n // Every AuthZEN call is a POST with a JSON body, so a token never goes in a\n // URL, where proxies and access logs keep it.\n const request = async <T>(url: string, body: unknown): Promise<T> => {\n const res = await fetchImpl(url, {\n method: \"POST\",\n headers: { authorization: `Bearer ${await credentialToken()}`, accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) {\n const { code, message } = await refusal(res);\n throw new AuthorizationError(res.status, code, message ?? `authorization request failed: ${res.status}`);\n }\n return (await res.json()) as T;\n };\n\n // The AuthZEN subject: the token for a delegated principal, which Pontive\n // evaluates as the (user, agent) pair (subject type `token`, Pontive's\n // extension); the principal by its kind and id otherwise.\n const subject = (principal: Principal): { type: string; id: string } =>\n principal.isDelegated ? { type: \"token\", id: principal.token } : { type: principal.kind, id: principal.sub };\n\n const check: AuthorizationClient[\"check\"] = async (principal, permission, resource, options) => {\n const res = await request<Decision>(`${base}/evaluation`, {\n subject: subject(principal),\n ...evaluation({ permission, resource }),\n });\n return res.decision === true && hasScopes(grantedScopes(principal, echoed(res.context)), options?.scopes);\n };\n\n const checkBatch: AuthorizationClient[\"checkBatch\"] = async (principal, items, options) => {\n const out: boolean[] = [];\n for (let i = 0; i < items.length; i += MAX_BATCH_ITEMS) {\n const chunk = items.slice(i, i + MAX_BATCH_ITEMS);\n const res = await request<{ evaluations?: Decision[] }>(`${base}/evaluations`, {\n subject: subject(principal),\n evaluations: chunk.map(evaluation),\n options: { evaluations_semantic: \"execute_all\" },\n });\n const results = res.evaluations ?? [];\n if (results.length !== chunk.length) {\n throw new AuthorizationError(502, undefined, `evaluations answered ${results.length} of ${chunk.length} items`);\n }\n for (const r of results) out.push(r.decision === true && hasScopes(grantedScopes(principal, echoed(r.context)), options?.scopes));\n }\n return out;\n };\n\n const listAccessible: AuthorizationClient[\"listAccessible\"] = async (principal, params, options) => {\n if (!params.resourceType) throw new Error(\"listAccessible: resourceType is required\");\n if (principal.isDelegated && !params.permission) {\n // A pair holding different roles has no single \"reach\"; the server\n // refuses it too (400 delegated_permission_required).\n throw new AuthorizationError(400, \"delegated_permission_required\", \"a delegated listing needs a permission\");\n }\n // Without the API's scopes the token reaches nothing here: ask nothing.\n if (!hasScopes(principal.scopes, options?.scopes)) return { data: [] };\n\n const page = {\n ...(params.pageToken ? { token: params.pageToken } : {}),\n ...(params.limit !== undefined ? { limit: params.limit } : {}),\n };\n const res = await request<{\n results?: { type?: string; id?: string; properties?: Record<string, unknown> }[];\n page?: { next_token?: string; total?: number };\n }>(`${base}/search/resource`, {\n subject: subject(principal),\n ...(params.permission ? { action: { name: params.permission } } : {}),\n resource: { type: params.resourceType },\n ...(params.organizationId ? { context: { organization_id: params.organizationId } } : {}),\n ...(Object.keys(page).length ? { page } : {}),\n });\n\n const data = (res.results ?? [])\n .filter((r) => typeof r.id === \"string\" && r.id)\n .map((r) => ({ roles: [], name: \"\", ...r.properties, id: r.id!, resource_type: r.type ?? params.resourceType }) as AccessibleResource);\n return {\n data,\n ...(res.page?.next_token ? { nextPageToken: res.page.next_token } : {}),\n ...(typeof res.page?.total === \"number\" ? { total: res.page.total } : {}),\n };\n };\n\n const filterAccessible: AuthorizationClient[\"filterAccessible\"] = async (principal, items, idOf, options) => {\n if (!options?.resourceType) throw new Error(\"filterAccessible: resourceType is required\");\n if (!options.permission) throw new Error(\"filterAccessible: permission is required\");\n const threshold = options.threshold ?? DEFAULT_FILTER_THRESHOLD;\n const maxListed = options.maxListed ?? DEFAULT_MAX_LISTED;\n const scoped = options.scopes ? { scopes: options.scopes } : undefined;\n\n // Distinct ids, first-seen order; an item without one is never asked about.\n const ids = [...new Set(items.map(idOf).filter((id): id is string => typeof id === \"string\" && id !== \"\"))];\n if (!ids.length) return [];\n\n const allowed = new Set<string>();\n if (ids.length <= threshold) {\n const answers = await checkBatch(\n principal,\n ids.map((id) => ({ permission: options.permission, resource: { type: options.resourceType, id } })),\n scoped,\n );\n ids.forEach((id, i) => answers[i] && allowed.add(id));\n } else {\n const params = { resourceType: options.resourceType, permission: options.permission, limit: LIST_PAGE_SIZE };\n let listed = 0;\n let pageToken: string | undefined;\n do {\n const res = await listAccessible(principal, { ...params, ...(pageToken ? { pageToken } : {}) }, scoped);\n if (res.total !== undefined && res.total > maxListed) throw new ListingTooLargeError(options.resourceType, maxListed);\n listed += res.data.length;\n if (listed > maxListed) throw new ListingTooLargeError(options.resourceType, maxListed);\n // An ancestor listed only because something below it is reachable grants nothing.\n for (const r of res.data) if (!r.via_descendant) allowed.add(r.id);\n pageToken = res.data.length ? res.nextPageToken : undefined;\n } while (pageToken);\n }\n\n return items.filter((item) => {\n const id = idOf(item);\n return typeof id === \"string\" && allowed.has(id);\n });\n };\n\n return { check, checkBatch, listAccessible, filterAccessible };\n}\n\nexport { managementAudience } from \"./management-credential\";\nexport type { ManagementCredential } from \"./management-credential\";\nexport type { DelegatedPrincipal, Principal, PrincipalActor, UndelegatedPrincipal } from \"./resource-server\";\n"],"names":["AuthorizationError","status","code","message","ListingTooLargeError","resourceType","maxListed","MAX_BATCH_ITEMS","DEFAULT_FILTER_THRESHOLD","DEFAULT_MAX_LISTED","LIST_PAGE_SIZE","trimSlash","value","hasScopes","granted","required","set","scope","grantedScopes","principal","verified","authzUrlFor","managementUrl","base","managementBase","url","evaluation","item","echoed","context","str","v","refusal","res","body","b","e","createAuthorizationClient","config","fetchImpl","args","credentialToken","managementTokenSource","request","subject","check","permission","resource","options","checkBatch","items","out","i","chunk","results","r","listAccessible","params","page","idOf","threshold","scoped","ids","id","allowed","answers","listed","pageToken"],"mappings":"wIAoHO,MAAMA,UAA2B,KAAM,CAC5C,YACWC,EACAC,EACTC,EACA,CACA,MAAMA,CAAO,EAJJ,KAAA,OAAAF,EACA,KAAA,KAAAC,EAIT,KAAK,KAAO,oBACd,CANW,OACA,IAMb,CAoFO,MAAME,UAA6B,KAAM,CAC9C,YACWC,EACAC,EACT,CACA,MACE,qDAAqDA,CAAS,IAAID,CAAY,yFAAA,EAJvE,KAAA,aAAAA,EACA,KAAA,UAAAC,EAMT,KAAK,KAAO,sBACd,CARW,aACA,SAQb,CAGO,MAAMC,EAAkB,IASlBC,EAA2BD,EAG3BE,EAAqB,IAG5BC,EAAiB,IAEjBC,EAAaC,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4C,CAC9C"}
@@ -0,0 +1,222 @@
1
+ import { ManagementCredential } from './management-credential.cjs';
2
+ import { Principal } from './resource-server.cjs';
3
+ /**
4
+ * Authorization checks against Pontive for a verified principal (pontive-spec
5
+ * 20 C3, G1, OD-21; agent-identity-implementation-plan §9.5), asked of the
6
+ * authz host in the OpenID AuthZEN Authorization API 1.0's shapes
7
+ * (`POST /access/v1/evaluation`, `/access/v1/evaluations`,
8
+ * `/access/v1/search/resource`; pontive-spec api-route-review D11, D24).
9
+ *
10
+ * Pass the `Principal` the resource server verified, never an id you took
11
+ * from it. For a delegated principal (an agent acting for a user,
12
+ * `principal.isDelegated`) the client sends the raw token, and Pontive
13
+ * derives the user and the agent from it and answers for the intersection of
14
+ * the two. Checking by `principal.sub` would answer for the user alone, wider
15
+ * than the agent may act; this client never does that.
16
+ *
17
+ * Any other principal is checked by subject, as itself.
18
+ *
19
+ * **Scopes.** Pontive does not interpret scopes in a check. Pass
20
+ * `options.scopes` and the client applies your API's scope conjunct: the
21
+ * answer is allowed only when the token was granted every one of them (from
22
+ * the principal Pontive echoes for a check by token, or the verified token's
23
+ * own scopes otherwise). A listing without them returns no rows and asks
24
+ * nothing.
25
+ *
26
+ * ```ts
27
+ * import { createAuthorizationClient } from "@pontive/server/authorization";
28
+ *
29
+ * const authz = createAuthorizationClient({
30
+ * managementUrl: "https://api.us.pontive.com",
31
+ * issuer: "https://acme.auth.us.pontive.app",
32
+ * credential: { clientId: "svc_…", clientSecret: process.env.PONTIVE_SECRET! },
33
+ * });
34
+ *
35
+ * if (!(await authz.check(principal, "doc:write", { type: "doc", id: docId }, { scopes: ["docs:write"] }))) {
36
+ * return new Response("forbidden", { status: 403 });
37
+ * }
38
+ * ```
39
+ */
40
+ /** The object a permission is checked on: an organization (`org`), a resource of a custom type, or the root. */
41
+ export interface ResourceRef {
42
+ /** The resource type key, e.g. `doc`, or `org` for an organization. */
43
+ type: string;
44
+ /** The organization's or resource's id, or the instance id for the root. */
45
+ id: string;
46
+ }
47
+ export interface CheckItem {
48
+ permission: string;
49
+ resource: ResourceRef;
50
+ }
51
+ export interface CheckOptions {
52
+ /** Scopes the token must have been granted as well; the answer is a deny without any of them. */
53
+ scopes?: string[];
54
+ }
55
+ export interface ListAccessibleParams {
56
+ /** The resource type key (`org` for organizations). */
57
+ resourceType: string;
58
+ /** Only resources where the principal holds this permission. Required for a delegated principal. */
59
+ permission?: string;
60
+ /** Only resources belonging to this organization. */
61
+ organizationId?: string;
62
+ /** The `nextPageToken` of the page before; none for the first page. */
63
+ pageToken?: string;
64
+ /** The page's size, 1 to 100. */
65
+ limit?: number;
66
+ }
67
+ /** One resource the principal can reach: a resource search's result, its properties spread. */
68
+ export interface AccessibleResource {
69
+ object?: string;
70
+ id: string;
71
+ resource_type: string;
72
+ external_id?: string;
73
+ name: string;
74
+ metadata?: Record<string, string>;
75
+ organization_id?: string;
76
+ parent?: {
77
+ resource_id: string;
78
+ resource_type: string;
79
+ };
80
+ slug?: string;
81
+ status?: string;
82
+ /** The role keys held there; for a delegated principal, the keys both the user and the agent hold. */
83
+ roles: string[];
84
+ via_descendant?: boolean;
85
+ created_at?: string;
86
+ updated_at?: string;
87
+ }
88
+ export interface AccessibleResourcePage {
89
+ data: AccessibleResource[];
90
+ /** The token of the next page, for `pageToken`; none on the last page. */
91
+ nextPageToken?: string;
92
+ /** How many resources the principal reaches in all, when the server says. */
93
+ total?: number;
94
+ }
95
+ /** The principal Pontive verified a token as, echoed by a check by token. */
96
+ export interface TokenPrincipal {
97
+ sub: string;
98
+ act?: {
99
+ sub: string;
100
+ agent_instance?: string;
101
+ };
102
+ aud?: string[];
103
+ scope?: string;
104
+ client_id?: string;
105
+ org_id?: string;
106
+ }
107
+ /**
108
+ * A refused authorization request. `code` tells "authenticate again"
109
+ * (`invalid_token`: the token expired, is another instance's, or does not
110
+ * verify) from a configuration problem (`403`: the credential lacks
111
+ * `sys:authz:check`) and from a bad request (`delegated_permission_required`).
112
+ * A denied check is not an error: it resolves `false`.
113
+ */
114
+ export declare class AuthorizationError extends Error {
115
+ readonly status: number;
116
+ readonly code: string | undefined;
117
+ constructor(status: number, code: string | undefined, message: string);
118
+ }
119
+ export interface AuthorizationClientConfig {
120
+ /**
121
+ * The management API's origin in the instance's region, e.g.
122
+ * `https://api.us.pontive.com`: the audience a client-credentials exchange
123
+ * asks a management token for (the origin itself, api-route-review D51), and
124
+ * where the authz host is derived from. A `/v1`, `/mgmt` or `/mgmt/v1`
125
+ * suffix is dropped.
126
+ */
127
+ managementUrl: string;
128
+ /**
129
+ * The authz host, AuthZEN's decision point (`https://authz.us.pontive.com`).
130
+ * Defaults to `managementUrl` with its leading `api.` label replaced by
131
+ * `authz.`, or `managementUrl` itself when it has none (a local
132
+ * management API serves `/access/v1` too).
133
+ */
134
+ authzUrl?: string;
135
+ /**
136
+ * A credential holding `sys:authz:check` in the instance: a secret key or
137
+ * management token, a function returning one, or a service account's client
138
+ * credentials (exchanged at `issuer`).
139
+ */
140
+ credential: ManagementCredential;
141
+ /** The instance's issuer; required for client credentials. */
142
+ issuer?: string;
143
+ /** Defaults to the global `fetch`. */
144
+ fetch?: typeof fetch;
145
+ }
146
+ export interface AuthorizationClient {
147
+ /** Whether the principal holds `permission` on `resource`. */
148
+ check(principal: Principal, permission: string, resource: ResourceRef, options?: CheckOptions): Promise<boolean>;
149
+ /** One answer per item, in order. Sent 100 evaluations per request; each item counts as one check. */
150
+ checkBatch(principal: Principal, items: CheckItem[], options?: CheckOptions): Promise<boolean[]>;
151
+ /**
152
+ * The resources of one type the principal can reach, a page at a time. A
153
+ * delegated principal's listing needs `permission`.
154
+ */
155
+ listAccessible(principal: Principal, params: ListAccessibleParams, options?: CheckOptions): Promise<AccessibleResourcePage>;
156
+ /**
157
+ * The items the principal may access, in their order: a retrieval set
158
+ * (documents or chunks for a RAG step) filtered to what the principal holds
159
+ * `permission` on. `idOf` names each item's resource id; an item without
160
+ * one is excluded, and items sharing an id (chunks of one document) are
161
+ * checked once and kept or dropped together.
162
+ *
163
+ * Up to `threshold` distinct ids are checked with `checkBatch`; above it,
164
+ * the principal's reach is listed with `listAccessible` and the items
165
+ * filtered locally. A delegated principal is evaluated as the pair, by
166
+ * token, either way.
167
+ */
168
+ filterAccessible<T>(principal: Principal, items: readonly T[], idOf: (item: T) => string | null | undefined, options: FilterAccessibleOptions): Promise<T[]>;
169
+ }
170
+ export interface FilterAccessibleOptions extends CheckOptions {
171
+ /** The items' resource type key, e.g. `doc`. */
172
+ resourceType: string;
173
+ /** The permission an item needs to be kept, e.g. `doc:read`. */
174
+ permission: string;
175
+ /**
176
+ * The most distinct ids checked by batch; more are filtered by listing.
177
+ * Defaults to {@link DEFAULT_FILTER_THRESHOLD}. `0` always lists;
178
+ * `Infinity` always checks.
179
+ */
180
+ threshold?: number;
181
+ /**
182
+ * The most resources a listing may return before `filterAccessible` gives
183
+ * up with a {@link ListingTooLargeError}. Defaults to
184
+ * {@link DEFAULT_MAX_LISTED}.
185
+ */
186
+ maxListed?: number;
187
+ }
188
+ /**
189
+ * A listing that reaches more resources than `filterAccessible` will page
190
+ * through. Filter by batch check instead (a lower candidate count, or
191
+ * `threshold: Infinity`).
192
+ */
193
+ export declare class ListingTooLargeError extends Error {
194
+ readonly resourceType: string;
195
+ readonly maxListed: number;
196
+ constructor(resourceType: string, maxListed: number);
197
+ }
198
+ /** The most evaluations per AuthZEN evaluations request. */
199
+ export declare const MAX_BATCH_ITEMS = 100;
200
+ /**
201
+ * `filterAccessible`'s default: up to 100 distinct ids are checked by batch,
202
+ * which is one request, as few as any listing takes, and costs one check per
203
+ * id whatever the principal's reach. Above it a batch takes more requests,
204
+ * while a listing's cost (one check and one request per page of 100) is set by
205
+ * the principal's reach, not the candidate count.
206
+ */
207
+ export declare const DEFAULT_FILTER_THRESHOLD = 100;
208
+ /** `filterAccessible`'s default cap on a listing: 100 pages of 100. */
209
+ export declare const DEFAULT_MAX_LISTED = 10000;
210
+ /**
211
+ * The authz host for a management API origin (api-route-review D11): the
212
+ * management API's base (`managementBase`, so a `/v1`, `/mgmt` or `/mgmt/v1`
213
+ * suffix is dropped) with its leading `api.` label replaced by `authz.`
214
+ * (`https://api.us.pontive.com/v1` → `https://authz.us.pontive.com`), or that
215
+ * base itself when it has none (a local management API serves `/access/v1`
216
+ * too).
217
+ */
218
+ export declare function authzUrlFor(managementUrl: string): string;
219
+ export declare function createAuthorizationClient(config: AuthorizationClientConfig): AuthorizationClient;
220
+ export { managementAudience } from './management-credential.cjs';
221
+ export type { ManagementCredential } from './management-credential.cjs';
222
+ export type { DelegatedPrincipal, Principal, PrincipalActor, UndelegatedPrincipal } from './resource-server.cjs';