@oauth-spa-kit/server 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,6 +65,39 @@ for the lower-level protocol primitives these handlers are built from, and
65
65
  [`@oauth-spa-kit/react`](https://www.npmjs.com/package/@oauth-spa-kit/react)
66
66
  for a client-side `useAuth()` hook that talks to these routes.
67
67
 
68
+ ## AuthZEN (externalized authorization)
69
+
70
+ Once a request is authenticated, [`evaluateAccess`](https://openid.net/specs/authorization-api-1_0-01.html)
71
+ and friends ask a [OpenID AuthZEN](https://openid.net/specs/authorization-api-1_0-01.html)-conformant
72
+ Policy Decision Point (OpenFGA, Topaz, Cerbos, Aserto, ...) whether the
73
+ session's subject may perform an action -- reusing the *same* session access
74
+ token `getAuthorizationHeader` would hand to any other upstream resource
75
+ server, so the PDP is treated like any other resource server this BFF calls
76
+ on the user's behalf, not a separately-credentialed service.
77
+
78
+ ```ts
79
+ import { evaluateAccess, type AuthzenClientConfig } from "@oauth-spa-kit/server";
80
+
81
+ const authzen: AuthzenClientConfig = { pdpUrl: "https://pdp.example.com" };
82
+
83
+ // In an API route, after you already have `request` and `config` (above):
84
+ const access = await evaluateAccess(request, config, authzen, {
85
+ subject: { type: "user", id: user.sub },
86
+ resource: { type: "document", id: params.docId },
87
+ action: { name: "can_read" },
88
+ });
89
+ if (access === null) return new Response("Unauthorized", { status: 401 }); // no session
90
+ if (!access.result.decision) return new Response("Forbidden", { status: 403 });
91
+ ```
92
+
93
+ Every AuthZEN call returns `null` when there's no session to authorize with
94
+ (the same signal `getAuthorizationHeader` uses), and an `{ result, setCookie? }`
95
+ otherwise -- forward `setCookie` on your response if the underlying access
96
+ token needed a refresh. Also exported: `evaluateAccessBatch` (`POST
97
+ /access/v1/evaluations`, several checks in one PDP round trip) and
98
+ `searchResources` / `searchSubjects` / `searchActions` (the AuthZEN search
99
+ APIs -- e.g. "which documents can this user read").
100
+
68
101
  ## License
69
102
 
70
103
  MIT
@@ -0,0 +1,119 @@
1
+ import { type OAuthHandlersConfig } from "./handlers.js";
2
+ /**
3
+ * OpenID AuthZEN Authorization API 1.0 (https://openid.net/specs/authorization-api-1_0-01.html).
4
+ * Wire types mirror the spec's JSON shapes exactly, snake_case fields
5
+ * included, so a request/response can be copied straight from the spec or a
6
+ * PDP's own docs (OpenFGA, Topaz, Cerbos, Aserto, ...) without a translation
7
+ * layer.
8
+ */
9
+ export interface AuthzenEntity {
10
+ type: string;
11
+ id?: string;
12
+ properties?: Record<string, unknown>;
13
+ }
14
+ export interface AuthzenAction {
15
+ name: string;
16
+ properties?: Record<string, unknown>;
17
+ }
18
+ export type AuthzenContext = Record<string, unknown>;
19
+ export interface AuthzenEvaluationRequest {
20
+ subject: AuthzenEntity;
21
+ resource?: AuthzenEntity;
22
+ action?: AuthzenAction;
23
+ context?: AuthzenContext;
24
+ }
25
+ export interface AuthzenEvaluationResponse {
26
+ decision: boolean;
27
+ context?: {
28
+ id?: string;
29
+ reason_admin?: Record<string, unknown>;
30
+ reason_user?: Record<string, unknown>;
31
+ [key: string]: unknown;
32
+ };
33
+ }
34
+ export interface AuthzenEvaluationsRequest {
35
+ /** Defaults applied to every entry in `evaluations` that omits the field. */
36
+ subject?: AuthzenEntity;
37
+ resource?: AuthzenEntity;
38
+ action?: AuthzenAction;
39
+ context?: AuthzenContext;
40
+ evaluations: Array<{
41
+ subject?: AuthzenEntity;
42
+ resource?: AuthzenEntity;
43
+ action?: AuthzenAction;
44
+ context?: AuthzenContext;
45
+ }>;
46
+ options?: {
47
+ evaluations_semantic?: "execute_all" | "deny_on_first_deny" | "permit_on_first_permit";
48
+ };
49
+ }
50
+ export interface AuthzenEvaluationsResponse {
51
+ evaluations: AuthzenEvaluationResponse[];
52
+ }
53
+ export interface AuthzenPageRequest {
54
+ token?: string;
55
+ }
56
+ export interface AuthzenPageResponse {
57
+ next_token?: string;
58
+ }
59
+ export interface AuthzenResourceSearchRequest {
60
+ subject: AuthzenEntity;
61
+ action: AuthzenAction;
62
+ /** Partial resource -- typically just `{ type }` to scope the search. */
63
+ resource?: Partial<AuthzenEntity>;
64
+ context?: AuthzenContext;
65
+ page?: AuthzenPageRequest;
66
+ }
67
+ export interface AuthzenResourceSearchResponse {
68
+ results: AuthzenEntity[];
69
+ page?: AuthzenPageResponse;
70
+ }
71
+ export interface AuthzenSubjectSearchRequest {
72
+ resource: AuthzenEntity;
73
+ action: AuthzenAction;
74
+ /** Partial subject -- typically just `{ type }` to scope the search. */
75
+ subject?: Partial<AuthzenEntity>;
76
+ context?: AuthzenContext;
77
+ page?: AuthzenPageRequest;
78
+ }
79
+ export interface AuthzenSubjectSearchResponse {
80
+ results: AuthzenEntity[];
81
+ page?: AuthzenPageResponse;
82
+ }
83
+ export interface AuthzenActionSearchRequest {
84
+ subject: AuthzenEntity;
85
+ resource: AuthzenEntity;
86
+ /** Partial action -- typically just `{ name }` to scope the search. */
87
+ action?: Partial<AuthzenAction>;
88
+ context?: AuthzenContext;
89
+ page?: AuthzenPageRequest;
90
+ }
91
+ export interface AuthzenActionSearchResponse {
92
+ results: AuthzenAction[];
93
+ page?: AuthzenPageResponse;
94
+ }
95
+ export declare class AuthzenError extends Error {
96
+ readonly status?: number | undefined;
97
+ readonly body?: string | undefined;
98
+ constructor(message: string, status?: number | undefined, body?: string | undefined);
99
+ }
100
+ export interface AuthzenClientConfig {
101
+ /** PDP base URL, e.g. `"https://pdp.example.com"` -- the `/access/v1/...` paths are resolved against it. */
102
+ pdpUrl: string;
103
+ fetchImpl?: typeof fetch;
104
+ }
105
+ export interface AuthzenResult<T> {
106
+ result: T;
107
+ /** Set only when the underlying session's access token was refreshed -- forward this Set-Cookie on your outgoing response. */
108
+ setCookie?: string;
109
+ }
110
+ /** Single access decision -- `POST /access/v1/evaluation`. */
111
+ export declare function evaluateAccess(request: Request, config: OAuthHandlersConfig, authzen: AuthzenClientConfig, evaluation: AuthzenEvaluationRequest): Promise<AuthzenResult<AuthzenEvaluationResponse> | null>;
112
+ /** Batch access decisions in one PDP round trip -- `POST /access/v1/evaluations`. */
113
+ export declare function evaluateAccessBatch(request: Request, config: OAuthHandlersConfig, authzen: AuthzenClientConfig, evaluations: AuthzenEvaluationsRequest): Promise<AuthzenResult<AuthzenEvaluationsResponse> | null>;
114
+ /** Which resources the subject can perform `action` on -- `POST /access/v1/search/resource`. */
115
+ export declare function searchResources(request: Request, config: OAuthHandlersConfig, authzen: AuthzenClientConfig, search: AuthzenResourceSearchRequest): Promise<AuthzenResult<AuthzenResourceSearchResponse> | null>;
116
+ /** Which subjects can perform `action` on `resource` -- `POST /access/v1/search/subject`. */
117
+ export declare function searchSubjects(request: Request, config: OAuthHandlersConfig, authzen: AuthzenClientConfig, search: AuthzenSubjectSearchRequest): Promise<AuthzenResult<AuthzenSubjectSearchResponse> | null>;
118
+ /** Which actions the subject can perform on `resource` -- `POST /access/v1/search/action`. */
119
+ export declare function searchActions(request: Request, config: OAuthHandlersConfig, authzen: AuthzenClientConfig, search: AuthzenActionSearchRequest): Promise<AuthzenResult<AuthzenActionSearchResponse> | null>;
@@ -0,0 +1,63 @@
1
+ import { getAuthorizationHeader } from "./handlers.js";
2
+ export class AuthzenError extends Error {
3
+ status;
4
+ body;
5
+ constructor(message, status, body) {
6
+ super(message);
7
+ this.status = status;
8
+ this.body = body;
9
+ this.name = "AuthzenError";
10
+ }
11
+ }
12
+ function pdpEndpoint(pdpUrl, path) {
13
+ return `${pdpUrl.replace(/\/+$/, "")}/${path}`;
14
+ }
15
+ async function postToPdp(authzen, path, authorizationHeader, body) {
16
+ const fetchImpl = authzen.fetchImpl ?? fetch;
17
+ const response = await fetchImpl(pdpEndpoint(authzen.pdpUrl, path), {
18
+ method: "POST",
19
+ headers: {
20
+ "content-type": "application/json",
21
+ authorization: authorizationHeader,
22
+ },
23
+ body: JSON.stringify(body),
24
+ });
25
+ if (!response.ok) {
26
+ const responseBody = await response.text().catch(() => "");
27
+ throw new AuthzenError(`AuthZEN PDP call to ${path} failed with status ${response.status}`, response.status, responseBody);
28
+ }
29
+ return response.json();
30
+ }
31
+ /**
32
+ * Calls the PDP with the caller's own session -- the same access token
33
+ * `getAuthorizationHeader` would hand to any other upstream resource
34
+ * server -- and returns `null` when there's no session to authorize with,
35
+ * the same "not logged in" signal `getAuthorizationHeader` itself uses.
36
+ */
37
+ async function callPdp(request, config, authzen, path, body) {
38
+ const auth = await getAuthorizationHeader(request, config);
39
+ if (!auth)
40
+ return null;
41
+ const result = await postToPdp(authzen, path, auth.header, body);
42
+ return { result, setCookie: auth.setCookie };
43
+ }
44
+ /** Single access decision -- `POST /access/v1/evaluation`. */
45
+ export async function evaluateAccess(request, config, authzen, evaluation) {
46
+ return callPdp(request, config, authzen, "access/v1/evaluation", evaluation);
47
+ }
48
+ /** Batch access decisions in one PDP round trip -- `POST /access/v1/evaluations`. */
49
+ export async function evaluateAccessBatch(request, config, authzen, evaluations) {
50
+ return callPdp(request, config, authzen, "access/v1/evaluations", evaluations);
51
+ }
52
+ /** Which resources the subject can perform `action` on -- `POST /access/v1/search/resource`. */
53
+ export async function searchResources(request, config, authzen, search) {
54
+ return callPdp(request, config, authzen, "access/v1/search/resource", search);
55
+ }
56
+ /** Which subjects can perform `action` on `resource` -- `POST /access/v1/search/subject`. */
57
+ export async function searchSubjects(request, config, authzen, search) {
58
+ return callPdp(request, config, authzen, "access/v1/search/subject", search);
59
+ }
60
+ /** Which actions the subject can perform on `resource` -- `POST /access/v1/search/action`. */
61
+ export async function searchActions(request, config, authzen, search) {
62
+ return callPdp(request, config, authzen, "access/v1/search/action", search);
63
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from "./session.js";
2
2
  export * from "./handlers.js";
3
+ export * from "./authzen.js";
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from "./session.js";
2
2
  export * from "./handlers.js";
3
+ export * from "./authzen.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oauth-spa-kit/server",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "description": "BFF-pattern OAuth handlers: sealed HttpOnly-cookie sessions + login/callback/refresh/logout route factories, built on Web-standard Request/Response so they drop into Nitro, Next.js route handlers, Cloudflare Workers, or plain Node (via a small adapter).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -22,7 +22,7 @@
22
22
  "node": ">=18"
23
23
  },
24
24
  "dependencies": {
25
- "@oauth-spa-kit/core": "1.0.2"
25
+ "@oauth-spa-kit/core": "1.2.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "typescript": "^5.6.0",