@consciousclouds/access 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@consciousclouds/access` are documented here.
4
+
5
+ ## 0.1.0
6
+
7
+ - Initial release. The policy-free Access SDK for the Control Plane's operator
8
+ identity + Access surface (control-plane-doctrine §5, Build Increment 1).
9
+ - Four subpath exports: root (types) · `/client` (isomorphic no-store HTTP
10
+ wrappers) · `/server` (request-bound, fail-closed BFF adapter) · `/react`
11
+ (`AccessProvider` + operator hooks, including the
12
+ `useOperatorPermissionResolver` bridge).
13
+ - Reuses the `Capability` `<primitive>.<verb>` vocabulary and the operator-shell
14
+ `allowed|denied|unknown` decision union (`unknown` ⇒ denied).
15
+ - First consumer: the CCU Admin migration off the dev-auth stub onto the real
16
+ Control Plane.
package/LICENSE ADDED
@@ -0,0 +1,171 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or contributory
82
+ patent infringement, then any patent licenses granted to You under
83
+ this License for that Work shall terminate as of the date such
84
+ litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative Works
92
+ a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works that
98
+ You distribute, all copyright, patent, trademark, and attribution
99
+ notices from the Source form of the Work, excluding those notices
100
+ that do not pertain to any part of the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the attribution
104
+ notices contained within such NOTICE file, in at least one of the
105
+ following places: within a NOTICE text provided as part of the
106
+ Derivative Works; within the Source form or documentation, if
107
+ provided along with the Derivative Works; or, within a display
108
+ generated by the Derivative Works, if and wherever such third-party
109
+ notices normally appear. The contents of the NOTICE file are for
110
+ informational purposes only and do not modify the License. You may
111
+ add Your own attribution notices within Derivative Works that You
112
+ distribute, alongside or in addition to the NOTICE text from the
113
+ Work, provided that such additional attribution notices cannot be
114
+ construed as modifying the License.
115
+
116
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
117
+ any Contribution intentionally submitted for inclusion in the Work by
118
+ You to the Licensor shall be under the terms and conditions of this
119
+ License, without any additional terms or conditions.
120
+
121
+ 6. Trademarks. This License does not grant permission to use the trade
122
+ names, trademarks, service marks, or product names of the Licensor,
123
+ except as required for reasonable and customary use in describing the
124
+ origin of the Work and reproducing the content of the NOTICE file.
125
+
126
+ 7. Disclaimer of Warranty. Unless required by applicable law or
127
+ agreed to in writing, Licensor provides the Work (and each
128
+ Contributor provides its Contributions) on an "AS IS" BASIS,
129
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
130
+ implied, including, without limitation, any conditions of TITLE,
131
+ MERCHANTIBILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely
132
+ responsible for determining the appropriateness of using or
133
+ redistributing the Work and assume any risks associated with Your
134
+ exercise of permissions under this License.
135
+
136
+ 8. Limitation of Liability. In no event and under no legal theory,
137
+ whether in tort (including negligence), contract, or otherwise,
138
+ unless required by applicable law (such as deliberate and grossly
139
+ negligent acts) or agreed to in writing, shall any Contributor be
140
+ liable to You for damages, including any direct, indirect, special,
141
+ incidental, or exemplary damages of any character arising as a result
142
+ of this License or out of the use or inability to use the Work
143
+ (including but not limited to damages for loss of goodwill, work
144
+ stoppage, computer failure or malfunction, or all other commercial
145
+ damages or losses), even if such Contributor has been advised of the
146
+ possibility of such damages.
147
+
148
+ 9. Accepting Warranty or Liability. While redistributing the Work or
149
+ Derivative Works thereof, You may choose to offer, and charge a fee
150
+ for, acceptance of support, warranty, indemnity, or other liability
151
+ obligations and/or rights consistent with this License. However, in
152
+ accepting such obligations, You may offer such obligations only on
153
+ Your own behalf and on Your sole responsibility, not on behalf of any
154
+ other Contributor, and only if You agree to indemnify, defend, and
155
+ hold each Contributor harmless for any liability incurred by, or
156
+ claims asserted against, such Contributor by reason of your accepting
157
+ any such warranty or additional liability.
158
+
159
+ Copyright 2024 Conscious Clouds
160
+
161
+ Licensed under the Apache License, Version 2.0 (the "License");
162
+ you may not use this file except in compliance with the License.
163
+ You may obtain a copy of the License at
164
+
165
+ http://www.apache.org/licenses/LICENSE-2.0
166
+
167
+ Unless required by applicable law or agreed to in writing, software
168
+ distributed under the License is distributed on an "AS IS" BASIS,
169
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
170
+ See the License for the specific language governing permissions and
171
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # @consciousclouds/access
2
+
3
+ The thin, **policy-free** client for the Control Plane's operator identity +
4
+ Access surface — the SDK half of *"central authority, local enforcement"*
5
+ ([control-plane-doctrine](../../../docs/design/control-plane-doctrine.md) §5).
6
+
7
+ The Control Plane **decides**; this SDK only asks the five operating questions
8
+ and **enforces the answers, fail-closed**:
9
+
10
+ > *Who is the current operator? What project is being entered? What permissions
11
+ > does this operator have here? Can this action be performed? What capabilities
12
+ > are granted?*
13
+
14
+ **No policy logic.** Types + thin HTTP wrappers + React/server wiring only. There
15
+ is no role→capability mapping, no grant cache, no second permission vocabulary —
16
+ it reuses the `Capability` `<primitive>.<verb>` type from
17
+ `@consciousclouds/capability-sdk` and the operator-shell's `allowed|denied|unknown`
18
+ decision union (`unknown` ⇒ denied).
19
+
20
+ ## Exports
21
+
22
+ | Subpath | What | Runs |
23
+ |---|---|---|
24
+ | `.` | Types only — `OperatorIdentity`, `ProjectScope`, `Grant`, `AccessDecision`, `AccessIntent`, `AccessSession`, `PermissionResolver` | anywhere |
25
+ | `./client` | `createAccessClient({ baseUrl })` → `login` · `refresh` · `logout` · `whoami` · `session` · `can`. Isomorphic, every call `cache: 'no-store'`, holds no grant cache | where the token is readable |
26
+ | `./server` | `createAccess({ baseUrl, cookieName, scope, capabilities })` → request-bound `identity` · `scope` · `session` · `can`. **Fail-closed** (deny / unreachable / throw ⇒ denied) | server (BFF / RSC) |
27
+ | `./react` | `AccessProvider` + `useOperator` · `useProjectScope` · `useGrants` · `useCapabilities` · `useCan` · `useOperatorPermissionResolver` | client |
28
+
29
+ ## The grant-resolution note
30
+
31
+ `GET /access/session` returns the operator's **role** assignments, not resolved
32
+ `<primitive>.<verb>` capabilities. The only path to a capability decision is
33
+ `POST /access/authorize`. So `AccessSession.grants` (the capability set the UI
34
+ gates on) is assembled by asking the Control Plane's authorize decision for a
35
+ **candidate** capability set — a policy-free aggregation (the Control Plane
36
+ decides each one). The candidate set is the capabilities a surface gates its nav
37
+ on (e.g. `factory.observe`).
38
+
39
+ ## The load-bearing rule
40
+
41
+ `access.can(scope, action)` server-side, **uncached, fail-closed** — before any
42
+ admin read or token-spending turn is forwarded. A hidden nav item is never the
43
+ enforcement; the server call is.
44
+
45
+ ## Adopting it for a second surface
46
+
47
+ Two adapters from the standard template — an identity adapter (its cookie name,
48
+ login endpoint, issuer/audience) and an access adapter (its `scope`, its BFF
49
+ routes) — plus the product's Brand + Flavor. No shell fork, no SDK fork.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `@consciousclouds/access/client` — isomorphic, no-store HTTP wrappers over the
3
+ * Control Plane's operator-identity + Access surface. Thin by contract: parse
4
+ * the request, call the endpoint, shape the response. NO policy, NO grant cache
5
+ * (every call is `cache: 'no-store'`; the Control Plane is the only authority).
6
+ *
7
+ * These wrappers take an explicit operator `token` — they are meant to run where
8
+ * the token is readable (the BFF `/server` adapter, a login route). The browser
9
+ * never holds the operator token (it lives in an httpOnly cookie); browser code
10
+ * goes through the product's same-origin BFF routes and the `/react` hooks.
11
+ */
12
+ import type { AccessDecision, AccessIntent, AccessSession, Grant, OperatorIdentity, ProjectScope } from '../types.js';
13
+ /** Configuration for a client bound to one Control Plane origin. */
14
+ export interface AccessClientConfig {
15
+ /** The Control Plane base URL (server-only; never a `NEXT_PUBLIC_` value). */
16
+ baseUrl: string;
17
+ /** Optional fetch implementation (defaults to the ambient global `fetch`). */
18
+ fetchImpl?: typeof fetch;
19
+ /** Default freshness window the assembled AccessSession advertises. */
20
+ ttlSeconds?: number;
21
+ }
22
+ /** The credential a login accepts. Operators only — no product-user path exists. */
23
+ export interface LoginInput {
24
+ email: string;
25
+ password: string;
26
+ }
27
+ /** The token bundle the Control Plane returns from login/refresh (snake_case wire → camelCase). */
28
+ export interface TokenSet {
29
+ accessToken: string;
30
+ refreshToken: string;
31
+ sid: string;
32
+ operatorId: string;
33
+ /** Access-token lifetime in seconds (~15m). */
34
+ expiresIn: number;
35
+ tokenType: string;
36
+ }
37
+ /** An error carrying the HTTP status so callers can distinguish 401 from unreachable. */
38
+ export declare class AccessError extends Error {
39
+ readonly status: number;
40
+ readonly code?: string;
41
+ constructor(status: number, message: string, code?: string);
42
+ }
43
+ /** Build the display identity from an access token's claims (null if malformed). */
44
+ export declare function identityFromToken(token: string | null | undefined): OperatorIdentity | null;
45
+ /** A client bound to one Control Plane origin. */
46
+ export interface AccessClient {
47
+ login(input: LoginInput): Promise<TokenSet>;
48
+ refresh(refreshToken: string): Promise<TokenSet>;
49
+ logout(token: string): Promise<void>;
50
+ whoami(token: string): Promise<OperatorIdentity | null>;
51
+ session(token: string, scope: ProjectScope, candidates?: readonly Grant[]): Promise<AccessSession>;
52
+ can(token: string, scope: ProjectScope, action: Grant, intent?: AccessIntent): Promise<AccessDecision>;
53
+ }
54
+ /** Create a client bound to one Control Plane origin. */
55
+ export declare function createAccessClient(config: AccessClientConfig): AccessClient;
56
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,aAAa,EACb,KAAK,EACL,gBAAgB,EAChB,YAAY,EACb,MAAM,aAAa,CAAC;AAErB,oEAAoE;AACpE,MAAM,WAAW,kBAAkB;IACjC,8EAA8E;IAC9E,OAAO,EAAE,MAAM,CAAC;IAChB,8EAA8E;IAC9E,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IACzB,uEAAuE;IACvE,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,oFAAoF;AACpF,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,mGAAmG;AACnG,MAAM,WAAW,QAAQ;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MA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appers over the
3
+ * Control Plane's operator-identity + Access surface. Thin by contract: parse
4
+ * the request, call the endpoint, shape the response. NO policy, NO grant cache
5
+ * (every call is `cache: 'no-store'`; the Control Plane is the only authority).
6
+ *
7
+ * These wrappers take an explicit operator `token` — they are meant to run where
8
+ * the token is readable (the BFF `/server` adapter, a login route). The browser
9
+ * never holds the operator token (it lives in an httpOnly cookie); browser code
10
+ * goes through the product's same-origin BFF routes and the `/react` hooks.
11
+ */
12
+ /** An error carrying the HTTP status so callers can distinguish 401 from unreachable. */
13
+ export class AccessError extends Error {
14
+ constructor(status, message, code) {
15
+ super(message);
16
+ this.name = 'AccessError';
17
+ this.status = status;
18
+ this.code = code;
19
+ }
20
+ }
21
+ const DEFAULT_TTL_SECONDS = 30;
22
+ /** Decode a JWT's claims for DISPLAY only (no verification). Isomorphic (atob, no Buffer). */
23
+ function decodeClaims(token) {
24
+ const parts = token.split('.');
25
+ if (parts.length !== 3)
26
+ return null;
27
+ try {
28
+ const b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
29
+ const pad = b64.length % 4 === 0 ? '' : '='.repeat(4 - (b64.length % 4));
30
+ const json = decodeURIComponent(Array.prototype.map
31
+ .call(atob(b64 + pad), (c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
32
+ .join(''));
33
+ return JSON.parse(json);
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ function str(v) {
40
+ return typeof v === 'string' ? v : '';
41
+ }
42
+ /** Build the display identity from an access token's claims (null if malformed). */
43
+ export function identityFromToken(token) {
44
+ if (!token)
45
+ return null;
46
+ const claims = decodeClaims(token);
47
+ if (!claims || !str(claims.sub))
48
+ return null;
49
+ return {
50
+ sub: str(claims.sub),
51
+ email: str(claims.email),
52
+ iss: str(claims.iss),
53
+ aud: str(claims.aud),
54
+ exp: typeof claims.exp === 'number' ? claims.exp : undefined,
55
+ };
56
+ }
57
+ /** Extract the (sub, sid) an Access call needs from a verified token's claims. */
58
+ function principalFromToken(token) {
59
+ const claims = decodeClaims(token) ?? {};
60
+ return { sub: str(claims.sub), sid: str(claims.sid) };
61
+ }
62
+ /** Create a client bound to one Control Plane origin. */
63
+ export function createAccessClient(config) {
64
+ const doFetch = config.fetchImpl ?? fetch;
65
+ const base = config.baseUrl.replace(/\/$/, '');
66
+ const ttlSeconds = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
67
+ function tokenSetFrom(body) {
68
+ return {
69
+ accessToken: str(body.access_token),
70
+ refreshToken: str(body.refresh_token),
71
+ sid: str(body.sid),
72
+ operatorId: str(body.operator_id),
73
+ expiresIn: typeof body.expires_in === 'number' ? body.expires_in : 0,
74
+ tokenType: str(body.token_type) || 'Bearer',
75
+ };
76
+ }
77
+ async function login(input) {
78
+ const res = await doFetch(`${base}/operator/login`, {
79
+ method: 'POST',
80
+ headers: { 'Content-Type': 'application/json' },
81
+ body: JSON.stringify({ email: input.email, password: input.password }),
82
+ cache: 'no-store',
83
+ });
84
+ if (!res.ok) {
85
+ const detail = (await res.json().catch(() => ({})));
86
+ throw new AccessError(res.status, detail.error?.message ?? `login failed (${res.status})`, detail.error?.code);
87
+ }
88
+ return tokenSetFrom((await res.json()));
89
+ }
90
+ async function refresh(refreshToken) {
91
+ const res = await doFetch(`${base}/operator/refresh`, {
92
+ method: 'POST',
93
+ headers: { 'Content-Type': 'application/json' },
94
+ body: JSON.stringify({ refresh_token: refreshToken }),
95
+ cache: 'no-store',
96
+ });
97
+ if (!res.ok)
98
+ throw new AccessError(res.status, `refresh failed (${res.status})`);
99
+ return tokenSetFrom((await res.json()));
100
+ }
101
+ async function logout(token) {
102
+ await doFetch(`${base}/operator/logout`, {
103
+ method: 'POST',
104
+ headers: { Authorization: `Bearer ${token}` },
105
+ cache: 'no-store',
106
+ });
107
+ }
108
+ async function whoami(token) {
109
+ const fromToken = identityFromToken(token);
110
+ if (!fromToken)
111
+ return null;
112
+ const res = await doFetch(`${base}/operator/me`, {
113
+ headers: { Authorization: `Bearer ${token}` },
114
+ cache: 'no-store',
115
+ });
116
+ if (!res.ok)
117
+ return fromToken;
118
+ const body = (await res.json().catch(() => ({})));
119
+ return {
120
+ ...fromToken,
121
+ email: str(body.email) || fromToken.email,
122
+ displayName: str(body.display_name) || undefined,
123
+ };
124
+ }
125
+ async function can(token, scope, action, intent = 'mutate') {
126
+ const { sub, sid } = principalFromToken(token);
127
+ if (!sub || !sid)
128
+ return 'denied';
129
+ // Send the bearer so an edge-authed ingress (the Operator Gateway) verifies the operator; the
130
+ // (operator_sub, sid) body stays the Control Plane's S2S proof (defense in depth — the CP re-proves).
131
+ const res = await doFetch(`${base}/access/authorize`, {
132
+ method: 'POST',
133
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
134
+ body: JSON.stringify({
135
+ operator_sub: sub,
136
+ sid,
137
+ action,
138
+ project: scope.project,
139
+ intent,
140
+ }),
141
+ cache: 'no-store',
142
+ });
143
+ if (!res.ok)
144
+ return 'denied';
145
+ const body = (await res.json().catch(() => ({})));
146
+ return body.allowed === true ? 'allowed' : 'denied';
147
+ }
148
+ async function session(token, scope, candidates = []) {
149
+ const identity = identityFromToken(token);
150
+ const empty = { identity, scope, roles: [], grants: [], ttlSeconds };
151
+ const { sub, sid } = principalFromToken(token);
152
+ if (!sub || !sid)
153
+ return empty;
154
+ const url = `${base}/access/session?operator_sub=${encodeURIComponent(sub)}&sid=${encodeURIComponent(sid)}&project=${encodeURIComponent(scope.project)}`;
155
+ // Bearer for the edge-authed ingress; the (operator_sub, sid) query stays the CP's S2S proof.
156
+ const res = await doFetch(url, { cache: 'no-store', headers: { Authorization: `Bearer ${token}` } });
157
+ if (!res.ok)
158
+ return empty;
159
+ const body = (await res.json().catch(() => ({})));
160
+ if (!body.live)
161
+ return empty;
162
+ const roles = Array.from(new Set((body.grants ?? []).map((g) => g.role).filter(Boolean)));
163
+ // The session endpoint returns ROLES, not resolved capabilities. Resolve the
164
+ // granted subset by asking the Control Plane's authorize decision for each
165
+ // candidate capability — policy-free aggregation (the Control Plane decides
166
+ // each one). A candidate is `read` unless it declares mutate semantics; we
167
+ // probe with `read` so a read-only operator's read capabilities resolve.
168
+ const grants = [];
169
+ for (const action of candidates) {
170
+ const decision = await can(token, scope, action, 'read').catch(() => 'denied');
171
+ if (decision === 'allowed')
172
+ grants.push(action);
173
+ }
174
+ return { identity, scope, roles, grants, ttlSeconds };
175
+ }
176
+ return { login, refresh, logout, whoami, session, can };
177
+ }
178
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAsCH,yFAAyF;AACzF,MAAM,OAAO,WAAY,SAAQ,KAAK;IAGpC,YAAY,MAAc,EAAE,OAAe,EAAE,IAAa;QACxD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAED,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAE/B,8FAA8F;AAC9F,SAAS,YAAY,CAAC,KAAa;IACjC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACpC,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC3D,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,C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E,CAAC,CAAC;QACrG,IAAI,CAAC,GAAG,CAAC,EAAE;YAAE,OAAO,KAAK,CAAC;QAC1B,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAgB,CAAC;QACjE,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAO,KAAK,CAAC;QAE7B,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QAE1F,6EAA6E;QAC7E,2EAA2E;QAC3E,4EAA4E;QAC5E,2EAA2E;QAC3E,yEAAyE;QACzE,MAAM,MAAM,GAAY,EAAE,CAAC;QAC3B,KAAK,MAAM,MAAM,IAAI,UAAU,EAAE,CAAC;YAChC,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,QAA0B,CAAC,CAAC;YACjG,IAAI,QAAQ,KAAK,SAAS;gBAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAClD,CAAC;QAED,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;AAC1D,CAAC"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@consciousclouds/access` — root export: TYPES ONLY.
3
+ *
4
+ * The thin, policy-free client for the Control Plane's operator identity +
5
+ * Access surface. Import the runtime pieces from the subpaths:
6
+ * - `@consciousclouds/access/client` — isomorphic no-store HTTP wrappers.
7
+ * - `@consciousclouds/access/server` — request-bound, fail-closed BFF adapter.
8
+ * - `@consciousclouds/access/react` — AccessProvider + hooks.
9
+ *
10
+ * This package carries NO policy logic. Every access decision belongs to the
11
+ * Control Plane (control-plane-doctrine §5); the SDK only asks the five
12
+ * operating questions and enforces the answers, fail-closed.
13
+ */
14
+ export type { OperatorIdentity, ProjectScope, Grant, AccessDecision, AccessIntent, AccessSession, PermissionResolver, } from './types.js';
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,YAAY,EACV,gBAAgB,EAChB,YAAY,EACZ,KAAK,EACL,cAAc,EACd,YAAY,EACZ,aAAa,EACb,kBAAkB,GACnB,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@consciousclouds/access` — root export: TYPES ONLY.
3
+ *
4
+ * The thin, policy-free client for the Control Plane's operator identity +
5
+ * Access surface. Import the runtime pieces from the subpaths:
6
+ * - `@consciousclouds/access/client` — isomorphic no-store HTTP wrappers.
7
+ * - `@consciousclouds/access/server` — request-bound, fail-closed BFF adapter.
8
+ * - `@consciousclouds/access/react` — AccessProvider + hooks.
9
+ *
10
+ * This package carries NO policy logic. Every access decision belongs to the
11
+ * Control Plane (control-plane-doctrine §5); the SDK only asks the five
12
+ * operating questions and enforces the answers, fail-closed.
13
+ */
14
+ export {};
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG"}
@@ -0,0 +1,30 @@
1
+ import type { AccessDecision, Grant, OperatorIdentity, PermissionResolver, ProjectScope } from '../types.js';
2
+ /** Who is the current operator? (null when unauthenticated). */
3
+ export declare function useOperator(): OperatorIdentity | null;
4
+ /** What project scope is being acted in? */
5
+ export declare function useProjectScope(): ProjectScope;
6
+ /** What capabilities does this operator hold here? (the granted `<primitive>.<verb>` set). */
7
+ export declare function useGrants(): Grant[];
8
+ /**
9
+ * "What capabilities are granted?" — the doctrine's fifth operating question.
10
+ * Same granted set as {@link useGrants}, named for the question it answers.
11
+ */
12
+ export declare function useCapabilities(): Grant[];
13
+ /**
14
+ * Can this action be performed? Reflects the fetched grants snapshot, fail-closed:
15
+ * `allowed` when the capability is in the granted set; `unknown` when there is no
16
+ * operator (nothing resolved yet); `denied` otherwise. The load-bearing check is
17
+ * still the server-side `access.can` before a read/turn is forwarded — this hook
18
+ * is for UX gating, never the enforcement.
19
+ */
20
+ export declare function useCan(action: Grant): AccessDecision;
21
+ /**
22
+ * The bridge: a PermissionResolver built over the CURRENT grants snapshot —
23
+ * the same shape `createOperatorPermissionResolver(authenticated, grants)`
24
+ * produces (a Set-membership check; `unknown` ⇒ denied). Because the provider
25
+ * refetches the snapshot on mount / focus / route-change / TTL, the grant SOURCE
26
+ * is live without the resolver SHAPE changing. Memoized on the snapshot so the
27
+ * shell's sync decisions stay stable between refetches.
28
+ */
29
+ export declare function useOperatorPermissionResolver(): PermissionResolver;
30
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/react/hooks.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAG7G,gEAAgE;AAChE,wBAAgB,WAAW,IAAI,gBAAgB,GAAG,IAAI,CAErD;AAED,4CAA4C;AAC5C,wBAAgB,eAAe,IAAI,YAAY,CAE9C;AAED,8FAA8F;AAC9F,wBAAgB,SAAS,IAAI,KAAK,EAAE,CAEnC;AAED;;;GAGG;AACH,wBAAgB,eAAe,IAAI,KAAK,EAAE,CAEzC;AAED;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,MAAM,EAAE,KAAK,GAAG,cAAc,CAMpD;AAED;;;;;;;GAOG;AACH,wBAAgB,6BAA6B,IAAI,kBAAkB,CAMlE"}
@@ -0,0 +1,59 @@
1
+ 'use client';
2
+ /**
3
+ * The Access hooks — the five operating questions, answered over the current
4
+ * fresh session snapshot the AccessProvider holds. Every hook is fail-closed:
5
+ * a capability not in the granted snapshot resolves `unknown` (⇒ denied by the
6
+ * shell). There is NO policy here — the grants were decided by the Control Plane.
7
+ */
8
+ import * as React from 'react';
9
+ import { useAccessContext } from './provider.js';
10
+ /** Who is the current operator? (null when unauthenticated). */
11
+ export function useOperator() {
12
+ return useAccessContext().session.identity;
13
+ }
14
+ /** What project scope is being acted in? */
15
+ export function useProjectScope() {
16
+ return useAccessContext().session.scope;
17
+ }
18
+ /** What capabilities does this operator hold here? (the granted `<primitive>.<verb>` set). */
19
+ export function useGrants() {
20
+ return useAccessContext().session.grants;
21
+ }
22
+ /**
23
+ * "What capabilities are granted?" — the doctrine's fifth operating question.
24
+ * Same granted set as {@link useGrants}, named for the question it answers.
25
+ */
26
+ export function useCapabilities() {
27
+ return useAccessContext().session.grants;
28
+ }
29
+ /**
30
+ * Can this action be performed? Reflects the fetched grants snapshot, fail-closed:
31
+ * `allowed` when the capability is in the granted set; `unknown` when there is no
32
+ * operator (nothing resolved yet); `denied` otherwise. The load-bearing check is
33
+ * still the server-side `access.can` before a read/turn is forwarded — this hook
34
+ * is for UX gating, never the enforcement.
35
+ */
36
+ export function useCan(action) {
37
+ const { session, authenticated } = useAccessContext();
38
+ return React.useMemo(() => {
39
+ if (!authenticated)
40
+ return 'unknown';
41
+ return session.grants.includes(action) ? 'allowed' : 'denied';
42
+ }, [authenticated, session.grants, action]);
43
+ }
44
+ /**
45
+ * The bridge: a PermissionResolver built over the CURRENT grants snapshot —
46
+ * the same shape `createOperatorPermissionResolver(authenticated, grants)`
47
+ * produces (a Set-membership check; `unknown` ⇒ denied). Because the provider
48
+ * refetches the snapshot on mount / focus / route-change / TTL, the grant SOURCE
49
+ * is live without the resolver SHAPE changing. Memoized on the snapshot so the
50
+ * shell's sync decisions stay stable between refetches.
51
+ */
52
+ export function useOperatorPermissionResolver() {
53
+ const { session, authenticated } = useAccessContext();
54
+ return React.useMemo(() => {
55
+ const granted = new Set(authenticated ? session.grants : []);
56
+ return (permission) => (granted.has(permission) ? 'allowed' : 'unknown');
57
+ }, [authenticated, session.grants]);
58
+ }
59
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../src/react/hooks.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;GAKG;AAEH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD,gEAAgE;AAChE,MAAM,UAAU,WAAW;IACzB,OAAO,gBAAgB,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC;AAC7C,CAAC;AAED,4CAA4C;AAC5C,MAAM,UAAU,eAAe;IAC7B,OAAO,gBAAgB,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC;AAC1C,CAAC;AAED,8FAA8F;AAC9F,MAAM,UAAU,SAAS;IACvB,OAAO,gBAAgB,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC;AAC3C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe;IAC7B,OAAO,gBAAgB,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC;AAC3C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,MAAM,CAAC,MAAa;IAClC,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,GAAG,gBAAgB,EAAE,CAAC;IACtD,OAAO,KAAK,CAAC,OAAO,CAAiB,GAAG,EAAE;QACxC,IAAI,CAAC,aAAa;YAAE,OAAO,SAAS,CAAC;QACrC,OAAO,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC;IAChE,CAAC,EAAE,CAAC,aAAa,EAAE,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAC9C,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,6BAA6B;IAC3C,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,GAAG,gBAAgB,EAAE,CAAC;IACtD,OAAO,KAAK,CAAC,OAAO,CAAqB,GAAG,EAAE;QAC5C,MAAM,OAAO,GAAG,IAAI,GAAG,CAAS,aAAa,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QACrE,OAAO,CAAC,UAAkB,EAAkB,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IACnG,CAAC,EAAE,CAAC,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;AACtC,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@consciousclouds/access/react` — AccessProvider + the operator hooks.
3
+ * Client-only. Reads a fresh Access session snapshot from the product's
4
+ * same-origin BFF seam; carries no policy and no long-lived cache.
5
+ */
6
+ export { AccessProvider, useAccessContext } from './provider.js';
7
+ export type { AccessProviderProps, AccessContextValue } from './provider.js';
8
+ export { useOperator, useProjectScope, useGrants, useCapabilities, useCan, useOperatorPermissionResolver, } from './hooks.js';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjE,YAAY,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAE7E,OAAO,EACL,WAAW,EACX,eAAe,EACf,SAAS,EACT,eAAe,EACf,MAAM,EACN,6BAA6B,GAC9B,MAAM,YAAY,CAAC"}
@@ -0,0 +1,9 @@
1
+ 'use client';
2
+ /**
3
+ * `@consciousclouds/access/react` — AccessProvider + the operator hooks.
4
+ * Client-only. Reads a fresh Access session snapshot from the product's
5
+ * same-origin BFF seam; carries no policy and no long-lived cache.
6
+ */
7
+ export { AccessProvider, useAccessContext } from './provider.js';
8
+ export { useOperator, useProjectScope, useGrants, useCapabilities, useCan, useOperatorPermissionResolver, } from './hooks.js';
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;GAIG;AAEH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAGjE,OAAO,EACL,WAAW,EACX,eAAe,EACf,SAAS,EACT,eAAe,EACf,MAAM,EACN,6BAA6B,GAC9B,MAAM,YAAY,CAAC"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * AccessProvider — the client-side context that holds a FRESH Access session
3
+ * snapshot for the current operator + scope. It fetches the snapshot from the
4
+ * product's SAME-ORIGIN BFF seam (default `/api/access/session`), never the
5
+ * Control Plane directly — the browser holds no operator token and the Control
6
+ * Plane URL is server-only.
7
+ *
8
+ * NO long-lived cache (control-plane-doctrine §4): the snapshot is refetched on
9
+ * mount, on window focus / tab visibility, on a short TTL, and whenever the
10
+ * caller-supplied `routeKey` changes (pass `usePathname()` for route-change
11
+ * revalidation without coupling this SDK to any router). Fail-closed: a failed
12
+ * fetch yields an empty session (no identity, no grants).
13
+ */
14
+ import * as React from 'react';
15
+ import type { AccessSession, ProjectScope } from '../types.js';
16
+ export interface AccessContextValue {
17
+ /** The current fresh session snapshot. */
18
+ session: AccessSession;
19
+ /** True when an operator identity is present in the snapshot. */
20
+ authenticated: boolean;
21
+ /** Force a refetch of the session snapshot. */
22
+ refresh(): Promise<void>;
23
+ }
24
+ export interface AccessProviderProps {
25
+ /** The project scope this surface acts in (also the fallback when a snapshot has none). */
26
+ scope: ProjectScope;
27
+ /** An SSR-resolved snapshot to paint from before the first client fetch. */
28
+ initialSession?: AccessSession;
29
+ /** The same-origin BFF route returning an AccessSession JSON. */
30
+ sessionEndpoint?: string;
31
+ /** Freshness window (seconds) before a background revalidation. */
32
+ ttlSeconds?: number;
33
+ /** A value that changes on navigation (e.g. `usePathname()`) → triggers a refetch. */
34
+ routeKey?: string;
35
+ children: React.ReactNode;
36
+ }
37
+ export declare function AccessProvider({ scope, initialSession, sessionEndpoint, ttlSeconds, routeKey, children, }: AccessProviderProps): import("react/jsx-runtime").JSX.Element;
38
+ /** Internal: read the Access context (throws when used outside an AccessProvider). */
39
+ export declare function useAccessContext(): AccessContextValue;
40
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/react/provider.tsx"],"names":[],"mappings":"AAEA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE/D,MAAM,WAAW,kBAAkB;IACjC,0CAA0C;IAC1C,OAAO,EAAE,aAAa,CAAC;IACvB,iEAAiE;IACjE,aAAa,EAAE,OAAO,CAAC;IACvB,+CAA+C;IAC/C,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAID,MAAM,WAAW,mBAAmB;IAClC,2FAA2F;IAC3F,KAAK,EAAE,YAAY,CAAC;IACpB,4EAA4E;IAC5E,cAAc,CAAC,EAAE,aAAa,CAAC;IAC/B,iEAAiE;IACjE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,mEAAmE;IACnE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,sFAAsF;IACtF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;CAC3B;AAiBD,wBAAgB,cAAc,CAAC,EAC7B,KAAK,EACL,cAAc,EACd,eAAuC,EACvC,UAAe,EACf,QAAQ,EACR,QAAQ,GACT,EAAE,mBAAmB,2CAqDrB;AAED,sFAAsF;AACtF,wBAAgB,gBAAgB,IAAI,kBAAkB,CAIrD"}
@@ -0,0 +1,84 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ /**
4
+ * AccessProvider — the client-side context that holds a FRESH Access session
5
+ * snapshot for the current operator + scope. It fetches the snapshot from the
6
+ * product's SAME-ORIGIN BFF seam (default `/api/access/session`), never the
7
+ * Control Plane directly — the browser holds no operator token and the Control
8
+ * Plane URL is server-only.
9
+ *
10
+ * NO long-lived cache (control-plane-doctrine §4): the snapshot is refetched on
11
+ * mount, on window focus / tab visibility, on a short TTL, and whenever the
12
+ * caller-supplied `routeKey` changes (pass `usePathname()` for route-change
13
+ * revalidation without coupling this SDK to any router). Fail-closed: a failed
14
+ * fetch yields an empty session (no identity, no grants).
15
+ */
16
+ import * as React from 'react';
17
+ const AccessContext = React.createContext(null);
18
+ function emptySession(scope, ttlSeconds) {
19
+ return { identity: null, scope, roles: [], grants: [], ttlSeconds };
20
+ }
21
+ function normalize(raw, scope, ttlSeconds) {
22
+ const s = (raw ?? {});
23
+ return {
24
+ identity: s.identity ?? null,
25
+ scope: s.scope ?? scope,
26
+ roles: Array.isArray(s.roles) ? s.roles : [],
27
+ grants: Array.isArray(s.grants) ? s.grants : [],
28
+ ttlSeconds: typeof s.ttlSeconds === 'number' ? s.ttlSeconds : ttlSeconds,
29
+ };
30
+ }
31
+ export function AccessProvider({ scope, initialSession, sessionEndpoint = '/api/access/session', ttlSeconds = 30, routeKey, children, }) {
32
+ const [session, setSession] = React.useState(() => initialSession ?? emptySession(scope, ttlSeconds));
33
+ const refresh = React.useCallback(async () => {
34
+ try {
35
+ const res = await fetch(sessionEndpoint, { cache: 'no-store', credentials: 'same-origin' });
36
+ if (!res.ok) {
37
+ setSession(emptySession(scope, ttlSeconds));
38
+ return;
39
+ }
40
+ const body = (await res.json());
41
+ setSession(normalize(body, scope, ttlSeconds));
42
+ }
43
+ catch {
44
+ // Fail-closed: an unreachable BFF yields no grants.
45
+ setSession(emptySession(scope, ttlSeconds));
46
+ }
47
+ }, [sessionEndpoint, scope, ttlSeconds]);
48
+ // Refetch on mount and whenever the route changes.
49
+ React.useEffect(() => {
50
+ void refresh();
51
+ }, [refresh, routeKey]);
52
+ // Refetch on window focus / tab becoming visible.
53
+ React.useEffect(() => {
54
+ if (typeof window === 'undefined')
55
+ return;
56
+ const onFocus = () => void refresh();
57
+ const onVisible = () => {
58
+ if (document.visibilityState === 'visible')
59
+ void refresh();
60
+ };
61
+ window.addEventListener('focus', onFocus);
62
+ document.addEventListener('visibilitychange', onVisible);
63
+ return () => {
64
+ window.removeEventListener('focus', onFocus);
65
+ document.removeEventListener('visibilitychange', onVisible);
66
+ };
67
+ }, [refresh]);
68
+ // Short-TTL background revalidation (no long-lived cache).
69
+ React.useEffect(() => {
70
+ const ttl = session.ttlSeconds > 0 ? session.ttlSeconds : ttlSeconds;
71
+ const id = setInterval(() => void refresh(), Math.max(5, ttl) * 1000);
72
+ return () => clearInterval(id);
73
+ }, [refresh, session.ttlSeconds, ttlSeconds]);
74
+ const value = React.useMemo(() => ({ session, authenticated: !!session.identity, refresh }), [session, refresh]);
75
+ return _jsx(AccessContext.Provider, { value: value, children: children });
76
+ }
77
+ /** Internal: read the Access context (throws when used outside an AccessProvider). */
78
+ export function useAccessContext() {
79
+ const ctx = React.useContext(AccessContext);
80
+ if (!ctx)
81
+ throw new Error('useAccess* must be used within an <AccessProvider>');
82
+ return ctx;
83
+ }
84
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {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,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IAChF,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `@consciousclouds/access/server` — the request-bound BFF adapter. It reads the
3
+ * operator token from the request's httpOnly cookie (name configurable) and
4
+ * calls the Control Plane server-side, so the Control Plane URL and the operator
5
+ * token never reach the browser.
6
+ *
7
+ * FAIL-CLOSED by construction — this is the load-bearing enforcement seam
8
+ * (control-plane-doctrine §4): any deny, unreachable Control Plane, or thrown
9
+ * error resolves to `denied` / an empty session. A failure can never widen
10
+ * access. Carries NO policy: it forwards the operator's identity to the Control
11
+ * Plane, which decides.
12
+ */
13
+ import type { AccessDecision, AccessIntent, AccessSession, Grant, OperatorIdentity, ProjectScope } from '../types.js';
14
+ /** The minimum request shape the adapter needs — satisfied by a Fetch `Request`
15
+ * or `{ headers: <Next headers()> }`. */
16
+ export interface RequestLike {
17
+ headers: {
18
+ get(name: string): string | null;
19
+ };
20
+ }
21
+ /** Configuration for the request-bound adapter. */
22
+ export interface ServerAccessConfig {
23
+ /** Control Plane base URL — SERVER-ONLY (never `NEXT_PUBLIC_`). */
24
+ baseUrl: string;
25
+ /** The httpOnly cookie carrying the operator token (e.g. `ccu_operator`). */
26
+ cookieName: string;
27
+ /** The default project scope for this surface (single-project surfaces set it once). */
28
+ scope?: ProjectScope;
29
+ /** The capability candidates whose granted subset seeds `AccessSession.grants`
30
+ * (the set this surface gates its nav on). Probed via the Control Plane — no policy here. */
31
+ capabilities?: readonly Grant[];
32
+ /** Optional fetch implementation. */
33
+ fetchImpl?: typeof fetch;
34
+ /** Freshness window the assembled AccessSession advertises. */
35
+ ttlSeconds?: number;
36
+ }
37
+ /** The request-bound adapter surface. */
38
+ export interface ServerAccess {
39
+ /** Who is the current operator? (decoded from the cookie for display; null when absent). */
40
+ identity(req: RequestLike): OperatorIdentity | null;
41
+ /** What project scope is this surface acting in? */
42
+ scope(req?: RequestLike): ProjectScope;
43
+ /** What permissions does the operator have here? (fail-closed empty session on any failure). */
44
+ session(req: RequestLike, scope?: ProjectScope): Promise<AccessSession>;
45
+ /** Can this action be performed? (uncached, fail-closed — deny/unreachable/throw ⇒ denied). */
46
+ can(req: RequestLike, scope: ProjectScope, action: Grant, intent?: AccessIntent): Promise<AccessDecision>;
47
+ }
48
+ /** Create the request-bound BFF adapter. */
49
+ export declare function createAccess(config: ServerAccessConfig): ServerAccess;
50
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAOH,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,aAAa,EACb,KAAK,EACL,gBAAgB,EAChB,YAAY,EACb,MAAM,aAAa,CAAC;AAErB;yCACyC;AACzC,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE;QAAE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;CAC/C;AAED,mDAAmD;AACnD,MAAM,WAAW,kBAAkB;IACjC,mEAAmE;IACnE,OAAO,EAAE,MAAM,CAAC;IAChB,6EAA6E;IAC7E,UAAU,EAAE,MAAM,CAAC;IACnB,wFAAwF;IACxF,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB;iGAC6F;IAC7F,YAAY,CAAC,EAAE,SAAS,KAAK,EAAE,CAAC;IAChC,qCAAqC;IACrC,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IACzB,+DAA+D;IAC/D,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,yCAAyC;AACzC,MAAM,WAAW,YAAY;IAC3B,4FAA4F;IAC5F,QAAQ,CAAC,GAAG,EAAE,WAAW,GAAG,gBAAgB,GAAG,IAAI,CAAC;IACpD,oDAAoD;IACpD,KAAK,CAAC,GAAG,CAAC,EAAE,WAAW,GAAG,YAAY,CAAC;IACvC,gGAAgG;IAChG,OAAO,CAAC,GAAG,EAAE,WAAW,EAAE,KAAK,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IACxE,+FAA+F;IAC/F,GAAG,CAAC,GAAG,EAAE,WAAW,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;CAC3G;AAeD,4CAA4C;AAC5C,wBAAgB,YAAY,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAwDrE"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * `@consciousclouds/access/server` — the request-bound BFF adapter. It reads the
3
+ * operator token from the request's httpOnly cookie (name configurable) and
4
+ * calls the Control Plane server-side, so the Control Plane URL and the operator
5
+ * token never reach the browser.
6
+ *
7
+ * FAIL-CLOSED by construction — this is the load-bearing enforcement seam
8
+ * (control-plane-doctrine §4): any deny, unreachable Control Plane, or thrown
9
+ * error resolves to `denied` / an empty session. A failure can never widen
10
+ * access. Carries NO policy: it forwards the operator's identity to the Control
11
+ * Plane, which decides.
12
+ */
13
+ import { createAccessClient, identityFromToken } from '../client/index.js';
14
+ const EMPTY_SCOPE = { project: '', environment: '' };
15
+ /** Pull one cookie value out of a raw `Cookie:` header. */
16
+ function readCookie(header, name) {
17
+ if (!header)
18
+ return null;
19
+ for (const part of header.split(';')) {
20
+ const eq = part.indexOf('=');
21
+ if (eq < 0)
22
+ continue;
23
+ if (part.slice(0, eq).trim() === name)
24
+ return decodeURIComponent(part.slice(eq + 1).trim());
25
+ }
26
+ return null;
27
+ }
28
+ /** Create the request-bound BFF adapter. */
29
+ export function createAccess(config) {
30
+ const clientConfig = {
31
+ baseUrl: config.baseUrl,
32
+ fetchImpl: config.fetchImpl,
33
+ ttlSeconds: config.ttlSeconds,
34
+ };
35
+ const client = createAccessClient(clientConfig);
36
+ const candidates = config.capabilities ?? [];
37
+ const tokenOf = (req) => readCookie(req.headers.get('cookie'), config.cookieName);
38
+ const scopeOf = (explicit) => explicit ?? config.scope ?? EMPTY_SCOPE;
39
+ function identity(req) {
40
+ return identityFromToken(tokenOf(req));
41
+ }
42
+ function scope(_req) {
43
+ return scopeOf();
44
+ }
45
+ async function session(req, explicit) {
46
+ const scoped = scopeOf(explicit);
47
+ const token = tokenOf(req);
48
+ if (!token)
49
+ return { identity: null, scope: scoped, roles: [], grants: [], ttlSeconds: config.ttlSeconds ?? 30 };
50
+ try {
51
+ return await client.session(token, scoped, candidates);
52
+ }
53
+ catch {
54
+ // Fail-closed: an unreachable/erroring Control Plane yields no grants.
55
+ return {
56
+ identity: identityFromToken(token),
57
+ scope: scoped,
58
+ roles: [],
59
+ grants: [],
60
+ ttlSeconds: config.ttlSeconds ?? 30,
61
+ };
62
+ }
63
+ }
64
+ async function can(req, explicit, action, intent = 'mutate') {
65
+ const token = tokenOf(req);
66
+ if (!token)
67
+ return 'denied';
68
+ try {
69
+ return await client.can(token, scopeOf(explicit), action, intent);
70
+ }
71
+ catch {
72
+ return 'denied';
73
+ }
74
+ }
75
+ return { identity, scope, session, can };
76
+ }
77
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAiD3E,MAAM,WAAW,GAAiB,EAAE,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC;AAEnE,2DAA2D;AAC3D,SAAS,UAAU,CAAC,MAAqB,EAAE,IAAY;IACrD,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACrC,MAAM,EAAE,GAAG,IAAI,CAAC,OA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C;QAC3B,IAAI,CAAC,KAAK;YAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;QACjH,IAAI,CAAC;YACH,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;QACzD,CAAC;QAAC,MAAM,CAAC;YACP,uEAAuE;YACvE,OAAO;gBACL,QAAQ,EAAE,iBAAiB,CAAC,KAAK,CAAC;gBAClC,KAAK,EAAE,MAAM;gBACb,KAAK,EAAE,EAAE;gBACT,MAAM,EAAE,EAAE;gBACV,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,EAAE;aACpC,CAAC;QACJ,CAAC;IACH,CAAC;IAED,KAAK,UAAU,GAAG,CAChB,GAAgB,EAChB,QAAsB,EACtB,MAAa,EACb,SAAuB,QAAQ;QAE/B,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,KAAK;YAAE,OAAO,QAAQ,CAAC;QAC5B,IAAI,CAAC;YACH,OAAO,MAAM,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QACpE,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,QAAQ,CAAC;QAClB,CAAC;IACH,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;AAC3C,CAAC"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The Access vocabulary — TYPES ONLY. No React, no `fetch`, no policy. This is
3
+ * the root export (`@consciousclouds/access`); everything here is inert data
4
+ * shapes that both the browser and the server share.
5
+ *
6
+ * The five operating questions the Control Plane answers (control-plane-doctrine
7
+ * §5) map onto these types:
8
+ * - Who is the current operator? → OperatorIdentity
9
+ * - What project is being entered? → ProjectScope
10
+ * - What permissions does the operator have here? → AccessSession.roles / .grants
11
+ * - Can this action be performed? → AccessDecision (from `can`)
12
+ * - What capabilities are granted? → AccessSession.grants (Grant[])
13
+ */
14
+ import type { Capability } from '@consciousclouds/capability-sdk';
15
+ /**
16
+ * The authenticated operator, decoded from the operator JWT for DISPLAY (never
17
+ * verified here — the gateway does the real signature/iss/aud verification).
18
+ * `iss`/`aud` are the operator plane's fixed identity (`ccu-admin.identity` /
19
+ * `ccu-admin.app`); `exp` is seconds since epoch when present.
20
+ */
21
+ export interface OperatorIdentity {
22
+ sub: string;
23
+ email: string;
24
+ displayName?: string;
25
+ iss: string;
26
+ aud: string;
27
+ exp?: number;
28
+ }
29
+ /**
30
+ * The project + environment an operator is acting in. The Control Plane keys
31
+ * Access decisions on the project slug; the environment travels with it (env =
32
+ * a Neon branch, per the parity toolchain).
33
+ */
34
+ export interface ProjectScope {
35
+ project: string;
36
+ environment: string;
37
+ }
38
+ /**
39
+ * A single granted capability — REUSES the platform `Capability` vocabulary
40
+ * (`<primitive>.<verb>`, e.g. `factory.observe`, `assistant.turn`). There is
41
+ * exactly ONE permission vocabulary; this SDK invents no second one.
42
+ */
43
+ export type Grant = Capability;
44
+ /**
45
+ * The three outcomes a permission check can produce. This union is IDENTICAL to
46
+ * `@consciousclouds/operator-shell`'s `PermissionDecision` (allowed | denied |
47
+ * unknown) — a resolver returning `AccessDecision` is assignable wherever the
48
+ * shell wants a `PermissionResolver`. `unknown` ⇒ denied (fail-closed): a value
49
+ * the resolver could not resolve to `allowed` never widens access.
50
+ */
51
+ export type AccessDecision = 'allowed' | 'denied' | 'unknown';
52
+ /**
53
+ * The intent of an authorization check. It gates exactly one boundary in the
54
+ * Control Plane — the read-only cross-grant gate (a `read_only` assignment
55
+ * attempting a `mutate` is denied). Admin reads are `read`; a turn is `mutate`.
56
+ */
57
+ export type AccessIntent = 'read' | 'mutate';
58
+ /**
59
+ * The operator's answer to "what permissions do I have here?" for one project
60
+ * scope, as the SDK assembles it from the Control Plane:
61
+ * - `roles` — the role keys the operator holds at this scope (from
62
+ * `GET /access/session`, whose grants are ROLE assignments).
63
+ * - `grants` — the resolved `<primitive>.<verb>` capabilities the operator is
64
+ * actually allowed here. The Control Plane's `/access/session`
65
+ * returns roles, not resolved capabilities, so the granted subset
66
+ * is resolved by asking the Control Plane's authorize decision for
67
+ * a candidate capability set (policy-free aggregation — the
68
+ * Control Plane decides each one).
69
+ * - `ttlSeconds` — how long a consumer may treat this snapshot as fresh before
70
+ * revalidating. Short by design; the SDK holds no long-lived cache.
71
+ * Fail-closed: an invalid/expired/logged-out session yields empty `roles` +
72
+ * `grants` (nothing to gate `allowed`).
73
+ */
74
+ export interface AccessSession {
75
+ identity: OperatorIdentity | null;
76
+ scope: ProjectScope;
77
+ roles: string[];
78
+ grants: Grant[];
79
+ ttlSeconds: number;
80
+ }
81
+ /**
82
+ * A resolver from a permission REFERENCE → a decision (sync or async),
83
+ * structurally identical to `@consciousclouds/operator-shell`'s
84
+ * `PermissionResolver`. Declared here so the SDK need not depend on the shell.
85
+ */
86
+ export type PermissionResolver = (permission: string) => AccessDecision | Promise<AccessDecision>;
87
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAElE;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,MAAM,MAAM,KAAK,GAAG,UAAU,CAAC;AAE/B;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,QAAQ,GAAG,SAAS,CAAC;AAE9D;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,QAAQ,CAAC;AAE7C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAClC,KAAK,EAAE,YAAY,CAAC;IACpB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAC/B,UAAU,EAAE,MAAM,KACf,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The Access vocabulary — TYPES ONLY. No React, no `fetch`, no policy. This is
3
+ * the root export (`@consciousclouds/access`); everything here is inert data
4
+ * shapes that both the browser and the server share.
5
+ *
6
+ * The five operating questions the Control Plane answers (control-plane-doctrine
7
+ * §5) map onto these types:
8
+ * - Who is the current operator? → OperatorIdentity
9
+ * - What project is being entered? → ProjectScope
10
+ * - What permissions does the operator have here? → AccessSession.roles / .grants
11
+ * - Can this action be performed? → AccessDecision (from `can`)
12
+ * - What capabilities are granted? → AccessSession.grants (Grant[])
13
+ */
14
+ export {};
15
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG"}
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@consciousclouds/access",
3
+ "version": "0.1.0",
4
+ "description": "Conscious Clouds Access SDK — the thin, policy-free client for the Control Plane's operator identity + Access surface. Types (root) + isomorphic HTTP wrappers (/client) + a request-bound fail-closed BFF adapter (/server) + React hooks & AccessProvider (/react). Reuses the `Capability` `<primitive>.<verb>` vocabulary and the operator-shell's allowed|denied|unknown decision union. NO policy logic — every decision is the Control Plane's; the SDK only asks the five operating questions and enforces the answers (fail-closed).",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./client": {
15
+ "types": "./dist/client/index.d.ts",
16
+ "import": "./dist/client/index.js"
17
+ },
18
+ "./server": {
19
+ "types": "./dist/server/index.d.ts",
20
+ "import": "./dist/server/index.js"
21
+ },
22
+ "./react": {
23
+ "types": "./dist/react/index.d.ts",
24
+ "import": "./dist/react/index.js"
25
+ }
26
+ },
27
+ "files": ["dist", "README.md", "CHANGELOG.md", "LICENSE"],
28
+ "scripts": {
29
+ "build": "tsc -p tsconfig.build.json",
30
+ "clean": "rm -rf dist",
31
+ "type-check": "tsc --noEmit",
32
+ "test": "bun test",
33
+ "prepublishOnly": "bun run clean && bun run build && bun run type-check"
34
+ },
35
+ "dependencies": {
36
+ "@consciousclouds/capability-sdk": "^0.1.0"
37
+ },
38
+ "peerDependencies": {
39
+ "react": ">=18.0.0"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "react": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^22.10.5",
48
+ "@types/react": "^19.2.7",
49
+ "react": "^19.2.3",
50
+ "typescript": "^5.7.2"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "engines": {
56
+ "bun": ">=1.0.0",
57
+ "node": ">=18.0.0"
58
+ }
59
+ }