@authyon/auth 0.1.5 → 0.2.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +301 -158
- package/dist/ability-CVplsuzO.d.cts +615 -0
- package/dist/ability-CVplsuzO.d.ts +615 -0
- package/dist/chunk-OKPSF4LZ.js +303 -0
- package/dist/index.cjs +727 -60
- package/dist/index.d.cts +57 -466
- package/dist/index.d.ts +57 -466
- package/dist/index.js +429 -58
- package/dist/react/index.cjs +406 -0
- package/dist/react/index.d.cts +38 -0
- package/dist/react/index.d.ts +38 -0
- package/dist/react/index.js +106 -0
- package/package.json +71 -37
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
"use client";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/react/index.tsx
|
|
22
|
+
var react_exports = {};
|
|
23
|
+
__export(react_exports, {
|
|
24
|
+
AuthyonProvider: () => AuthyonProvider,
|
|
25
|
+
AuthyonSessionController: () => AuthyonSessionController,
|
|
26
|
+
PermissionGuard: () => PermissionGuard,
|
|
27
|
+
SessionGuard: () => SessionGuard,
|
|
28
|
+
useAuthyon: () => useAuthyon,
|
|
29
|
+
useAuthyonAbility: () => useAuthyonAbility,
|
|
30
|
+
useCan: () => useCan
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(react_exports);
|
|
33
|
+
var import_react = require("react");
|
|
34
|
+
|
|
35
|
+
// ../../internal/core/authorization/ability.ts
|
|
36
|
+
var AuthyonAbility = class {
|
|
37
|
+
constructor(rules = [], detectSubjectType = defaultSubjectType) {
|
|
38
|
+
this.detectSubjectType = detectSubjectType;
|
|
39
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
40
|
+
this.currentRules = rules.map(cloneRule);
|
|
41
|
+
}
|
|
42
|
+
get rules() {
|
|
43
|
+
return this.currentRules;
|
|
44
|
+
}
|
|
45
|
+
can(action, subject, field) {
|
|
46
|
+
const subjectType = typeof subject === "string" ? subject : this.detectSubjectType(subject);
|
|
47
|
+
for (let index = this.currentRules.length - 1; index >= 0; index -= 1) {
|
|
48
|
+
const rule = this.currentRules[index];
|
|
49
|
+
if (!matchesToken(rule.action, action, "manage")) continue;
|
|
50
|
+
if (!matchesToken(rule.subject, subjectType, "all")) continue;
|
|
51
|
+
if (field && rule.fields && !rule.fields.some((value) => matchesField(value, field)))
|
|
52
|
+
continue;
|
|
53
|
+
if (rule.conditions) {
|
|
54
|
+
if (typeof subject === "string" || !matchesConditions(subject, rule.conditions)) continue;
|
|
55
|
+
}
|
|
56
|
+
return !rule.inverted;
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
cannot(action, subject, field) {
|
|
61
|
+
return !this.can(action, subject, field);
|
|
62
|
+
}
|
|
63
|
+
rulesFor(action, subject) {
|
|
64
|
+
return this.currentRules.filter(
|
|
65
|
+
(rule) => matchesToken(rule.action, action, "manage") && matchesToken(rule.subject, subject, "all")
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
update(rules) {
|
|
69
|
+
this.currentRules = rules.map(cloneRule);
|
|
70
|
+
for (const listener of this.listeners) listener(this.rules);
|
|
71
|
+
}
|
|
72
|
+
on(event, listener) {
|
|
73
|
+
if (event !== "updated") return () => void 0;
|
|
74
|
+
this.listeners.add(listener);
|
|
75
|
+
return () => this.listeners.delete(listener);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
function createAuthyonAbility(source = {}, options = {}) {
|
|
79
|
+
return new AuthyonAbility(createAuthyonRules(source, options), options.detectSubjectType);
|
|
80
|
+
}
|
|
81
|
+
function createAuthyonRules(source = {}, options = {}) {
|
|
82
|
+
const permissions = /* @__PURE__ */ new Set([
|
|
83
|
+
...source.permissions ?? [],
|
|
84
|
+
...source.scope?.split(/\s+/).filter(Boolean) ?? []
|
|
85
|
+
]);
|
|
86
|
+
const rules = [...permissions].map(permissionToRule).filter(isAbilityRule);
|
|
87
|
+
for (const role of /* @__PURE__ */ new Set([...source.roles ?? [], ...options.roles ?? []])) {
|
|
88
|
+
rules.push(...(options.roleRules?.[role] ?? []).map(cloneRule));
|
|
89
|
+
}
|
|
90
|
+
rules.push(...(options.rules ?? []).map(cloneRule));
|
|
91
|
+
return rules;
|
|
92
|
+
}
|
|
93
|
+
function permissionToRule(permission) {
|
|
94
|
+
const normalized = permission.trim();
|
|
95
|
+
if (!normalized) return null;
|
|
96
|
+
if (normalized === "*" || normalized === "*:*" || normalized === "all:manage") {
|
|
97
|
+
return { action: "manage", subject: "all" };
|
|
98
|
+
}
|
|
99
|
+
const separator = normalized.lastIndexOf(":");
|
|
100
|
+
if (separator <= 0 || separator === normalized.length - 1) return null;
|
|
101
|
+
const subject = normalized.slice(0, separator);
|
|
102
|
+
const action = normalized.slice(separator + 1);
|
|
103
|
+
return {
|
|
104
|
+
action: action === "*" ? "manage" : action,
|
|
105
|
+
subject: subject === "*" ? "all" : subject
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function matchesToken(value, expected, wildcard) {
|
|
109
|
+
return (Array.isArray(value) ? value : [value]).some(
|
|
110
|
+
(candidate) => candidate === expected || candidate === wildcard || candidate === "*"
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
function matchesField(pattern, field) {
|
|
114
|
+
if (pattern === "*" || pattern === field) return true;
|
|
115
|
+
return pattern.endsWith(".*") && field.startsWith(pattern.slice(0, -1));
|
|
116
|
+
}
|
|
117
|
+
function matchesConditions(subject, conditions) {
|
|
118
|
+
return Object.entries(conditions).every(([path, expected]) => {
|
|
119
|
+
if (path === "$and" && Array.isArray(expected)) {
|
|
120
|
+
return expected.every(
|
|
121
|
+
(condition) => matchesConditions(subject, condition)
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
if (path === "$or" && Array.isArray(expected)) {
|
|
125
|
+
return expected.some(
|
|
126
|
+
(condition) => matchesConditions(subject, condition)
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
return matchesValue(readPath(subject, path), expected);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
function matchesValue(actual, expected) {
|
|
133
|
+
if (!isRecord(expected) || !Object.keys(expected).some((key) => key.startsWith("$"))) {
|
|
134
|
+
return isRecord(expected) && isRecord(actual) ? matchesConditions(actual, expected) : Object.is(actual, expected);
|
|
135
|
+
}
|
|
136
|
+
return Object.entries(expected).every(([operator, operand]) => {
|
|
137
|
+
switch (operator) {
|
|
138
|
+
case "$eq":
|
|
139
|
+
return Object.is(actual, operand);
|
|
140
|
+
case "$ne":
|
|
141
|
+
return !Object.is(actual, operand);
|
|
142
|
+
case "$in":
|
|
143
|
+
return Array.isArray(operand) && operand.some((value) => Object.is(actual, value));
|
|
144
|
+
case "$nin":
|
|
145
|
+
return Array.isArray(operand) && !operand.some((value) => Object.is(actual, value));
|
|
146
|
+
case "$gt":
|
|
147
|
+
return typeof actual === "number" && typeof operand === "number" && actual > operand;
|
|
148
|
+
case "$gte":
|
|
149
|
+
return typeof actual === "number" && typeof operand === "number" && actual >= operand;
|
|
150
|
+
case "$lt":
|
|
151
|
+
return typeof actual === "number" && typeof operand === "number" && actual < operand;
|
|
152
|
+
case "$lte":
|
|
153
|
+
return typeof actual === "number" && typeof operand === "number" && actual <= operand;
|
|
154
|
+
case "$exists":
|
|
155
|
+
return operand ? actual !== void 0 : actual === void 0;
|
|
156
|
+
default:
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
function readPath(value, path) {
|
|
162
|
+
return path.split(".").reduce((current, part) => isRecord(current) ? current[part] : void 0, value);
|
|
163
|
+
}
|
|
164
|
+
function defaultSubjectType(subject) {
|
|
165
|
+
const explicit = subject.__type ?? subject.type ?? subject.kind;
|
|
166
|
+
if (typeof explicit === "string") return explicit;
|
|
167
|
+
const constructorName = subject.constructor?.name;
|
|
168
|
+
return typeof constructorName === "string" ? constructorName : "Object";
|
|
169
|
+
}
|
|
170
|
+
function cloneRule(rule) {
|
|
171
|
+
return {
|
|
172
|
+
...rule,
|
|
173
|
+
action: Array.isArray(rule.action) ? [...rule.action] : rule.action,
|
|
174
|
+
subject: Array.isArray(rule.subject) ? [...rule.subject] : rule.subject,
|
|
175
|
+
fields: rule.fields ? [...rule.fields] : void 0
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function isRecord(value) {
|
|
179
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
180
|
+
}
|
|
181
|
+
function isAbilityRule(value) {
|
|
182
|
+
return value !== null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// src/session/sessionController.ts
|
|
186
|
+
var SERVER_SNAPSHOT = {
|
|
187
|
+
status: "unauthenticated",
|
|
188
|
+
session: null,
|
|
189
|
+
user: null,
|
|
190
|
+
error: null
|
|
191
|
+
};
|
|
192
|
+
var AuthyonSessionController = class {
|
|
193
|
+
constructor(client, options = {}) {
|
|
194
|
+
this.client = client;
|
|
195
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
196
|
+
this.getSnapshot = () => this.snapshot;
|
|
197
|
+
this.getServerSnapshot = () => SERVER_SNAPSHOT;
|
|
198
|
+
this.subscribe = (listener) => {
|
|
199
|
+
this.listeners.add(listener);
|
|
200
|
+
return () => this.listeners.delete(listener);
|
|
201
|
+
};
|
|
202
|
+
this.refreshAheadMs = options.refreshAheadMs ?? 3e4;
|
|
203
|
+
if (!Number.isFinite(this.refreshAheadMs) || this.refreshAheadMs < 0) {
|
|
204
|
+
throw new Error("Authyon: `refreshAheadMs` must be a non-negative finite number");
|
|
205
|
+
}
|
|
206
|
+
const session = client.getSession();
|
|
207
|
+
this.snapshot = {
|
|
208
|
+
status: session ? "validating" : "unauthenticated",
|
|
209
|
+
session,
|
|
210
|
+
user: session?.user ?? null,
|
|
211
|
+
error: null
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
start() {
|
|
215
|
+
if (!this.unsubscribeAuth) {
|
|
216
|
+
this.unsubscribeAuth = this.client.onAuthStateChange((event) => {
|
|
217
|
+
if (event.type === "signed_out") {
|
|
218
|
+
this.cancelRefresh();
|
|
219
|
+
this.setSnapshot({
|
|
220
|
+
status: "unauthenticated",
|
|
221
|
+
session: null,
|
|
222
|
+
user: null,
|
|
223
|
+
error: null
|
|
224
|
+
});
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (event.type === "session_validated") {
|
|
228
|
+
this.acceptSession(event.session);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
this.setSnapshot({
|
|
232
|
+
status: "validating",
|
|
233
|
+
session: event.session,
|
|
234
|
+
user: event.session.user ?? null,
|
|
235
|
+
error: null
|
|
236
|
+
});
|
|
237
|
+
void this.validate();
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
void this.validate();
|
|
241
|
+
return () => this.stop();
|
|
242
|
+
}
|
|
243
|
+
stop() {
|
|
244
|
+
this.unsubscribeAuth?.();
|
|
245
|
+
this.unsubscribeAuth = void 0;
|
|
246
|
+
this.cancelRefresh();
|
|
247
|
+
}
|
|
248
|
+
validate() {
|
|
249
|
+
if (this.validation) return this.validation;
|
|
250
|
+
const localSession = this.client.getSession();
|
|
251
|
+
if (!localSession) {
|
|
252
|
+
this.setSnapshot({
|
|
253
|
+
status: "unauthenticated",
|
|
254
|
+
session: null,
|
|
255
|
+
user: null,
|
|
256
|
+
error: null
|
|
257
|
+
});
|
|
258
|
+
return Promise.resolve(this.snapshot);
|
|
259
|
+
}
|
|
260
|
+
this.setSnapshot({ ...this.snapshot, status: "validating", error: null });
|
|
261
|
+
this.validation = this.client.validateSession().then((session) => {
|
|
262
|
+
if (session) this.acceptSession(session);
|
|
263
|
+
else {
|
|
264
|
+
this.setSnapshot({
|
|
265
|
+
status: "unauthenticated",
|
|
266
|
+
session: null,
|
|
267
|
+
user: null,
|
|
268
|
+
error: null
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
return this.snapshot;
|
|
272
|
+
}).catch((error) => {
|
|
273
|
+
this.setSnapshot({ ...this.snapshot, status: "error", error });
|
|
274
|
+
return this.snapshot;
|
|
275
|
+
}).finally(() => {
|
|
276
|
+
this.validation = void 0;
|
|
277
|
+
});
|
|
278
|
+
return this.validation;
|
|
279
|
+
}
|
|
280
|
+
async refreshNow() {
|
|
281
|
+
if (!this.client.getSession()) return this.validate();
|
|
282
|
+
try {
|
|
283
|
+
await this.client.refresh();
|
|
284
|
+
} catch (error) {
|
|
285
|
+
if (!this.client.getSession()) return this.validate();
|
|
286
|
+
this.setSnapshot({ ...this.snapshot, status: "error", error });
|
|
287
|
+
return this.snapshot;
|
|
288
|
+
}
|
|
289
|
+
return this.validate();
|
|
290
|
+
}
|
|
291
|
+
acceptSession(session) {
|
|
292
|
+
this.setSnapshot({
|
|
293
|
+
status: "authenticated",
|
|
294
|
+
session,
|
|
295
|
+
user: session.user ?? null,
|
|
296
|
+
error: null
|
|
297
|
+
});
|
|
298
|
+
this.scheduleRefresh(session);
|
|
299
|
+
}
|
|
300
|
+
scheduleRefresh(session) {
|
|
301
|
+
this.cancelRefresh();
|
|
302
|
+
const delay = Math.max(1e3, session.expiresAt - Date.now() - this.refreshAheadMs);
|
|
303
|
+
this.refreshTimer = setTimeout(() => void this.refreshNow(), delay);
|
|
304
|
+
}
|
|
305
|
+
cancelRefresh() {
|
|
306
|
+
if (this.refreshTimer !== void 0) clearTimeout(this.refreshTimer);
|
|
307
|
+
this.refreshTimer = void 0;
|
|
308
|
+
}
|
|
309
|
+
setSnapshot(snapshot) {
|
|
310
|
+
this.snapshot = snapshot;
|
|
311
|
+
for (const listener of this.listeners) listener();
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
// src/react/index.tsx
|
|
316
|
+
var AuthyonReactContext = (0, import_react.createContext)(null);
|
|
317
|
+
function AuthyonProvider({
|
|
318
|
+
client,
|
|
319
|
+
children,
|
|
320
|
+
refreshAheadMs,
|
|
321
|
+
validateOnFocus = true
|
|
322
|
+
}) {
|
|
323
|
+
const controllerRef = (0, import_react.useRef)(null);
|
|
324
|
+
if (!controllerRef.current || controllerRef.current.client !== client) {
|
|
325
|
+
controllerRef.current = new AuthyonSessionController(client, { refreshAheadMs });
|
|
326
|
+
}
|
|
327
|
+
const controller = controllerRef.current;
|
|
328
|
+
const snapshot = (0, import_react.useSyncExternalStore)(
|
|
329
|
+
controller.subscribe,
|
|
330
|
+
controller.getSnapshot,
|
|
331
|
+
controller.getServerSnapshot
|
|
332
|
+
);
|
|
333
|
+
(0, import_react.useEffect)(() => controller.start(), [controller]);
|
|
334
|
+
(0, import_react.useEffect)(() => {
|
|
335
|
+
if (!validateOnFocus) return;
|
|
336
|
+
const validateWhenVisible = () => {
|
|
337
|
+
if (document.visibilityState === "visible") void controller.validate();
|
|
338
|
+
};
|
|
339
|
+
document.addEventListener("visibilitychange", validateWhenVisible);
|
|
340
|
+
return () => document.removeEventListener("visibilitychange", validateWhenVisible);
|
|
341
|
+
}, [controller, validateOnFocus]);
|
|
342
|
+
const value = (0, import_react.useMemo)(
|
|
343
|
+
() => ({
|
|
344
|
+
...snapshot,
|
|
345
|
+
client,
|
|
346
|
+
validateSession: () => controller.validate(),
|
|
347
|
+
refreshSession: () => controller.refreshNow()
|
|
348
|
+
}),
|
|
349
|
+
[client, controller, snapshot]
|
|
350
|
+
);
|
|
351
|
+
return (0, import_react.createElement)(AuthyonReactContext.Provider, { value }, children);
|
|
352
|
+
}
|
|
353
|
+
function useAuthyon() {
|
|
354
|
+
const context = (0, import_react.useContext)(AuthyonReactContext);
|
|
355
|
+
if (!context) throw new Error("Authyon: `useAuthyon` must be used inside `AuthyonProvider`");
|
|
356
|
+
return context;
|
|
357
|
+
}
|
|
358
|
+
function useAuthyonAbility(options = {}) {
|
|
359
|
+
const { user } = useAuthyon();
|
|
360
|
+
return (0, import_react.useMemo)(() => createAuthyonAbility(user ?? {}, options), [user, options]);
|
|
361
|
+
}
|
|
362
|
+
function useCan(action, subject, field, options) {
|
|
363
|
+
const ability = useAuthyonAbility(options);
|
|
364
|
+
return ability.can(action, subject, field);
|
|
365
|
+
}
|
|
366
|
+
function SessionGuard({
|
|
367
|
+
children,
|
|
368
|
+
loadingFallback = null,
|
|
369
|
+
unauthenticatedFallback = null,
|
|
370
|
+
errorFallback = null,
|
|
371
|
+
onUnauthenticated
|
|
372
|
+
}) {
|
|
373
|
+
const { status } = useAuthyon();
|
|
374
|
+
(0, import_react.useEffect)(() => {
|
|
375
|
+
if (status === "unauthenticated") onUnauthenticated?.();
|
|
376
|
+
}, [onUnauthenticated, status]);
|
|
377
|
+
if (status === "validating") return loadingFallback;
|
|
378
|
+
if (status === "error") return errorFallback;
|
|
379
|
+
if (status !== "authenticated") return unauthenticatedFallback;
|
|
380
|
+
return children;
|
|
381
|
+
}
|
|
382
|
+
function PermissionGuard({
|
|
383
|
+
action,
|
|
384
|
+
subject,
|
|
385
|
+
field,
|
|
386
|
+
forbiddenFallback = null,
|
|
387
|
+
abilityOptions,
|
|
388
|
+
children,
|
|
389
|
+
...sessionProps
|
|
390
|
+
}) {
|
|
391
|
+
const allowed = useCan(action, subject, field, abilityOptions);
|
|
392
|
+
return (0, import_react.createElement)(SessionGuard, {
|
|
393
|
+
...sessionProps,
|
|
394
|
+
children: allowed ? children : forbiddenFallback
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
398
|
+
0 && (module.exports = {
|
|
399
|
+
AuthyonProvider,
|
|
400
|
+
AuthyonSessionController,
|
|
401
|
+
PermissionGuard,
|
|
402
|
+
SessionGuard,
|
|
403
|
+
useAuthyon,
|
|
404
|
+
useAuthyonAbility,
|
|
405
|
+
useCan
|
|
406
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { B as SessionControllerOptions, A as AuthyonClient, E as SessionSnapshot, f as AbilitySubject, n as AuthyonAbilityOptions, l as AuthyonAbility } from '../ability-CVplsuzO.cjs';
|
|
4
|
+
export { q as AuthyonSessionController, G as SessionSnapshotListener, J as SessionStatus } from '../ability-CVplsuzO.cjs';
|
|
5
|
+
|
|
6
|
+
interface AuthyonProviderProps extends SessionControllerOptions {
|
|
7
|
+
client: AuthyonClient;
|
|
8
|
+
children: ReactNode;
|
|
9
|
+
/** Revalidate with `/auth/me` when the tab becomes visible. Defaults to true. */
|
|
10
|
+
validateOnFocus?: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface AuthyonReactContextValue extends SessionSnapshot {
|
|
13
|
+
client: AuthyonClient;
|
|
14
|
+
validateSession(): Promise<SessionSnapshot>;
|
|
15
|
+
refreshSession(): Promise<SessionSnapshot>;
|
|
16
|
+
}
|
|
17
|
+
declare function AuthyonProvider({ client, children, refreshAheadMs, validateOnFocus, }: AuthyonProviderProps): react.FunctionComponentElement<react.ProviderProps<AuthyonReactContextValue | null>>;
|
|
18
|
+
declare function useAuthyon(): AuthyonReactContextValue;
|
|
19
|
+
declare function useAuthyonAbility(options?: AuthyonAbilityOptions): AuthyonAbility;
|
|
20
|
+
declare function useCan(action: string, subject: AbilitySubject, field?: string, options?: AuthyonAbilityOptions): boolean;
|
|
21
|
+
interface SessionGuardProps {
|
|
22
|
+
children: ReactNode;
|
|
23
|
+
loadingFallback?: ReactNode;
|
|
24
|
+
unauthenticatedFallback?: ReactNode;
|
|
25
|
+
errorFallback?: ReactNode;
|
|
26
|
+
onUnauthenticated?: () => void;
|
|
27
|
+
}
|
|
28
|
+
declare function SessionGuard({ children, loadingFallback, unauthenticatedFallback, errorFallback, onUnauthenticated, }: SessionGuardProps): ReactNode;
|
|
29
|
+
interface PermissionGuardProps extends SessionGuardProps {
|
|
30
|
+
action: string;
|
|
31
|
+
subject: AbilitySubject;
|
|
32
|
+
field?: string;
|
|
33
|
+
forbiddenFallback?: ReactNode;
|
|
34
|
+
abilityOptions?: AuthyonAbilityOptions;
|
|
35
|
+
}
|
|
36
|
+
declare function PermissionGuard({ action, subject, field, forbiddenFallback, abilityOptions, children, ...sessionProps }: PermissionGuardProps): react.FunctionComponentElement<SessionGuardProps>;
|
|
37
|
+
|
|
38
|
+
export { AuthyonProvider, type AuthyonProviderProps, PermissionGuard, type PermissionGuardProps, SessionControllerOptions, SessionGuard, type SessionGuardProps, SessionSnapshot, useAuthyon, useAuthyonAbility, useCan };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { B as SessionControllerOptions, A as AuthyonClient, E as SessionSnapshot, f as AbilitySubject, n as AuthyonAbilityOptions, l as AuthyonAbility } from '../ability-CVplsuzO.js';
|
|
4
|
+
export { q as AuthyonSessionController, G as SessionSnapshotListener, J as SessionStatus } from '../ability-CVplsuzO.js';
|
|
5
|
+
|
|
6
|
+
interface AuthyonProviderProps extends SessionControllerOptions {
|
|
7
|
+
client: AuthyonClient;
|
|
8
|
+
children: ReactNode;
|
|
9
|
+
/** Revalidate with `/auth/me` when the tab becomes visible. Defaults to true. */
|
|
10
|
+
validateOnFocus?: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface AuthyonReactContextValue extends SessionSnapshot {
|
|
13
|
+
client: AuthyonClient;
|
|
14
|
+
validateSession(): Promise<SessionSnapshot>;
|
|
15
|
+
refreshSession(): Promise<SessionSnapshot>;
|
|
16
|
+
}
|
|
17
|
+
declare function AuthyonProvider({ client, children, refreshAheadMs, validateOnFocus, }: AuthyonProviderProps): react.FunctionComponentElement<react.ProviderProps<AuthyonReactContextValue | null>>;
|
|
18
|
+
declare function useAuthyon(): AuthyonReactContextValue;
|
|
19
|
+
declare function useAuthyonAbility(options?: AuthyonAbilityOptions): AuthyonAbility;
|
|
20
|
+
declare function useCan(action: string, subject: AbilitySubject, field?: string, options?: AuthyonAbilityOptions): boolean;
|
|
21
|
+
interface SessionGuardProps {
|
|
22
|
+
children: ReactNode;
|
|
23
|
+
loadingFallback?: ReactNode;
|
|
24
|
+
unauthenticatedFallback?: ReactNode;
|
|
25
|
+
errorFallback?: ReactNode;
|
|
26
|
+
onUnauthenticated?: () => void;
|
|
27
|
+
}
|
|
28
|
+
declare function SessionGuard({ children, loadingFallback, unauthenticatedFallback, errorFallback, onUnauthenticated, }: SessionGuardProps): ReactNode;
|
|
29
|
+
interface PermissionGuardProps extends SessionGuardProps {
|
|
30
|
+
action: string;
|
|
31
|
+
subject: AbilitySubject;
|
|
32
|
+
field?: string;
|
|
33
|
+
forbiddenFallback?: ReactNode;
|
|
34
|
+
abilityOptions?: AuthyonAbilityOptions;
|
|
35
|
+
}
|
|
36
|
+
declare function PermissionGuard({ action, subject, field, forbiddenFallback, abilityOptions, children, ...sessionProps }: PermissionGuardProps): react.FunctionComponentElement<SessionGuardProps>;
|
|
37
|
+
|
|
38
|
+
export { AuthyonProvider, type AuthyonProviderProps, PermissionGuard, type PermissionGuardProps, SessionControllerOptions, SessionGuard, type SessionGuardProps, SessionSnapshot, useAuthyon, useAuthyonAbility, useCan };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import {
|
|
3
|
+
AuthyonSessionController,
|
|
4
|
+
createAuthyonAbility
|
|
5
|
+
} from "../chunk-OKPSF4LZ.js";
|
|
6
|
+
|
|
7
|
+
// src/react/index.tsx
|
|
8
|
+
import {
|
|
9
|
+
createContext,
|
|
10
|
+
createElement,
|
|
11
|
+
useContext,
|
|
12
|
+
useEffect,
|
|
13
|
+
useMemo,
|
|
14
|
+
useRef,
|
|
15
|
+
useSyncExternalStore
|
|
16
|
+
} from "react";
|
|
17
|
+
var AuthyonReactContext = createContext(null);
|
|
18
|
+
function AuthyonProvider({
|
|
19
|
+
client,
|
|
20
|
+
children,
|
|
21
|
+
refreshAheadMs,
|
|
22
|
+
validateOnFocus = true
|
|
23
|
+
}) {
|
|
24
|
+
const controllerRef = useRef(null);
|
|
25
|
+
if (!controllerRef.current || controllerRef.current.client !== client) {
|
|
26
|
+
controllerRef.current = new AuthyonSessionController(client, { refreshAheadMs });
|
|
27
|
+
}
|
|
28
|
+
const controller = controllerRef.current;
|
|
29
|
+
const snapshot = useSyncExternalStore(
|
|
30
|
+
controller.subscribe,
|
|
31
|
+
controller.getSnapshot,
|
|
32
|
+
controller.getServerSnapshot
|
|
33
|
+
);
|
|
34
|
+
useEffect(() => controller.start(), [controller]);
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
if (!validateOnFocus) return;
|
|
37
|
+
const validateWhenVisible = () => {
|
|
38
|
+
if (document.visibilityState === "visible") void controller.validate();
|
|
39
|
+
};
|
|
40
|
+
document.addEventListener("visibilitychange", validateWhenVisible);
|
|
41
|
+
return () => document.removeEventListener("visibilitychange", validateWhenVisible);
|
|
42
|
+
}, [controller, validateOnFocus]);
|
|
43
|
+
const value = useMemo(
|
|
44
|
+
() => ({
|
|
45
|
+
...snapshot,
|
|
46
|
+
client,
|
|
47
|
+
validateSession: () => controller.validate(),
|
|
48
|
+
refreshSession: () => controller.refreshNow()
|
|
49
|
+
}),
|
|
50
|
+
[client, controller, snapshot]
|
|
51
|
+
);
|
|
52
|
+
return createElement(AuthyonReactContext.Provider, { value }, children);
|
|
53
|
+
}
|
|
54
|
+
function useAuthyon() {
|
|
55
|
+
const context = useContext(AuthyonReactContext);
|
|
56
|
+
if (!context) throw new Error("Authyon: `useAuthyon` must be used inside `AuthyonProvider`");
|
|
57
|
+
return context;
|
|
58
|
+
}
|
|
59
|
+
function useAuthyonAbility(options = {}) {
|
|
60
|
+
const { user } = useAuthyon();
|
|
61
|
+
return useMemo(() => createAuthyonAbility(user ?? {}, options), [user, options]);
|
|
62
|
+
}
|
|
63
|
+
function useCan(action, subject, field, options) {
|
|
64
|
+
const ability = useAuthyonAbility(options);
|
|
65
|
+
return ability.can(action, subject, field);
|
|
66
|
+
}
|
|
67
|
+
function SessionGuard({
|
|
68
|
+
children,
|
|
69
|
+
loadingFallback = null,
|
|
70
|
+
unauthenticatedFallback = null,
|
|
71
|
+
errorFallback = null,
|
|
72
|
+
onUnauthenticated
|
|
73
|
+
}) {
|
|
74
|
+
const { status } = useAuthyon();
|
|
75
|
+
useEffect(() => {
|
|
76
|
+
if (status === "unauthenticated") onUnauthenticated?.();
|
|
77
|
+
}, [onUnauthenticated, status]);
|
|
78
|
+
if (status === "validating") return loadingFallback;
|
|
79
|
+
if (status === "error") return errorFallback;
|
|
80
|
+
if (status !== "authenticated") return unauthenticatedFallback;
|
|
81
|
+
return children;
|
|
82
|
+
}
|
|
83
|
+
function PermissionGuard({
|
|
84
|
+
action,
|
|
85
|
+
subject,
|
|
86
|
+
field,
|
|
87
|
+
forbiddenFallback = null,
|
|
88
|
+
abilityOptions,
|
|
89
|
+
children,
|
|
90
|
+
...sessionProps
|
|
91
|
+
}) {
|
|
92
|
+
const allowed = useCan(action, subject, field, abilityOptions);
|
|
93
|
+
return createElement(SessionGuard, {
|
|
94
|
+
...sessionProps,
|
|
95
|
+
children: allowed ? children : forbiddenFallback
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
export {
|
|
99
|
+
AuthyonProvider,
|
|
100
|
+
AuthyonSessionController,
|
|
101
|
+
PermissionGuard,
|
|
102
|
+
SessionGuard,
|
|
103
|
+
useAuthyon,
|
|
104
|
+
useAuthyonAbility,
|
|
105
|
+
useCan
|
|
106
|
+
};
|