@aooth/arbac-moost 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 aoothjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,38 @@
1
+ <p align="center">
2
+ <a href="https://aooth.moost.org">
3
+ <img src="https://aooth.moost.org/logo.svg" alt="aoothjs" width="120" />
4
+ </a>
5
+ </p>
6
+
7
+ <h1 align="center">@aooth/arbac-moost</h1>
8
+
9
+ <p align="center">
10
+ Moost RBAC integration — DI-injectable <code>MoostArbac</code>, an authorize interceptor, <code>@ArbacResource</code> / <code>@ArbacAction</code> decorators, <code>AsArbacDbController</code> for scoped DB controllers, and auto-wired provider plumbing for <code>.as</code> user models.
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://aooth.moost.org/moost/"><strong>Documentation →</strong></a>
15
+ </p>
16
+
17
+ ---
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pnpm add @aooth/arbac-moost @aooth/arbac @aooth/user
23
+ ```
24
+
25
+ ## Documentation
26
+
27
+ Full docs, API reference, and recipes: **https://aooth.moost.org/moost/**
28
+
29
+ - [Setup](https://aooth.moost.org/moost/setup)
30
+ - [`@ArbacAuthorize`](https://aooth.moost.org/moost/arbac-authorize)
31
+ - [DB controllers (`AsArbacDbController`)](https://aooth.moost.org/moost/db-controllers)
32
+ - [Atscript wiring (`@arbac.*` annotations)](https://aooth.moost.org/moost/atscript)
33
+ - [Decorators](https://aooth.moost.org/moost/decorators)
34
+ - [API reference](https://aooth.moost.org/api/arbac-moost)
35
+
36
+ ## License
37
+
38
+ MIT
@@ -0,0 +1,80 @@
1
+ import { t as AoothArbacUserCredentials } from "../user-CFXfHtsb.mjs";
2
+ import { t as ArbacUserProvider } from "../user.provider-JpI5dD6Z.mjs";
3
+ import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
4
+
5
+ //#region src/atscript/auto-provider.d.ts
6
+ /**
7
+ * Minimal atscript-db readable surface used to fetch the user record. Matches
8
+ * `AtscriptDbTable.findOne` exactly so consumers pass the table directly.
9
+ * Kept loose to avoid pulling `@atscript/db` types into the public surface.
10
+ *
11
+ * `controls.$with` is optional — included so providers can request nav-prop
12
+ * expansion when `@arbac.role` is declared on a `@db.rel.from` field.
13
+ */
14
+ interface ArbacUserTable<T extends object> {
15
+ findOne(query: {
16
+ filter: Record<string, unknown>;
17
+ controls?: {
18
+ $select?: Record<string, 1>;
19
+ $with?: Array<{
20
+ name: string;
21
+ }>;
22
+ };
23
+ }): Promise<T | null>;
24
+ }
25
+ /**
26
+ * `@Injectable()` (SINGLETON) — moost@0.6.x's `Injectable` metadata is NOT
27
+ * inherited from the base `ArbacUserProvider` by infact, so the decorator
28
+ * must be re-applied here. SINGLETON is the right scope: there is no
29
+ * per-instance state worth scoping per event, and FOR_EVENT trips a
30
+ * scope-id mismatch when the interceptor resolves the provider in a
31
+ * multi-adapter app (HTTP + WF). Per-event memoization is provided via
32
+ * a wooks-slot cache keyed by `this` — see `useFetchCache` above.
33
+ *
34
+ * Consumers extend this class, implement `getUserId()` (typically reading
35
+ * the JWT subject from the auth composable), inject their atscript-db
36
+ * table, and register the subclass via `setReplaceRegistry`.
37
+ *
38
+ * `extractRoles` and `extractAttrs` are protected seams — override to
39
+ * reshape roles/attrs without re-implementing the fetch path.
40
+ */
41
+ declare abstract class AtscriptArbacUserProvider<T extends object = object> extends ArbacUserProvider {
42
+ protected readonly userType: TAtscriptAnnotatedType;
43
+ protected readonly table: ArbacUserTable<T>;
44
+ private readonly spec;
45
+ private readonly projection;
46
+ private readonly withClause;
47
+ constructor(userType: TAtscriptAnnotatedType, table: ArbacUserTable<T>);
48
+ abstract getUserId(): string | Promise<string>;
49
+ getRoles(id: string): Promise<string[]>;
50
+ getAttrs(id: string): Promise<object>;
51
+ /**
52
+ * Override seam: role identifiers pulled off the record.
53
+ *
54
+ * - inline (`string | string[]`): the field value, with empty / nullish /
55
+ * non-string entries dropped and duplicates collapsed in first-seen order.
56
+ * - `@db.rel.from` (joined array of role records): each entry's
57
+ * `roleTargetIdField` value (resolved at spec time on the target type
58
+ * using the same `@arbac.userId` → preferred unique index → `@meta.id`
59
+ * chain). Same dedup / drop-empty rules.
60
+ *
61
+ * Returns `[]` when the role field is undeclared or its value is null /
62
+ * undefined / empty.
63
+ */
64
+ protected extractRoles(record: T): string[];
65
+ /**
66
+ * Override seam: `@arbac.attribute` fields keyed by prop name. Undefined
67
+ * entries are retained so consumers can distinguish "declared but empty"
68
+ * from "not declared".
69
+ */
70
+ protected extractAttrs(record: T): object;
71
+ /**
72
+ * Per-event, per-instance, per-userId memoized fetch. The cache lives on
73
+ * the wooks event context so two distinct events never share state, and
74
+ * is keyed by `this` so multiple replacement subclasses in the same
75
+ * process do not collide.
76
+ */
77
+ private fetchRecord;
78
+ }
79
+ //#endregion
80
+ export { AoothArbacUserCredentials, type ArbacUserTable, AtscriptArbacUserProvider };
@@ -0,0 +1,229 @@
1
+ import { r as __decorate, t as ArbacUserProvider } from "../user.provider-CGWueNjx.mjs";
2
+ import { t as AoothArbacUserCredentials } from "../user-CFXfHtsb.mjs";
3
+ import { defineWook, key } from "@wooksjs/event-core";
4
+ import { Injectable } from "moost";
5
+ //#region \0@oxc-project+runtime@0.129.0/helpers/decorateMetadata.js
6
+ function __decorateMetadata(k, v) {
7
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8
+ }
9
+ //#endregion
10
+ //#region src/atscript/auto-provider.ts
11
+ const specCache = /* @__PURE__ */ new WeakMap();
12
+ /**
13
+ * Resolve the identifier field on an object type using the three-step chain
14
+ * documented on `ArbacExtractSpec.userIdField`. Used for the user type AND
15
+ * for the role target type referenced by `@db.rel.from`-shaped role fields.
16
+ */
17
+ function resolveIdentifierField(type) {
18
+ const def = type.type;
19
+ if (def.kind !== "object") return void 0;
20
+ let explicit;
21
+ let metaId;
22
+ const uniqueIndexFields = /* @__PURE__ */ new Map();
23
+ const anyUniqueField = [];
24
+ for (const [fieldName, fieldType] of def.props) {
25
+ const md = fieldType.metadata;
26
+ if (md.get("arbac.userId")) explicit = fieldName;
27
+ if (md.get("meta.id")) metaId = fieldName;
28
+ const unique = md.get("db.index.unique");
29
+ if (Array.isArray(unique)) {
30
+ for (const entry of unique) if (entry === true) anyUniqueField.push(fieldName);
31
+ else if (typeof entry === "string") {
32
+ const bucket = uniqueIndexFields.get(entry);
33
+ if (bucket) bucket.push(fieldName);
34
+ else uniqueIndexFields.set(entry, [fieldName]);
35
+ }
36
+ }
37
+ }
38
+ if (explicit) return explicit;
39
+ const preferred = type.metadata.get("db.table.preferredId.uniqueIndex");
40
+ if (preferred !== void 0) if (typeof preferred === "string") {
41
+ const fields = uniqueIndexFields.get(preferred);
42
+ if (fields && fields.length === 1) return fields[0];
43
+ } else {
44
+ for (const fields of uniqueIndexFields.values()) if (fields.length === 1) return fields[0];
45
+ if (anyUniqueField.length > 0) return anyUniqueField[0];
46
+ }
47
+ return metaId;
48
+ }
49
+ function getArbacExtractSpec(type) {
50
+ const cached = specCache.get(type);
51
+ if (cached !== void 0) return cached;
52
+ const spec = {
53
+ userIdField: void 0,
54
+ roleField: void 0,
55
+ attrFields: []
56
+ };
57
+ const def = type.type;
58
+ if (def.kind !== "object") {
59
+ specCache.set(type, spec);
60
+ return spec;
61
+ }
62
+ const roleCandidates = [];
63
+ for (const [fieldName, fieldType] of def.props) {
64
+ const md = fieldType.metadata;
65
+ if (md.get("arbac.role")) roleCandidates.push({
66
+ name: fieldName,
67
+ fieldType
68
+ });
69
+ if (md.get("arbac.attribute")) spec.attrFields.push(fieldName);
70
+ }
71
+ if (roleCandidates.length > 1) throw new Error(`AtscriptArbacUserProvider: multiple @arbac.role fields declared (${roleCandidates.map((c) => c.name).join(", ")}). Exactly one role source is supported — drop the @arbac.role from all but the canonical field.`);
72
+ if (roleCandidates.length === 1) {
73
+ const { name, fieldType } = roleCandidates[0];
74
+ if (fieldType.metadata.get("db.rel.from") !== void 0) {
75
+ const target = resolveRelTargetType(fieldType);
76
+ if (!target) throw new Error(`AtscriptArbacUserProvider: @arbac.role on @db.rel.from field "${name}" — could not resolve the target role type. Declare the nav prop as \`<RoleType>[]\`.`);
77
+ const roleTargetIdField = resolveIdentifierField(target);
78
+ if (!roleTargetIdField) throw new Error(`AtscriptArbacUserProvider: @arbac.role on @db.rel.from field "${name}" — target role type has no @arbac.userId / preferred unique index / @meta.id to identify role names by.`);
79
+ spec.roleField = {
80
+ name,
81
+ shape: "rel.from",
82
+ roleTargetIdField
83
+ };
84
+ } else spec.roleField = {
85
+ name,
86
+ shape: "inline"
87
+ };
88
+ }
89
+ spec.userIdField = resolveIdentifierField(type);
90
+ specCache.set(type, spec);
91
+ return spec;
92
+ }
93
+ /**
94
+ * Walk an annotated type to the target type of a navigation prop. Most cases
95
+ * are `Role[]` (array of annotated types), so we descend through `array.of`
96
+ * once. If the descent doesn't land on an `object`, the caller treats it as
97
+ * unresolvable.
98
+ */
99
+ function resolveRelTargetType(fieldType) {
100
+ const def = fieldType.type;
101
+ if (def.kind === "array") {
102
+ const of = def.of;
103
+ if (of && of.type.kind === "object") return of;
104
+ }
105
+ if (def.kind === "object") return fieldType;
106
+ }
107
+ /** Mongo-style projection covering id + `@arbac.role` (when inline) + `@arbac.attribute` fields. */
108
+ const projectionCache = /* @__PURE__ */ new WeakMap();
109
+ function getArbacProjection(type) {
110
+ const cached = projectionCache.get(type);
111
+ if (cached !== void 0) return cached;
112
+ const spec = getArbacExtractSpec(type);
113
+ const projection = {};
114
+ if (spec.userIdField) projection[spec.userIdField] = 1;
115
+ if (spec.roleField && spec.roleField.shape === "inline") projection[spec.roleField.name] = 1;
116
+ for (const f of spec.attrFields) projection[f] = 1;
117
+ projectionCache.set(type, projection);
118
+ return projection;
119
+ }
120
+ const fetchCacheKey = key("aooth.arbacFetchCache");
121
+ const useFetchCache = defineWook((ctx) => {
122
+ let cache = ctx.has(fetchCacheKey) ? ctx.get(fetchCacheKey) : void 0;
123
+ if (!cache) {
124
+ cache = /* @__PURE__ */ new WeakMap();
125
+ ctx.set(fetchCacheKey, cache);
126
+ }
127
+ return cache;
128
+ });
129
+ let AtscriptArbacUserProvider = class AtscriptArbacUserProvider extends ArbacUserProvider {
130
+ spec;
131
+ projection;
132
+ withClause;
133
+ constructor(userType, table) {
134
+ super();
135
+ this.userType = userType;
136
+ this.table = table;
137
+ this.spec = getArbacExtractSpec(userType);
138
+ if (!this.spec.userIdField) throw new Error("AtscriptArbacUserProvider: userType has no @arbac.userId, @db.table.preferredId.uniqueIndex field, or @meta.id — annotate one to identify users");
139
+ this.projection = getArbacProjection(userType);
140
+ this.withClause = this.spec.roleField?.shape === "rel.from" ? [{ name: this.spec.roleField.name }] : void 0;
141
+ }
142
+ async getRoles(id) {
143
+ const record = await this.fetchRecord(id);
144
+ if (record === null) return [];
145
+ return this.extractRoles(record);
146
+ }
147
+ async getAttrs(id) {
148
+ const record = await this.fetchRecord(id);
149
+ if (record === null) return {};
150
+ return this.extractAttrs(record);
151
+ }
152
+ /**
153
+ * Override seam: role identifiers pulled off the record.
154
+ *
155
+ * - inline (`string | string[]`): the field value, with empty / nullish /
156
+ * non-string entries dropped and duplicates collapsed in first-seen order.
157
+ * - `@db.rel.from` (joined array of role records): each entry's
158
+ * `roleTargetIdField` value (resolved at spec time on the target type
159
+ * using the same `@arbac.userId` → preferred unique index → `@meta.id`
160
+ * chain). Same dedup / drop-empty rules.
161
+ *
162
+ * Returns `[]` when the role field is undeclared or its value is null /
163
+ * undefined / empty.
164
+ */
165
+ extractRoles(record) {
166
+ const roleField = this.spec.roleField;
167
+ if (!roleField) return [];
168
+ const raw = record[roleField.name];
169
+ if (raw === void 0 || raw === null) return [];
170
+ const seen = /* @__PURE__ */ new Set();
171
+ const out = [];
172
+ const push = (val) => {
173
+ if (typeof val === "string" && val !== "" && !seen.has(val)) {
174
+ seen.add(val);
175
+ out.push(val);
176
+ }
177
+ };
178
+ if (roleField.shape === "inline") if (Array.isArray(raw)) for (const item of raw) push(item);
179
+ else push(raw);
180
+ else {
181
+ if (!Array.isArray(raw)) return out;
182
+ const idField = roleField.roleTargetIdField;
183
+ for (const item of raw) if (item && typeof item === "object") push(item[idField]);
184
+ }
185
+ return out;
186
+ }
187
+ /**
188
+ * Override seam: `@arbac.attribute` fields keyed by prop name. Undefined
189
+ * entries are retained so consumers can distinguish "declared but empty"
190
+ * from "not declared".
191
+ */
192
+ extractAttrs(record) {
193
+ const attrFields = this.spec.attrFields;
194
+ if (attrFields.length === 0) return {};
195
+ const out = {};
196
+ const rec = record;
197
+ for (const field of attrFields) out[field] = rec[field];
198
+ return out;
199
+ }
200
+ /**
201
+ * Per-event, per-instance, per-userId memoized fetch. The cache lives on
202
+ * the wooks event context so two distinct events never share state, and
203
+ * is keyed by `this` so multiple replacement subclasses in the same
204
+ * process do not collide.
205
+ */
206
+ fetchRecord(userId) {
207
+ const ctxCache = useFetchCache();
208
+ let perProvider = ctxCache.get(this);
209
+ if (!perProvider) {
210
+ perProvider = /* @__PURE__ */ new Map();
211
+ ctxCache.set(this, perProvider);
212
+ }
213
+ const cached = perProvider.get(userId);
214
+ if (cached !== void 0) return cached;
215
+ const userIdField = this.spec.userIdField;
216
+ const controls = { $select: this.projection };
217
+ if (this.withClause) controls.$with = this.withClause;
218
+ const promise = this.table.findOne({
219
+ filter: { [userIdField]: userId },
220
+ controls
221
+ });
222
+ promise.catch(() => perProvider?.delete(userId));
223
+ perProvider.set(userId, promise);
224
+ return promise;
225
+ }
226
+ };
227
+ AtscriptArbacUserProvider = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [Object, Object])], AtscriptArbacUserProvider);
228
+ //#endregion
229
+ export { AoothArbacUserCredentials, AtscriptArbacUserProvider };