@teamblind/axeda-express 0.0.0-stage → 0.1.0-alpha.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/CHANGELOG.md +30 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +14 -2
- package/dist/csrf.d.ts +11 -0
- package/dist/csrf.js +43 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/middleware.d.ts +85 -0
- package/dist/middleware.js +155 -0
- package/dist/scope.d.ts +42 -0
- package/dist/scope.js +47 -0
- package/package.json +57 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# @teamblind/axeda-express
|
|
2
|
+
|
|
3
|
+
## 0.1.0-alpha.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- No changes of its own. It is versioned together with the other packages so that the four share one version, and it now depends on `@teamblind/axeda-core` `0.1.0-alpha.1`.
|
|
8
|
+
- Updated dependencies [ce83aff]
|
|
9
|
+
- @teamblind/axeda-core@0.1.0-alpha.1
|
|
10
|
+
|
|
11
|
+
## 0.1.0-alpha.0
|
|
12
|
+
|
|
13
|
+
### Minor Changes
|
|
14
|
+
|
|
15
|
+
- 7ebf1fd: Add Express middleware, a secure Better Auth preset and the first documentation. `@teamblind/axeda-express` provides `requireAuth()`, `requirePermission()` and `resolveScope()`: it denies by default, resolves the company of a business from the database, answers the same whether a scope exists or not, requires a trusted origin for cookie-bearing writes and never fails open. `@teamblind/axeda-better-auth` adds `secureAuthOptions()` (refuses weak secrets, wildcard or plain-http origins), `sessionPrincipal()` and `principalFromUser()`, and the plugin now refuses to start with Better Auth's CSRF check, origin check or IP tracking disabled. `@teamblind/axeda-core` adds `resolveTarget()` so applications never trust a company id sent by the client. Documentation in English and Spanish, and an example API in `apps/example`.
|
|
16
|
+
- d9c4b80: `@teamblind/axeda-express` gains an optional `onDenied` hook that reports every refused request, with the exact reason the client is not told, so an application can log it; it never changes the response and a failing hook is ignored. All packages now declare a `default` export condition next to `types`, so they can be loaded from CommonJS with `require()` on Node 22.12 or later (and with `import()` everywhere); before, `require()` failed with `ERR_PACKAGE_PATH_NOT_EXPORTED`.
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- fed4ed1: Make the packages publishable: compiled ES modules with type declarations under `dist/`, an `exports` map, `files` limited to what is needed, a README, the licence and the notice in each tarball, and the dependencies each package really uses (`@teamblind/axeda-core` for the others, `zod`, and `vitest` and `@types/express` as peers where needed). The CI now builds the packages, checks what would be published and installs the packed files in an empty project to run and type-check them, and it runs the suite against Better Auth 1.7.10 and 1.7.14.
|
|
21
|
+
- Updated dependencies [b519956]
|
|
22
|
+
- Updated dependencies [c55b0f4]
|
|
23
|
+
- Updated dependencies [c6a80da]
|
|
24
|
+
- Updated dependencies [a836007]
|
|
25
|
+
- Updated dependencies [7ebf1fd]
|
|
26
|
+
- Updated dependencies [fed4ed1]
|
|
27
|
+
- Updated dependencies [d9c4b80]
|
|
28
|
+
- Updated dependencies [680ab7d]
|
|
29
|
+
- Updated dependencies [b402e20]
|
|
30
|
+
- @teamblind/axeda-core@0.1.0-alpha.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] TeamBlind
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @teamblind/axeda-express
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Middleware to guard the routes of an Express 5 application with Axeda permissions: `requireAuth()`, `requirePermission()` and `resolveScope()`. It denies by default, resolves the company of a business from the database and requires a trusted origin for cookie-bearing writes.
|
|
4
|
+
|
|
5
|
+
> **Status:** alpha (`0.1.0-alpha.1`); the API can still change before 1.0. Install with `npm install @teamblind/axeda-express@alpha`. Documentation: [English](https://github.com/teamblindmx/axeda/tree/main/docs/en) · [Español](https://github.com/teamblindmx/axeda/tree/main/docs/es).
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createAxedaExpress, resolveScope } from '@teamblind/axeda-express';
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Peer dependency: `express` `^5`. Express 4 is not supported.
|
|
12
|
+
|
|
13
|
+
Guides: [Quick start](https://github.com/teamblindmx/axeda/blob/main/docs/en/quickstart.md) · [Configuration](https://github.com/teamblindmx/axeda/blob/main/docs/en/configuration.md) · [Reference](https://github.com/teamblindmx/axeda/blob/main/docs/en/reference.md) · [Upgrading](https://github.com/teamblindmx/axeda/blob/main/docs/en/upgrading.md).
|
|
14
|
+
|
|
15
|
+
Part of [Axeda](https://github.com/teamblindmx/axeda), hierarchical authorization (global → company → business) on top of [Better Auth](https://www.better-auth.com). Licensed under [Apache-2.0](LICENSE).
|
package/dist/csrf.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Orígenes de confianza, normalizados. Una entrada con comodín o con ruta es un error de configuración. */
|
|
2
|
+
export declare function trustedOriginSet(origins: readonly string[]): ReadonlySet<string>;
|
|
3
|
+
/**
|
|
4
|
+
* ¿Es una petición entre sitios que puede hacer daño? Solo importa si es de las que cambian
|
|
5
|
+
* cosas y viaja con cookie: sin cookie no hay credencial que el navegador adjunte por su cuenta.
|
|
6
|
+
* Con cookie, el `Origin` debe ser de confianza; si falta o es `null`, se rechaza.
|
|
7
|
+
*/
|
|
8
|
+
export declare function isCrossSiteWrite(method: string, headers: {
|
|
9
|
+
readonly cookie?: string | undefined;
|
|
10
|
+
readonly origin?: string | string[] | undefined;
|
|
11
|
+
}, trusted: ReadonlySet<string>): boolean;
|
package/dist/csrf.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { AxedaError } from '@teamblind/axeda-core';
|
|
2
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
3
|
+
function normalise(origin) {
|
|
4
|
+
try {
|
|
5
|
+
const url = new URL(origin);
|
|
6
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : null;
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Orígenes de confianza, normalizados. Una entrada con comodín o con ruta es un error de configuración. */
|
|
13
|
+
export function trustedOriginSet(origins) {
|
|
14
|
+
if (origins.length === 0) {
|
|
15
|
+
throw new AxedaError('AXEDA_INVALID_CONFIG', 'trustedOrigins is empty: list the front end origins, or pass csrf: false if this API never ' +
|
|
16
|
+
'authenticates with cookies.');
|
|
17
|
+
}
|
|
18
|
+
const set = new Set();
|
|
19
|
+
for (const raw of origins) {
|
|
20
|
+
const origin = normalise(raw);
|
|
21
|
+
if (origin === null || raw.includes('*') || new URL(raw).pathname !== '/') {
|
|
22
|
+
throw new AxedaError('AXEDA_INVALID_CONFIG', `trustedOrigins entry "${raw}" must be an origin like https://app.example.com.`);
|
|
23
|
+
}
|
|
24
|
+
set.add(origin);
|
|
25
|
+
}
|
|
26
|
+
return set;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* ¿Es una petición entre sitios que puede hacer daño? Solo importa si es de las que cambian
|
|
30
|
+
* cosas y viaja con cookie: sin cookie no hay credencial que el navegador adjunte por su cuenta.
|
|
31
|
+
* Con cookie, el `Origin` debe ser de confianza; si falta o es `null`, se rechaza.
|
|
32
|
+
*/
|
|
33
|
+
export function isCrossSiteWrite(method, headers, trusted) {
|
|
34
|
+
if (SAFE_METHODS.has(method.toUpperCase()))
|
|
35
|
+
return false;
|
|
36
|
+
if (headers.cookie === undefined || headers.cookie === '')
|
|
37
|
+
return false;
|
|
38
|
+
const { origin } = headers;
|
|
39
|
+
if (typeof origin !== 'string')
|
|
40
|
+
return true;
|
|
41
|
+
const normalised = normalise(origin);
|
|
42
|
+
return normalised === null || !trusted.has(normalised);
|
|
43
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { createAxedaExpress, type AxedaExpress, type AxedaExpressOptions, type DeniedDetail, type DeniedEvent, type DeniedReason, type PrincipalResolver, type RequirePermissionOptions, } from './middleware.js';
|
|
2
|
+
export { globalScope, resolveScope, type RequestedScope, type ScopeRequest, type ScopeResolver, type ScopeSource, } from './scope.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { IncomingHttpHeaders } from 'node:http';
|
|
2
|
+
import type { Request, RequestHandler } from 'express';
|
|
3
|
+
import { type Actor, type Axeda, type Principal, type ScopeFilter } from '@teamblind/axeda-core';
|
|
4
|
+
import { type ScopeResolver } from './scope.js';
|
|
5
|
+
/** Cómo se sabe quién hace la petición: recibe las cabeceras y da el `Principal`, o `null` sin sesión. */
|
|
6
|
+
export type PrincipalResolver = (request: {
|
|
7
|
+
readonly headers: Headers;
|
|
8
|
+
}) => Promise<Principal | null>;
|
|
9
|
+
/** Lo que recibió el cliente. */
|
|
10
|
+
export type DeniedReason = 'unauthenticated' | 'forbidden' | 'not-found' | 'cross-site';
|
|
11
|
+
/**
|
|
12
|
+
* Por qué se denegó. El cliente NO lo sabe (una compañía que no existe y un permiso que falta
|
|
13
|
+
* reciben la misma respuesta); quien administra la aplicación sí, para su registro.
|
|
14
|
+
*/
|
|
15
|
+
export type DeniedDetail = 'no-session' | 'cross-site-write' | 'missing-permission' | 'scope-not-found' | 'scope-mismatch' | 'malformed-scope';
|
|
16
|
+
/**
|
|
17
|
+
* Una petición denegada. Solo lleva lo necesario para investigarla: nunca cookies, cabeceras,
|
|
18
|
+
* la cadena de consulta ni el cuerpo. Los textos salen de la petición (están recortados): regístralos
|
|
19
|
+
* como datos de un registro estructurado, no pegados dentro de una línea de texto.
|
|
20
|
+
*/
|
|
21
|
+
export interface DeniedEvent {
|
|
22
|
+
/** Lo que recibió el cliente. */
|
|
23
|
+
readonly reason: DeniedReason;
|
|
24
|
+
/** El estado HTTP que recibió. */
|
|
25
|
+
readonly status: number;
|
|
26
|
+
/** El motivo exacto. */
|
|
27
|
+
readonly detail: DeniedDetail;
|
|
28
|
+
/** El permiso que exigía la ruta, si lo había. */
|
|
29
|
+
readonly permission: string | null;
|
|
30
|
+
readonly method: string;
|
|
31
|
+
/** La ruta, sin la cadena de consulta. */
|
|
32
|
+
readonly path: string;
|
|
33
|
+
/** Quien llamaba, si se llegó a saber. */
|
|
34
|
+
readonly userId: string | null;
|
|
35
|
+
readonly ip: string | null;
|
|
36
|
+
readonly userAgent: string | null;
|
|
37
|
+
}
|
|
38
|
+
interface BaseOptions {
|
|
39
|
+
readonly axeda: Axeda;
|
|
40
|
+
/** Con Better Auth: `sessionPrincipal(auth)` de `@teamblind/axeda-better-auth`. */
|
|
41
|
+
readonly principal: PrincipalResolver;
|
|
42
|
+
/**
|
|
43
|
+
* Se llama cada vez que el middleware deniega una petición, para que la aplicación la registre
|
|
44
|
+
* (Axeda no escribe registros). Corre después de responder: **no puede cambiar la respuesta**, y
|
|
45
|
+
* si lanza un error o rechaza la promesa, se ignora.
|
|
46
|
+
*/
|
|
47
|
+
readonly onDenied?: (event: DeniedEvent) => void | Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Defensa contra CSRF: las peticiones que cambian cosas y viajan con cookie deben venir de un
|
|
51
|
+
* origen de confianza. Se exige decidir: lista los orígenes de tu front end o, si esta API nunca
|
|
52
|
+
* se autentica con cookies, di `csrf: false`.
|
|
53
|
+
*/
|
|
54
|
+
export type AxedaExpressOptions = BaseOptions & ({
|
|
55
|
+
readonly trustedOrigins: readonly string[];
|
|
56
|
+
readonly csrf?: undefined;
|
|
57
|
+
} | {
|
|
58
|
+
readonly csrf: false;
|
|
59
|
+
readonly trustedOrigins?: undefined;
|
|
60
|
+
});
|
|
61
|
+
export interface RequirePermissionOptions {
|
|
62
|
+
/** Dónde se comprueba el permiso (ver `resolveScope`). Por defecto, en global. */
|
|
63
|
+
readonly scope?: ScopeResolver;
|
|
64
|
+
/**
|
|
65
|
+
* Qué responder al que no puede. `forbidden` (403, por defecto) o `not-found` (404). La
|
|
66
|
+
* respuesta es la misma si el recurso no existe o si existe pero no es tuyo: no revela nada.
|
|
67
|
+
*/
|
|
68
|
+
readonly onDeny?: 'forbidden' | 'not-found';
|
|
69
|
+
}
|
|
70
|
+
export interface AxedaExpress {
|
|
71
|
+
/** Exige una sesión. Sin ella, 401. Deja a quien llama disponible en `principalOf(req)`. */
|
|
72
|
+
requireAuth(): RequestHandler;
|
|
73
|
+
/**
|
|
74
|
+
* Exige sesión y el permiso en el alcance de la ruta. Se deniega por defecto: sin sesión 401;
|
|
75
|
+
* sin permiso (o con un alcance que no existe o no cuadra) 403, o 404 con `onDeny: 'not-found'`.
|
|
76
|
+
*/
|
|
77
|
+
requirePermission(permission: string, options?: RequirePermissionOptions): RequestHandler;
|
|
78
|
+
/** Quien hace la petición. Solo en rutas con `requireAuth()` o `requirePermission()` delante. */
|
|
79
|
+
principalOf(request: Request): Actor;
|
|
80
|
+
/** Alcances donde quien llama tiene el permiso, para filtrar tus consultas (T5). */
|
|
81
|
+
scopeFilter(request: Request, permission: string): Promise<ScopeFilter>;
|
|
82
|
+
}
|
|
83
|
+
export declare function toHeaders(raw: IncomingHttpHeaders): Headers;
|
|
84
|
+
export declare function createAxedaExpress(options: AxedaExpressOptions): AxedaExpress;
|
|
85
|
+
export {};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { AxedaError, isWildcard, parsePermissionKey, } from '@teamblind/axeda-core';
|
|
2
|
+
import { isCrossSiteWrite, trustedOriginSet } from './csrf.js';
|
|
3
|
+
import { globalScope } from './scope.js';
|
|
4
|
+
const REPLIES = {
|
|
5
|
+
unauthenticated: [401, 'AXEDA_UNAUTHENTICATED', 'Sign in to continue.'],
|
|
6
|
+
forbidden: [403, 'AXEDA_FORBIDDEN', 'You are not allowed to do that.'],
|
|
7
|
+
notFound: [404, 'AXEDA_NOT_FOUND', 'Not found.'],
|
|
8
|
+
crossSite: [403, 'AXEDA_CROSS_SITE', 'This request comes from an origin that is not trusted.'],
|
|
9
|
+
};
|
|
10
|
+
const REASONS = {
|
|
11
|
+
unauthenticated: 'unauthenticated',
|
|
12
|
+
forbidden: 'forbidden',
|
|
13
|
+
notFound: 'not-found',
|
|
14
|
+
crossSite: 'cross-site',
|
|
15
|
+
};
|
|
16
|
+
const MAX_PATH = 512;
|
|
17
|
+
const MAX_USER_AGENT = 255;
|
|
18
|
+
const clip = (value, max) => value.length > max ? value.slice(0, max) : value;
|
|
19
|
+
function deny(response, reply) {
|
|
20
|
+
const [status, code, message] = REPLIES[reply];
|
|
21
|
+
// Una respuesta de autorización nunca se guarda en cachés compartidas.
|
|
22
|
+
response.status(status).set('Cache-Control', 'no-store').json({ code, message });
|
|
23
|
+
}
|
|
24
|
+
export function toHeaders(raw) {
|
|
25
|
+
const headers = new Headers();
|
|
26
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
27
|
+
if (value === undefined)
|
|
28
|
+
continue;
|
|
29
|
+
for (const item of Array.isArray(value) ? value : [value])
|
|
30
|
+
headers.append(name, item);
|
|
31
|
+
}
|
|
32
|
+
return headers;
|
|
33
|
+
}
|
|
34
|
+
/** Valida el permiso al declarar la ruta: un error tipográfico falla al arrancar, no en producción. */
|
|
35
|
+
function checkedPermission(axeda, permission) {
|
|
36
|
+
const key = parsePermissionKey(permission);
|
|
37
|
+
if (isWildcard(key)) {
|
|
38
|
+
throw new AxedaError('AXEDA_INVALID_PERMISSION', `"${permission}" is a wildcard; a route needs a concrete permission.`);
|
|
39
|
+
}
|
|
40
|
+
if (!axeda.catalog.includes(key)) {
|
|
41
|
+
throw new AxedaError('AXEDA_UNKNOWN_PERMISSION', `"${permission}" is not in the permission catalog. Declare it in axeda({ permissions }).`);
|
|
42
|
+
}
|
|
43
|
+
return permission;
|
|
44
|
+
}
|
|
45
|
+
/** Del alcance pedido al lugar donde decidir, leyendo la base de datos. */
|
|
46
|
+
async function resolve(axeda, requested) {
|
|
47
|
+
if (requested.kind === 'invalid')
|
|
48
|
+
return { detail: 'malformed-scope' };
|
|
49
|
+
if (requested.kind === 'global')
|
|
50
|
+
return { target: { type: 'global' } };
|
|
51
|
+
const target = await axeda.resolveTarget(requested.scope);
|
|
52
|
+
if (target === null)
|
|
53
|
+
return { detail: 'scope-not-found' };
|
|
54
|
+
// /companies/:companyId/businesses/:businessId — el negocio debe ser de esa compañía.
|
|
55
|
+
if (requested.companyMustBe !== undefined &&
|
|
56
|
+
(target.type !== 'business' || target.companyId !== requested.companyMustBe)) {
|
|
57
|
+
return { detail: 'scope-mismatch' };
|
|
58
|
+
}
|
|
59
|
+
return { target };
|
|
60
|
+
}
|
|
61
|
+
export function createAxedaExpress(options) {
|
|
62
|
+
const { axeda } = options;
|
|
63
|
+
const trusted = options.csrf === false ? null : trustedOriginSet(options.trustedOrigins);
|
|
64
|
+
const known = new WeakMap();
|
|
65
|
+
/** Quién es, una sola vez por petición (varios middlewares seguidos no repiten la consulta). */
|
|
66
|
+
async function authenticate(request) {
|
|
67
|
+
const existing = known.get(request);
|
|
68
|
+
if (existing !== undefined)
|
|
69
|
+
return existing;
|
|
70
|
+
const principal = await options.principal({ headers: toHeaders(request.headers) });
|
|
71
|
+
if (principal === null)
|
|
72
|
+
return null;
|
|
73
|
+
const actor = {
|
|
74
|
+
...principal,
|
|
75
|
+
ip: request.ip,
|
|
76
|
+
userAgent: request.get('user-agent'),
|
|
77
|
+
};
|
|
78
|
+
known.set(request, actor);
|
|
79
|
+
return actor;
|
|
80
|
+
}
|
|
81
|
+
/** Corre `work` y, ante cualquier fallo, no deja pasar la petición: se entrega al manejador de errores. */
|
|
82
|
+
const guarded = (work) => (request, response, next) => {
|
|
83
|
+
work(request, response).then((proceed) => (proceed ? next() : undefined), (error) => next(error));
|
|
84
|
+
};
|
|
85
|
+
const crossSite = (request) => trusted !== null && isCrossSiteWrite(request.method, request.headers, trusted);
|
|
86
|
+
/** Avisa a la aplicación. Nunca cambia la respuesta ni la tumba: lo que falle aquí se ignora. */
|
|
87
|
+
function report(request, reply, detail, permission) {
|
|
88
|
+
const hook = options.onDenied;
|
|
89
|
+
if (hook === undefined)
|
|
90
|
+
return;
|
|
91
|
+
const event = {
|
|
92
|
+
reason: REASONS[reply],
|
|
93
|
+
status: REPLIES[reply][0],
|
|
94
|
+
detail,
|
|
95
|
+
permission,
|
|
96
|
+
method: request.method,
|
|
97
|
+
path: clip(request.path, MAX_PATH),
|
|
98
|
+
userId: known.get(request)?.userId ?? null,
|
|
99
|
+
ip: request.ip ?? null,
|
|
100
|
+
userAgent: clip(request.get('user-agent') ?? '', MAX_USER_AGENT) || null,
|
|
101
|
+
};
|
|
102
|
+
try {
|
|
103
|
+
Promise.resolve(hook(event)).catch(() => undefined);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
// Un registro que falla no debe convertirse en un fallo de la ruta ni en una puerta abierta.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function refuse(request, response, reply, detail, permission = null) {
|
|
110
|
+
deny(response, reply);
|
|
111
|
+
report(request, reply, detail, permission);
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
function principalOf(request) {
|
|
115
|
+
const actor = known.get(request);
|
|
116
|
+
if (actor === undefined) {
|
|
117
|
+
throw new AxedaError('AXEDA_INVALID_CONFIG', 'principalOf() needs requireAuth() or requirePermission() earlier in the route.');
|
|
118
|
+
}
|
|
119
|
+
return actor;
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
requireAuth: () => guarded(async (request, response) => {
|
|
123
|
+
if (crossSite(request))
|
|
124
|
+
return refuse(request, response, 'crossSite', 'cross-site-write');
|
|
125
|
+
return (await authenticate(request)) === null
|
|
126
|
+
? refuse(request, response, 'unauthenticated', 'no-session')
|
|
127
|
+
: true;
|
|
128
|
+
}),
|
|
129
|
+
requirePermission(permission, permissionOptions = {}) {
|
|
130
|
+
const checked = checkedPermission(axeda, permission);
|
|
131
|
+
const resolver = permissionOptions.scope ?? globalScope;
|
|
132
|
+
const denied = permissionOptions.onDeny === 'not-found' ? 'notFound' : 'forbidden';
|
|
133
|
+
return guarded(async (request, response) => {
|
|
134
|
+
if (crossSite(request)) {
|
|
135
|
+
return refuse(request, response, 'crossSite', 'cross-site-write', checked);
|
|
136
|
+
}
|
|
137
|
+
const actor = await authenticate(request);
|
|
138
|
+
if (actor === null) {
|
|
139
|
+
return refuse(request, response, 'unauthenticated', 'no-session', checked);
|
|
140
|
+
}
|
|
141
|
+
const resolution = await resolve(axeda, resolver(request));
|
|
142
|
+
// Alcance inexistente, incoherente o sin permiso: la misma respuesta al cliente.
|
|
143
|
+
if ('detail' in resolution) {
|
|
144
|
+
return refuse(request, response, denied, resolution.detail, checked);
|
|
145
|
+
}
|
|
146
|
+
if (!(await axeda.can(actor, checked, resolution.target))) {
|
|
147
|
+
return refuse(request, response, denied, 'missing-permission', checked);
|
|
148
|
+
}
|
|
149
|
+
return true;
|
|
150
|
+
});
|
|
151
|
+
},
|
|
152
|
+
principalOf,
|
|
153
|
+
scopeFilter: (request, permission) => axeda.scopeFilter(principalOf(request), checkedPermission(axeda, permission)),
|
|
154
|
+
};
|
|
155
|
+
}
|
package/dist/scope.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { AssignmentScope } from '@teamblind/axeda-core';
|
|
2
|
+
/** Lo que se necesita de la petición para leer el alcance (`req.params` y `req.query`). */
|
|
3
|
+
export interface ScopeRequest {
|
|
4
|
+
readonly params: Record<string, unknown>;
|
|
5
|
+
readonly query: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
/** Dónde pide la ruta que se compruebe el permiso. */
|
|
8
|
+
export type RequestedScope = {
|
|
9
|
+
readonly kind: 'global';
|
|
10
|
+
} | {
|
|
11
|
+
readonly kind: 'scope';
|
|
12
|
+
readonly scope: AssignmentScope;
|
|
13
|
+
/** Si la ruta nombra también la compañía, el negocio debe ser de ella (T2). */
|
|
14
|
+
readonly companyMustBe?: string;
|
|
15
|
+
}
|
|
16
|
+
/** La petición no trae el alcance bien formado: se deniega, no se adivina. */
|
|
17
|
+
| {
|
|
18
|
+
readonly kind: 'invalid';
|
|
19
|
+
};
|
|
20
|
+
export type ScopeResolver = (request: ScopeRequest) => RequestedScope;
|
|
21
|
+
/** La ruta no es de ninguna compañía ni negocio: el permiso se comprueba en global. */
|
|
22
|
+
export declare const globalScope: ScopeResolver;
|
|
23
|
+
export interface ScopeSource {
|
|
24
|
+
/** Nombre del parámetro con el identificador de la compañía. */
|
|
25
|
+
readonly company?: string;
|
|
26
|
+
/** Nombre del parámetro con el identificador del negocio. */
|
|
27
|
+
readonly business?: string;
|
|
28
|
+
/** Dónde viene: en la ruta (`/companies/:companyId/…`, por defecto) o en la consulta (`?companyId=`). */
|
|
29
|
+
readonly from?: 'params' | 'query';
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Lee el alcance de la ruta. **El identificador es lo que dice el cliente; no se confía en él**:
|
|
33
|
+
* `requirePermission` lo resuelve contra la base de datos (la compañía de un negocio sale de ahí)
|
|
34
|
+
* y, si no existe o no le corresponde, la respuesta es la misma que sin permiso.
|
|
35
|
+
*
|
|
36
|
+
* ```ts
|
|
37
|
+
* resolveScope({ company: 'companyId' }) // /companies/:companyId/invoices
|
|
38
|
+
* resolveScope({ company: 'companyId', business: 'businessId' }) // el negocio debe ser de esa compañía
|
|
39
|
+
* resolveScope({ company: 'companyId', from: 'query' }) // /invoices?companyId=…
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function resolveScope(source: ScopeSource): ScopeResolver;
|
package/dist/scope.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** La ruta no es de ninguna compañía ni negocio: el permiso se comprueba en global. */
|
|
2
|
+
export const globalScope = () => ({ kind: 'global' });
|
|
3
|
+
const MAX_ID_LENGTH = 255;
|
|
4
|
+
/** Un identificador válido es un texto no vacío y corto: un arreglo (`?a=1&a=2`) o un objeto no. */
|
|
5
|
+
function readId(bag, name) {
|
|
6
|
+
const value = bag[name];
|
|
7
|
+
return typeof value === 'string' && value.length > 0 && value.length <= MAX_ID_LENGTH
|
|
8
|
+
? value
|
|
9
|
+
: undefined;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Lee el alcance de la ruta. **El identificador es lo que dice el cliente; no se confía en él**:
|
|
13
|
+
* `requirePermission` lo resuelve contra la base de datos (la compañía de un negocio sale de ahí)
|
|
14
|
+
* y, si no existe o no le corresponde, la respuesta es la misma que sin permiso.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* resolveScope({ company: 'companyId' }) // /companies/:companyId/invoices
|
|
18
|
+
* resolveScope({ company: 'companyId', business: 'businessId' }) // el negocio debe ser de esa compañía
|
|
19
|
+
* resolveScope({ company: 'companyId', from: 'query' }) // /invoices?companyId=…
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export function resolveScope(source) {
|
|
23
|
+
const from = source.from ?? 'params';
|
|
24
|
+
return (request) => {
|
|
25
|
+
const bag = request[from];
|
|
26
|
+
const company = source.company === undefined ? undefined : readId(bag, source.company);
|
|
27
|
+
const business = source.business === undefined ? undefined : readId(bag, source.business);
|
|
28
|
+
if (source.business !== undefined) {
|
|
29
|
+
// Si el parámetro no vino o no es un texto válido, se deniega.
|
|
30
|
+
if (business === undefined)
|
|
31
|
+
return { kind: 'invalid' };
|
|
32
|
+
if (source.company !== undefined && company === undefined)
|
|
33
|
+
return { kind: 'invalid' };
|
|
34
|
+
return {
|
|
35
|
+
kind: 'scope',
|
|
36
|
+
scope: { type: 'business', id: business },
|
|
37
|
+
...(company === undefined ? {} : { companyMustBe: company }),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
if (source.company !== undefined) {
|
|
41
|
+
return company === undefined
|
|
42
|
+
? { kind: 'invalid' }
|
|
43
|
+
: { kind: 'scope', scope: { type: 'company', id: company } };
|
|
44
|
+
}
|
|
45
|
+
return { kind: 'global' };
|
|
46
|
+
};
|
|
47
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teamblind/axeda-express",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-alpha.1",
|
|
4
|
+
"description": "Express helpers for Axeda: requirePermission() and resolveScope().",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "TeamBlind",
|
|
7
|
+
"homepage": "https://github.com/teamblindmx/axeda#readme",
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://github.com/teamblindmx/axeda/issues"
|
|
10
|
+
},
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/teamblindmx/axeda.git",
|
|
14
|
+
"directory": "packages/express"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"authorization",
|
|
18
|
+
"rbac",
|
|
19
|
+
"multi-tenant",
|
|
20
|
+
"better-auth",
|
|
21
|
+
"access-control"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"main": "./dist/index.js",
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE",
|
|
37
|
+
"NOTICE",
|
|
38
|
+
"CHANGELOG.md"
|
|
39
|
+
],
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public",
|
|
42
|
+
"provenance": true
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=22"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@teamblind/axeda-core": "^0.1.0-alpha.1"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"@types/express": "^5.0.0",
|
|
52
|
+
"express": "^5.0.0"
|
|
53
|
+
},
|
|
54
|
+
"peerDependenciesMeta": {
|
|
55
|
+
"@types/express": {
|
|
56
|
+
"optional": true
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|