@pontive/server 0.0.0-stage → 1.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.
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
@@ -0,0 +1,222 @@
1
+ import { ManagementCredential } from './management-credential.js';
2
+ import { Principal } from './resource-server.js';
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.js';
221
+ export type { ManagementCredential } from './management-credential.js';
222
+ export type { DelegatedPrincipal, Principal, PrincipalActor, UndelegatedPrincipal } from './resource-server.js';
@@ -0,0 +1,153 @@
1
+ import { m as U, a as I } from "./management-credential-VhmMzGDl.js";
2
+ import { b as X } from "./management-credential-VhmMzGDl.js";
3
+ class b extends Error {
4
+ constructor(t, s, d) {
5
+ super(d), this.status = t, this.code = s, this.name = "AuthorizationError";
6
+ }
7
+ status;
8
+ code;
9
+ }
10
+ class S extends Error {
11
+ constructor(t, s) {
12
+ super(
13
+ `filterAccessible: the principal reaches more than ${s} ${t} resources; filter fewer candidates, or pass threshold: Infinity to check them by batch`
14
+ ), this.resourceType = t, this.maxListed = s, this.name = "ListingTooLargeError";
15
+ }
16
+ resourceType;
17
+ maxListed;
18
+ }
19
+ const E = 100, D = E, q = 1e4, B = 100, _ = (e) => e.replace(/\/+$/, ""), k = (e, t) => {
20
+ if (!t?.length) return !0;
21
+ const s = new Set(e);
22
+ return t.every((d) => s.has(d));
23
+ }, $ = (e, t) => e.isDelegated && t ? (t.scope ?? "").split(" ").filter(Boolean) : e.scopes;
24
+ function F(e) {
25
+ const t = U(e);
26
+ try {
27
+ const s = new URL(t);
28
+ return s.hostname.toLowerCase().startsWith("api.") ? (s.hostname = `authz.${s.hostname.slice(4)}`, _(`${s.origin}${s.pathname}`)) : t;
29
+ } catch {
30
+ return t;
31
+ }
32
+ }
33
+ const j = (e) => ({
34
+ action: { name: e.permission },
35
+ resource: { type: e.resource.type, id: e.resource.id }
36
+ }), x = (e) => {
37
+ const t = e && typeof e == "object" ? e.principal : void 0;
38
+ return t && typeof t == "object" ? t : void 0;
39
+ }, y = (e) => typeof e == "string" && e ? e : void 0;
40
+ async function P(e) {
41
+ let t;
42
+ try {
43
+ t = await e.json();
44
+ } catch {
45
+ return {};
46
+ }
47
+ if (!t || typeof t != "object") return {};
48
+ const s = t;
49
+ if (s.error && typeof s.error == "object") {
50
+ const d = s.error;
51
+ return { code: y(d.code), message: y(d.message) };
52
+ }
53
+ return { code: y(s.error) ?? y(s.code), message: y(s.error_description) ?? y(s.message) };
54
+ }
55
+ function M(e) {
56
+ if (!e.managementUrl) throw new Error("authorization client: managementUrl is required");
57
+ const t = e.fetch ?? ((...n) => fetch(...n)), s = `${e.authzUrl ? _(e.authzUrl) : F(e.managementUrl)}/access/v1`, d = I({
58
+ credential: e.credential,
59
+ managementUrl: e.managementUrl,
60
+ issuer: e.issuer && _(e.issuer),
61
+ fetch: t
62
+ }), w = async (n, r) => {
63
+ const i = await t(n, {
64
+ method: "POST",
65
+ headers: { authorization: `Bearer ${await d()}`, accept: "application/json", "content-type": "application/json" },
66
+ body: JSON.stringify(r)
67
+ });
68
+ if (!i.ok) {
69
+ const { code: o, message: a } = await P(i);
70
+ throw new b(i.status, o, a ?? `authorization request failed: ${i.status}`);
71
+ }
72
+ return await i.json();
73
+ }, T = (n) => n.isDelegated ? { type: "token", id: n.token } : { type: n.kind, id: n.sub }, z = async (n, r, i, o) => {
74
+ const a = await w(`${s}/evaluation`, {
75
+ subject: T(n),
76
+ ...j({ permission: r, resource: i })
77
+ });
78
+ return a.decision === !0 && k($(n, x(a.context)), o?.scopes);
79
+ }, A = async (n, r, i) => {
80
+ const o = [];
81
+ for (let a = 0; a < r.length; a += E) {
82
+ const u = r.slice(a, a + E), h = (await w(`${s}/evaluations`, {
83
+ subject: T(n),
84
+ evaluations: u.map(j),
85
+ options: { evaluations_semantic: "execute_all" }
86
+ })).evaluations ?? [];
87
+ if (h.length !== u.length)
88
+ throw new b(502, void 0, `evaluations answered ${h.length} of ${u.length} items`);
89
+ for (const m of h) o.push(m.decision === !0 && k($(n, x(m.context)), i?.scopes));
90
+ }
91
+ return o;
92
+ }, v = async (n, r, i) => {
93
+ if (!r.resourceType) throw new Error("listAccessible: resourceType is required");
94
+ if (n.isDelegated && !r.permission)
95
+ throw new b(400, "delegated_permission_required", "a delegated listing needs a permission");
96
+ if (!k(n.scopes, i?.scopes)) return { data: [] };
97
+ const o = {
98
+ ...r.pageToken ? { token: r.pageToken } : {},
99
+ ...r.limit !== void 0 ? { limit: r.limit } : {}
100
+ }, a = await w(`${s}/search/resource`, {
101
+ subject: T(n),
102
+ ...r.permission ? { action: { name: r.permission } } : {},
103
+ resource: { type: r.resourceType },
104
+ ...r.organizationId ? { context: { organization_id: r.organizationId } } : {},
105
+ ...Object.keys(o).length ? { page: o } : {}
106
+ });
107
+ return {
108
+ data: (a.results ?? []).filter((c) => typeof c.id == "string" && c.id).map((c) => ({ roles: [], name: "", ...c.properties, id: c.id, resource_type: c.type ?? r.resourceType })),
109
+ ...a.page?.next_token ? { nextPageToken: a.page.next_token } : {},
110
+ ...typeof a.page?.total == "number" ? { total: a.page.total } : {}
111
+ };
112
+ };
113
+ return { check: z, checkBatch: A, listAccessible: v, filterAccessible: async (n, r, i, o) => {
114
+ if (!o?.resourceType) throw new Error("filterAccessible: resourceType is required");
115
+ if (!o.permission) throw new Error("filterAccessible: permission is required");
116
+ const a = o.threshold ?? D, u = o.maxListed ?? q, c = o.scopes ? { scopes: o.scopes } : void 0, h = [...new Set(r.map(i).filter((p) => typeof p == "string" && p !== ""))];
117
+ if (!h.length) return [];
118
+ const m = /* @__PURE__ */ new Set();
119
+ if (h.length <= a) {
120
+ const p = await A(
121
+ n,
122
+ h.map((l) => ({ permission: o.permission, resource: { type: o.resourceType, id: l } })),
123
+ c
124
+ );
125
+ h.forEach((l, f) => p[f] && m.add(l));
126
+ } else {
127
+ const p = { resourceType: o.resourceType, permission: o.permission, limit: B };
128
+ let l = 0, f;
129
+ do {
130
+ const g = await v(n, { ...p, ...f ? { pageToken: f } : {} }, c);
131
+ if (g.total !== void 0 && g.total > u) throw new S(o.resourceType, u);
132
+ if (l += g.data.length, l > u) throw new S(o.resourceType, u);
133
+ for (const L of g.data) L.via_descendant || m.add(L.id);
134
+ f = g.data.length ? g.nextPageToken : void 0;
135
+ } while (f);
136
+ }
137
+ return r.filter((p) => {
138
+ const l = i(p);
139
+ return typeof l == "string" && m.has(l);
140
+ });
141
+ } };
142
+ }
143
+ export {
144
+ b as AuthorizationError,
145
+ D as DEFAULT_FILTER_THRESHOLD,
146
+ q as DEFAULT_MAX_LISTED,
147
+ S as ListingTooLargeError,
148
+ E as MAX_BATCH_ITEMS,
149
+ F as authzUrlFor,
150
+ M as createAuthorizationClient,
151
+ X as managementAudience
152
+ };
153
+ //# sourceMappingURL=authorization.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authorization.js","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":";;AAoHO,MAAMA,UAA2B,MAAM;AAAA,EAC5C,YACWC,GACAC,GACTC,GACA;AACA,UAAMA,CAAO,GAJJ,KAAA,SAAAF,GACA,KAAA,OAAAC,GAIT,KAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAMb;AAoFO,MAAME,UAA6B,MAAM;AAAA,EAC9C,YACWC,GACAC,GACT;AACA;AAAA,MACE,qDAAqDA,CAAS,IAAID,CAAY;AAAA,IAAA,GAJvE,KAAA,eAAAA,GACA,KAAA,YAAAC,GAMT,KAAK,OAAO;AAAA,EACd;AAAA,EARW;AAAA,EACA;AAQb;AAGO,MAAMC,IAAkB,KASlBC,IAA2BD,GAG3BE,IAAqB,KAG5BC,IAAiB,KAEjBC,IAAY,CAACC,MAAkBA,EAAM,QAAQ,QAAQ,EAAE,GAEvDC,IAAY,CAACC,GAA2BC,MAA4C;AACxF,MAAI,CAACA,GAAU,OAAQ,QAAO;AAC9B,QAAMC,IAAM,IAAI,IAAIF,CAAO;AAC3B,SAAOC,EAAS,MAAM,CAACE,MAAUD,EAAI,IAAIC,CAAK,CAAC;AACjD,GAKMC,IAAgB,CAACC,GAAsBC,MAC3CD,EAAU,eAAeC,KAAYA,EAAS,SAAS,IAAI,MAAM,GAAG,EAAE,OAAO,OAAO,IAAID,EAAU;AAU7F,SAASE,EAAYC,GAA+B;AACzD,QAAMC,IAAOC,EAAeF,CAAa;AACzC,MAAI;AACF,UAAMG,IAAM,IAAI,IAAIF,CAAI;AACxB,WAAKE,EAAI,SAAS,YAAA,EAAc,WAAW,MAAM,KACjDA,EAAI,WAAW,SAASA,EAAI,SAAS,MAAM,CAAa,CAAC,IAClDd,EAAU,GAAGc,EAAI,MAAM,GAAGA,EAAI,QAAQ,EAAE,KAFYF;AAAA,EAG7D,QAAQ;AACN,WAAOA;AAAA,EACT;AACF;AAGA,MA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,cAAc,IAAAe,EAAA,IAAO;AAAA,QAClGF;AAAA,MAAA;AAEF,MAAAC,EAAI,QAAQ,CAACC,GAAIX,MAAMa,EAAQb,CAAC,KAAKY,EAAQ,IAAID,CAAE,CAAC;AAAA,IACtD,OAAO;AACL,YAAMN,IAAS,EAAE,cAAcT,EAAQ,cAAc,YAAYA,EAAQ,YAAY,OAAOtC,EAAA;AAC5F,UAAIwD,IAAS,GACTC;AACJ,SAAG;AACD,cAAMlC,IAAM,MAAMuB,EAAerC,GAAW,EAAE,GAAGsC,GAAQ,GAAIU,IAAY,EAAE,WAAAA,EAAA,IAAc,CAAA,EAAC,GAAMN,CAAM;AACtG,YAAI5B,EAAI,UAAU,UAAaA,EAAI,QAAQ3B,EAAW,OAAM,IAAIF,EAAqB4C,EAAQ,cAAc1C,CAAS;AAEpH,YADA4D,KAAUjC,EAAI,KAAK,QACfiC,IAAS5D,EAAW,OAAM,IAAIF,EAAqB4C,EAAQ,cAAc1C,CAAS;AAEtF,mBAAWiD,KAAKtB,EAAI,KAAM,CAAKsB,EAAE,kBAAgBS,EAAQ,IAAIT,EAAE,EAAE;AACjE,QAAAY,IAAYlC,EAAI,KAAK,SAASA,EAAI,gBAAgB;AAAA,MACpD,SAASkC;AAAA,IACX;AAEA,WAAOjB,EAAM,OAAO,CAACvB,MAAS;AAC5B,YAAMoC,IAAKJ,EAAKhC,CAAI;AACpB,aAAO,OAAOoC,KAAO,YAAYC,EAAQ,IAAID,CAAE;AAAA,IACjD,CAAC;AAAA,EACH,EAE4C;AAC9C;"}
@@ -0,0 +1,23 @@
1
+ import { ResolvedConfig } from './config.cjs';
2
+ import { CoreAuth } from './server-auth.cjs';
3
+ /**
4
+ * Server-side sessions for an app whose browser holds the session: a regular
5
+ * app, or a public oauth app, on the browser SDK.
6
+ *
7
+ * The browser SDK signs the user in and is the only thing that ever spends the
8
+ * refresh token. The auth server, reached through the auth proxy on this app's
9
+ * origin, keeps an HttpOnly cookie holding the current access token. The server
10
+ * reads and verifies that cookie, and nothing more — so there is exactly one
11
+ * refresher per session, and rotation never sees a token spent twice.
12
+ *
13
+ * When a page navigation arrives with no live access token but with the
14
+ * session marker, the access token has lapsed while the user is still signed
15
+ * in (the tab was closed, or idle past its refresh). The browser is sent
16
+ * through the auth server's session handshake, which renews the cookies and
17
+ * brings it straight back.
18
+ */
19
+ /** The access token, written by the auth server wherever it writes the refresh cookie. */
20
+ export declare const ACCESS_COOKIE = "__Host-pontive_access";
21
+ /** The readable marker: the browser holds a refresh token. */
22
+ export declare const SESSION_HINT_COOKIE = "__Secure-pontive_session_state";
23
+ export declare function createBrowserAuth(cfg: ResolvedConfig): CoreAuth;
@@ -0,0 +1,23 @@
1
+ import { ResolvedConfig } from './config.js';
2
+ import { CoreAuth } from './server-auth.js';
3
+ /**
4
+ * Server-side sessions for an app whose browser holds the session: a regular
5
+ * app, or a public oauth app, on the browser SDK.
6
+ *
7
+ * The browser SDK signs the user in and is the only thing that ever spends the
8
+ * refresh token. The auth server, reached through the auth proxy on this app's
9
+ * origin, keeps an HttpOnly cookie holding the current access token. The server
10
+ * reads and verifies that cookie, and nothing more — so there is exactly one
11
+ * refresher per session, and rotation never sees a token spent twice.
12
+ *
13
+ * When a page navigation arrives with no live access token but with the
14
+ * session marker, the access token has lapsed while the user is still signed
15
+ * in (the tab was closed, or idle past its refresh). The browser is sent
16
+ * through the auth server's session handshake, which renews the cookies and
17
+ * brings it straight back.
18
+ */
19
+ /** The access token, written by the auth server wherever it writes the refresh cookie. */
20
+ export declare const ACCESS_COOKIE = "__Host-pontive_access";
21
+ /** The readable marker: the browser holds a refresh token. */
22
+ export declare const SESSION_HINT_COOKIE = "__Secure-pontive_session_state";
23
+ export declare function createBrowserAuth(cfg: ResolvedConfig): CoreAuth;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * What an app tells the SDK, and the defaults for everything it doesn't.
3
+ *
4
+ * Whether `clientSecret` is set picks the mode, and nothing else does:
5
+ *
6
+ * - **With a secret** (a confidential oauth app): the server holds the whole
7
+ * session in a sealed cookie, signs users in through its own routes, and
8
+ * refreshes in middleware. Needs `sessionSecret`.
9
+ * - **Without one** (a regular app, or a public oauth app): the browser SDK
10
+ * signs users in and is the only thing that refreshes. The server reads the
11
+ * access token cookie the auth server keeps current, through the auth proxy,
12
+ * and sends a lapsed navigation through the auth server's session handshake.
13
+ *
14
+ * Everything beyond the first few fields exists for the rare app that must
15
+ * differ, and its default is the decision the SDK makes for everyone else.
16
+ *
17
+ * **The environment** (pontive-spec 47 §6.1): `issuer`, `clientId`,
18
+ * `clientSecret` and `sessionSecret` fall back to `PONTIVE_ISSUER`,
19
+ * `PONTIVE_CLIENT_ID`, `PONTIVE_CLIENT_SECRET` and `PONTIVE_SESSION_SECRET`
20
+ * when not passed; a value passed always wins. With neither an `issuer` nor
21
+ * `PONTIVE_ISSUER`, development (`NODE_ENV=development`) runs in **keyless
22
+ * mode** (§6.2): the SDK creates an unclaimed development instance on first
23
+ * use and writes its settings to `.env.local`. `PONTIVE_KEYLESS=0` turns that
24
+ * off; outside development a missing issuer is an error.
25
+ */
26
+ export interface ServerAuthConfig {
27
+ /** The Pontive auth domain, e.g. `https://acme.auth.us.pontive.com`. Default `PONTIVE_ISSUER`. */
28
+ issuer?: string;
29
+ /** The app's id. Default `PONTIVE_CLIENT_ID`. */
30
+ clientId?: string;
31
+ /**
32
+ * Set for a confidential app. It is sent on every token call, and is what
33
+ * lets the app hold its refresh token on its server at all. Default
34
+ * `PONTIVE_CLIENT_SECRET`.
35
+ */
36
+ clientSecret?: string;
37
+ /**
38
+ * Encrypts the session cookie. At least 32 characters; rotating it signs
39
+ * everyone out. Required with a `clientSecret`; unused without one, where the
40
+ * server stores nothing. Default `PONTIVE_SESSION_SECRET`.
41
+ */
42
+ sessionSecret?: string;
43
+ /**
44
+ * The app's public origin, e.g. `https://app.acme.com`. Set it for any
45
+ * deployment behind a proxy or in a container, where the request's own URL
46
+ * names the address the server binds to rather than the one a browser uses.
47
+ * Without it the origin comes from `x-forwarded-proto`/`x-forwarded-host`,
48
+ * then the request URL.
49
+ */
50
+ baseUrl?: string;
51
+ /**
52
+ * Without a `clientSecret`: where the auth proxy serves the auth server on
53
+ * this app's origin. Default `/__pontive`, the auth proxy's own default.
54
+ */
55
+ authPath?: string;
56
+ /** Default `openid email profile offline_access`. */
57
+ scopes?: string;
58
+ /** Where the SDK's sign-in routes live. Default `/api/auth`. */
59
+ basePath?: string;
60
+ /** Default `${origin}${basePath}/callback`; must be registered on the app verbatim. */
61
+ redirectUri?: string;
62
+ /** The app's own sign-in page: failed sign-ins and signed-out users land here. Default `/login`. */
63
+ signInPath?: string;
64
+ /** Where a sign-in lands when it did not start from a page. Default `/`. */
65
+ afterSignInPath?: string;
66
+ /** An OIDC `prompt` to send, e.g. `login`. */
67
+ prompt?: string;
68
+ /** Default `pontive_session`. */
69
+ cookieName?: string;
70
+ /** Default: whether the public origin is https. */
71
+ secureCookies?: boolean;
72
+ /**
73
+ * Whether the SDK's own cookies — the session and the sign-in transaction —
74
+ * are written `SameSite=None; Secure`, so the browser still sends them to a
75
+ * page inside an iframe on another site: an app builder's preview
76
+ * (pontive-spec 06, *SDK in builder previews*). `"auto"`, the default, does
77
+ * so when the public origin is a builder preview host (`*.lovable.app`,
78
+ * `*.lovableproject.com`, `*.vusercontent.net`, `*.v0.app`,
79
+ * `*.webcontainer-api.io`, `*.replit.dev`, …); `true` always, `false`
80
+ * never. Lax everywhere else. A browser that blocks third-party cookies
81
+ * (Safari, Firefox's partitioning) withholds them in the frame anyway.
82
+ */
83
+ iframeSafe?: boolean | "auto";
84
+ /**
85
+ * Whether sign-in uses the auth domain's hosted preview callback as its
86
+ * `redirect_uri` (pontive-spec 06, *Builder previews*): for an app builder's
87
+ * preview, whose host changes per draft and cannot be registered. The app
88
+ * turns the builder on in its *Builder previews* setting, on a development
89
+ * instance. The sign-in then runs in a popup; the callback page hands the
90
+ * code back to this page, which forwards it to the `callback` route, and the
91
+ * code is redeemed here with `redirect_uri` the hosted callback. `"auto"`,
92
+ * the default, does so when the public origin is a preview host of a known
93
+ * builder (`*.lovableproject.com`, `*.vusercontent.net`,
94
+ * `*.<server>.replit.dev`, …); `"always"` everywhere, `"never"` never — for
95
+ * a preview whose exact callback is registered.
96
+ */
97
+ previewCallback?: "auto" | "always" | "never";
98
+ /** The session cookie's lifetime. Default 7 days. */
99
+ sessionMaxAgeSeconds?: number;
100
+ /** Refresh when fewer than this many seconds remain. Default 60. */
101
+ refreshSkewSeconds?: number;
102
+ /** Defaults to the global `fetch`. */
103
+ fetch?: typeof fetch;
104
+ /** Where the SDK reports a failed refresh or sign-in. Defaults to `console`. */
105
+ logger?: Pick<Console, "warn">;
106
+ }
107
+ export interface ResolvedConfig {
108
+ /** `server`: a confidential app holding its own session. `browser`: the browser SDK's session, read. */
109
+ mode: "server" | "browser";
110
+ authPath: string;
111
+ issuer: string;
112
+ clientId: string;
113
+ clientSecret?: string;
114
+ sessionSecret: string;
115
+ baseUrl?: string;
116
+ scopes: string;
117
+ basePath: string;
118
+ redirectUri?: string;
119
+ signInPath: string;
120
+ afterSignInPath: string;
121
+ prompt?: string;
122
+ cookieName: string;
123
+ secureCookies?: boolean;
124
+ iframeSafe: boolean | "auto";
125
+ previewCallback: "auto" | "always" | "never";
126
+ sessionMaxAgeSeconds: number;
127
+ refreshSkewSeconds: number;
128
+ fetch: typeof fetch;
129
+ logger: Pick<Console, "warn">;
130
+ }
131
+ export declare function resolveConfig(config: ServerAuthConfig): ResolvedConfig;