@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.
@@ -0,0 +1,303 @@
1
+ // src/session/sessionController.ts
2
+ var SERVER_SNAPSHOT = {
3
+ status: "unauthenticated",
4
+ session: null,
5
+ user: null,
6
+ error: null
7
+ };
8
+ var AuthyonSessionController = class {
9
+ constructor(client, options = {}) {
10
+ this.client = client;
11
+ this.listeners = /* @__PURE__ */ new Set();
12
+ this.getSnapshot = () => this.snapshot;
13
+ this.getServerSnapshot = () => SERVER_SNAPSHOT;
14
+ this.subscribe = (listener) => {
15
+ this.listeners.add(listener);
16
+ return () => this.listeners.delete(listener);
17
+ };
18
+ this.refreshAheadMs = options.refreshAheadMs ?? 3e4;
19
+ if (!Number.isFinite(this.refreshAheadMs) || this.refreshAheadMs < 0) {
20
+ throw new Error("Authyon: `refreshAheadMs` must be a non-negative finite number");
21
+ }
22
+ const session = client.getSession();
23
+ this.snapshot = {
24
+ status: session ? "validating" : "unauthenticated",
25
+ session,
26
+ user: session?.user ?? null,
27
+ error: null
28
+ };
29
+ }
30
+ start() {
31
+ if (!this.unsubscribeAuth) {
32
+ this.unsubscribeAuth = this.client.onAuthStateChange((event) => {
33
+ if (event.type === "signed_out") {
34
+ this.cancelRefresh();
35
+ this.setSnapshot({
36
+ status: "unauthenticated",
37
+ session: null,
38
+ user: null,
39
+ error: null
40
+ });
41
+ return;
42
+ }
43
+ if (event.type === "session_validated") {
44
+ this.acceptSession(event.session);
45
+ return;
46
+ }
47
+ this.setSnapshot({
48
+ status: "validating",
49
+ session: event.session,
50
+ user: event.session.user ?? null,
51
+ error: null
52
+ });
53
+ void this.validate();
54
+ });
55
+ }
56
+ void this.validate();
57
+ return () => this.stop();
58
+ }
59
+ stop() {
60
+ this.unsubscribeAuth?.();
61
+ this.unsubscribeAuth = void 0;
62
+ this.cancelRefresh();
63
+ }
64
+ validate() {
65
+ if (this.validation) return this.validation;
66
+ const localSession = this.client.getSession();
67
+ if (!localSession) {
68
+ this.setSnapshot({
69
+ status: "unauthenticated",
70
+ session: null,
71
+ user: null,
72
+ error: null
73
+ });
74
+ return Promise.resolve(this.snapshot);
75
+ }
76
+ this.setSnapshot({ ...this.snapshot, status: "validating", error: null });
77
+ this.validation = this.client.validateSession().then((session) => {
78
+ if (session) this.acceptSession(session);
79
+ else {
80
+ this.setSnapshot({
81
+ status: "unauthenticated",
82
+ session: null,
83
+ user: null,
84
+ error: null
85
+ });
86
+ }
87
+ return this.snapshot;
88
+ }).catch((error) => {
89
+ this.setSnapshot({ ...this.snapshot, status: "error", error });
90
+ return this.snapshot;
91
+ }).finally(() => {
92
+ this.validation = void 0;
93
+ });
94
+ return this.validation;
95
+ }
96
+ async refreshNow() {
97
+ if (!this.client.getSession()) return this.validate();
98
+ try {
99
+ await this.client.refresh();
100
+ } catch (error) {
101
+ if (!this.client.getSession()) return this.validate();
102
+ this.setSnapshot({ ...this.snapshot, status: "error", error });
103
+ return this.snapshot;
104
+ }
105
+ return this.validate();
106
+ }
107
+ acceptSession(session) {
108
+ this.setSnapshot({
109
+ status: "authenticated",
110
+ session,
111
+ user: session.user ?? null,
112
+ error: null
113
+ });
114
+ this.scheduleRefresh(session);
115
+ }
116
+ scheduleRefresh(session) {
117
+ this.cancelRefresh();
118
+ const delay = Math.max(1e3, session.expiresAt - Date.now() - this.refreshAheadMs);
119
+ this.refreshTimer = setTimeout(() => void this.refreshNow(), delay);
120
+ }
121
+ cancelRefresh() {
122
+ if (this.refreshTimer !== void 0) clearTimeout(this.refreshTimer);
123
+ this.refreshTimer = void 0;
124
+ }
125
+ setSnapshot(snapshot) {
126
+ this.snapshot = snapshot;
127
+ for (const listener of this.listeners) listener();
128
+ }
129
+ };
130
+
131
+ // ../../internal/core/authorization/ability.ts
132
+ var AuthyonAbility = class {
133
+ constructor(rules = [], detectSubjectType = defaultSubjectType) {
134
+ this.detectSubjectType = detectSubjectType;
135
+ this.listeners = /* @__PURE__ */ new Set();
136
+ this.currentRules = rules.map(cloneRule);
137
+ }
138
+ get rules() {
139
+ return this.currentRules;
140
+ }
141
+ can(action, subject, field) {
142
+ const subjectType = typeof subject === "string" ? subject : this.detectSubjectType(subject);
143
+ for (let index = this.currentRules.length - 1; index >= 0; index -= 1) {
144
+ const rule = this.currentRules[index];
145
+ if (!matchesToken(rule.action, action, "manage")) continue;
146
+ if (!matchesToken(rule.subject, subjectType, "all")) continue;
147
+ if (field && rule.fields && !rule.fields.some((value) => matchesField(value, field)))
148
+ continue;
149
+ if (rule.conditions) {
150
+ if (typeof subject === "string" || !matchesConditions(subject, rule.conditions)) continue;
151
+ }
152
+ return !rule.inverted;
153
+ }
154
+ return false;
155
+ }
156
+ cannot(action, subject, field) {
157
+ return !this.can(action, subject, field);
158
+ }
159
+ rulesFor(action, subject) {
160
+ return this.currentRules.filter(
161
+ (rule) => matchesToken(rule.action, action, "manage") && matchesToken(rule.subject, subject, "all")
162
+ );
163
+ }
164
+ update(rules) {
165
+ this.currentRules = rules.map(cloneRule);
166
+ for (const listener of this.listeners) listener(this.rules);
167
+ }
168
+ on(event, listener) {
169
+ if (event !== "updated") return () => void 0;
170
+ this.listeners.add(listener);
171
+ return () => this.listeners.delete(listener);
172
+ }
173
+ };
174
+ var AuthyonAbilityBuilder = class {
175
+ constructor() {
176
+ this.rules = [];
177
+ }
178
+ can(action, subject, conditions, fields) {
179
+ this.rules.push({ action, subject, conditions, fields });
180
+ return this;
181
+ }
182
+ cannot(action, subject, conditions, fields, reason) {
183
+ this.rules.push({ action, subject, conditions, fields, reason, inverted: true });
184
+ return this;
185
+ }
186
+ build(options = {}) {
187
+ return new AuthyonAbility(this.rules, options.detectSubjectType);
188
+ }
189
+ };
190
+ function createAuthyonAbility(source = {}, options = {}) {
191
+ return new AuthyonAbility(createAuthyonRules(source, options), options.detectSubjectType);
192
+ }
193
+ function createAuthyonRules(source = {}, options = {}) {
194
+ const permissions = /* @__PURE__ */ new Set([
195
+ ...source.permissions ?? [],
196
+ ...source.scope?.split(/\s+/).filter(Boolean) ?? []
197
+ ]);
198
+ const rules = [...permissions].map(permissionToRule).filter(isAbilityRule);
199
+ for (const role of /* @__PURE__ */ new Set([...source.roles ?? [], ...options.roles ?? []])) {
200
+ rules.push(...(options.roleRules?.[role] ?? []).map(cloneRule));
201
+ }
202
+ rules.push(...(options.rules ?? []).map(cloneRule));
203
+ return rules;
204
+ }
205
+ function permissionToRule(permission) {
206
+ const normalized = permission.trim();
207
+ if (!normalized) return null;
208
+ if (normalized === "*" || normalized === "*:*" || normalized === "all:manage") {
209
+ return { action: "manage", subject: "all" };
210
+ }
211
+ const separator = normalized.lastIndexOf(":");
212
+ if (separator <= 0 || separator === normalized.length - 1) return null;
213
+ const subject = normalized.slice(0, separator);
214
+ const action = normalized.slice(separator + 1);
215
+ return {
216
+ action: action === "*" ? "manage" : action,
217
+ subject: subject === "*" ? "all" : subject
218
+ };
219
+ }
220
+ function matchesToken(value, expected, wildcard) {
221
+ return (Array.isArray(value) ? value : [value]).some(
222
+ (candidate) => candidate === expected || candidate === wildcard || candidate === "*"
223
+ );
224
+ }
225
+ function matchesField(pattern, field) {
226
+ if (pattern === "*" || pattern === field) return true;
227
+ return pattern.endsWith(".*") && field.startsWith(pattern.slice(0, -1));
228
+ }
229
+ function matchesConditions(subject, conditions) {
230
+ return Object.entries(conditions).every(([path, expected]) => {
231
+ if (path === "$and" && Array.isArray(expected)) {
232
+ return expected.every(
233
+ (condition) => matchesConditions(subject, condition)
234
+ );
235
+ }
236
+ if (path === "$or" && Array.isArray(expected)) {
237
+ return expected.some(
238
+ (condition) => matchesConditions(subject, condition)
239
+ );
240
+ }
241
+ return matchesValue(readPath(subject, path), expected);
242
+ });
243
+ }
244
+ function matchesValue(actual, expected) {
245
+ if (!isRecord(expected) || !Object.keys(expected).some((key) => key.startsWith("$"))) {
246
+ return isRecord(expected) && isRecord(actual) ? matchesConditions(actual, expected) : Object.is(actual, expected);
247
+ }
248
+ return Object.entries(expected).every(([operator, operand]) => {
249
+ switch (operator) {
250
+ case "$eq":
251
+ return Object.is(actual, operand);
252
+ case "$ne":
253
+ return !Object.is(actual, operand);
254
+ case "$in":
255
+ return Array.isArray(operand) && operand.some((value) => Object.is(actual, value));
256
+ case "$nin":
257
+ return Array.isArray(operand) && !operand.some((value) => Object.is(actual, value));
258
+ case "$gt":
259
+ return typeof actual === "number" && typeof operand === "number" && actual > operand;
260
+ case "$gte":
261
+ return typeof actual === "number" && typeof operand === "number" && actual >= operand;
262
+ case "$lt":
263
+ return typeof actual === "number" && typeof operand === "number" && actual < operand;
264
+ case "$lte":
265
+ return typeof actual === "number" && typeof operand === "number" && actual <= operand;
266
+ case "$exists":
267
+ return operand ? actual !== void 0 : actual === void 0;
268
+ default:
269
+ return false;
270
+ }
271
+ });
272
+ }
273
+ function readPath(value, path) {
274
+ return path.split(".").reduce((current, part) => isRecord(current) ? current[part] : void 0, value);
275
+ }
276
+ function defaultSubjectType(subject) {
277
+ const explicit = subject.__type ?? subject.type ?? subject.kind;
278
+ if (typeof explicit === "string") return explicit;
279
+ const constructorName = subject.constructor?.name;
280
+ return typeof constructorName === "string" ? constructorName : "Object";
281
+ }
282
+ function cloneRule(rule) {
283
+ return {
284
+ ...rule,
285
+ action: Array.isArray(rule.action) ? [...rule.action] : rule.action,
286
+ subject: Array.isArray(rule.subject) ? [...rule.subject] : rule.subject,
287
+ fields: rule.fields ? [...rule.fields] : void 0
288
+ };
289
+ }
290
+ function isRecord(value) {
291
+ return typeof value === "object" && value !== null && !Array.isArray(value);
292
+ }
293
+ function isAbilityRule(value) {
294
+ return value !== null;
295
+ }
296
+
297
+ export {
298
+ AuthyonSessionController,
299
+ AuthyonAbility,
300
+ AuthyonAbilityBuilder,
301
+ createAuthyonAbility,
302
+ createAuthyonRules
303
+ };