@oxyhq/core 3.9.1 → 3.10.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/dist/cjs/.tsbuildinfo +1 -1
- package/dist/cjs/i18n/locales/en-US.json +9 -0
- package/dist/cjs/i18n/locales/es-ES.json +9 -0
- package/dist/cjs/i18n/locales/locales/en-US.json +9 -0
- package/dist/cjs/i18n/locales/locales/es-ES.json +9 -0
- package/dist/cjs/index.js +2 -3
- package/dist/cjs/mixins/OxyServices.assets.js +29 -6
- package/dist/cjs/mixins/OxyServices.utility.js +52 -23
- package/dist/cjs/server/cors.js +155 -0
- package/dist/cjs/server/index.js +21 -1
- package/dist/cjs/server/safeFetch.js +458 -0
- package/dist/cjs/server/verifySecret.js +50 -0
- package/dist/cjs/utils/fapiAutoDetect.js +12 -42
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/i18n/locales/en-US.json +9 -0
- package/dist/esm/i18n/locales/es-ES.json +9 -0
- package/dist/esm/i18n/locales/locales/en-US.json +9 -0
- package/dist/esm/i18n/locales/locales/es-ES.json +9 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/mixins/OxyServices.assets.js +29 -6
- package/dist/esm/mixins/OxyServices.utility.js +52 -23
- package/dist/esm/server/cors.js +152 -0
- package/dist/esm/server/index.js +6 -0
- package/dist/esm/server/safeFetch.js +447 -0
- package/dist/esm/server/verifySecret.js +47 -0
- package/dist/esm/utils/fapiAutoDetect.js +12 -41
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/mixins/OxyServices.assets.d.ts +6 -1
- package/dist/types/mixins/OxyServices.utility.d.ts +3 -3
- package/dist/types/server/cors.d.ts +57 -0
- package/dist/types/server/index.d.ts +5 -0
- package/dist/types/server/safeFetch.d.ts +135 -0
- package/dist/types/server/verifySecret.d.ts +29 -0
- package/dist/types/utils/fapiAutoDetect.d.ts +6 -23
- package/package.json +2 -1
- package/src/__tests__/authSocket.test.ts +96 -0
- package/src/i18n/locales/en-US.json +9 -0
- package/src/i18n/locales/es-ES.json +9 -0
- package/src/index.ts +1 -1
- package/src/mixins/OxyServices.assets.ts +40 -6
- package/src/mixins/OxyServices.utility.ts +57 -23
- package/src/mixins/__tests__/assetUpload.test.ts +191 -0
- package/src/mixins/__tests__/getFileDownloadUrl.test.ts +13 -0
- package/src/mixins/__tests__/serviceAuth.test.ts +30 -2
- package/src/server/__tests__/cors.test.ts +144 -0
- package/src/server/__tests__/safeFetch.test.ts +232 -0
- package/src/server/__tests__/verifySecret.test.ts +40 -0
- package/src/server/cors.ts +195 -0
- package/src/server/index.ts +30 -0
- package/src/server/safeFetch.ts +581 -0
- package/src/server/verifySecret.ts +52 -0
- package/src/utils/__tests__/fapiAutoDetect.test.ts +40 -11
- package/src/utils/fapiAutoDetect.ts +12 -39
|
@@ -129,6 +129,15 @@
|
|
|
129
129
|
"title": "Reputation = Trust & Growth",
|
|
130
130
|
"body": "Oxy Trust is a reputation system that reacts to what you do. Helpful, respectful, constructive actions earn it. Harmful or low‑effort stuff chips it away. More reputation can unlock benefits; low reputation can limit features. It keeps things fair and rewards real contribution."
|
|
131
131
|
},
|
|
132
|
+
"name": {
|
|
133
|
+
"title": "What's your name?",
|
|
134
|
+
"body": "Add your name so people know who you are.",
|
|
135
|
+
"firstLabel": "First name",
|
|
136
|
+
"firstPlaceholder": "Your first name",
|
|
137
|
+
"lastLabel": "Last name",
|
|
138
|
+
"lastPlaceholder": "Your last name",
|
|
139
|
+
"saveFailed": "Could not save your name"
|
|
140
|
+
},
|
|
132
141
|
"avatar": {
|
|
133
142
|
"title": "Make It Yours",
|
|
134
143
|
"body": "Add an avatar so people recognize you. It will show anywhere you show up here. Skip if you want — you can add it later.",
|
|
@@ -849,6 +849,15 @@
|
|
|
849
849
|
"title": "Reputación = Confianza y crecimiento",
|
|
850
850
|
"body": "Oxy Trust es un sistema de reputación que reacciona a lo que haces. Las acciones útiles, respetuosas y constructivas la aumentan. Las acciones dañinas o de poco esfuerzo la reducen. Más reputación puede desbloquear beneficios; poca reputación puede limitar funciones. Mantiene la justicia y recompensa la contribución real."
|
|
851
851
|
},
|
|
852
|
+
"name": {
|
|
853
|
+
"title": "¿Cuál es tu nombre?",
|
|
854
|
+
"body": "Añade tu nombre para que la gente sepa quién eres.",
|
|
855
|
+
"firstLabel": "Nombre",
|
|
856
|
+
"firstPlaceholder": "Tu nombre",
|
|
857
|
+
"lastLabel": "Apellidos",
|
|
858
|
+
"lastPlaceholder": "Tus apellidos",
|
|
859
|
+
"saveFailed": "No se pudo guardar tu nombre"
|
|
860
|
+
},
|
|
852
861
|
"avatar": {
|
|
853
862
|
"title": "Hazlo tuyo",
|
|
854
863
|
"body": "Añade un avatar para que te reconozcan. Se mostrará donde aparezcas aquí. Puedes omitirlo — puedes añadirlo más tarde.",
|
|
@@ -129,6 +129,15 @@
|
|
|
129
129
|
"title": "Reputation = Trust & Growth",
|
|
130
130
|
"body": "Oxy Trust is a reputation system that reacts to what you do. Helpful, respectful, constructive actions earn it. Harmful or low‑effort stuff chips it away. More reputation can unlock benefits; low reputation can limit features. It keeps things fair and rewards real contribution."
|
|
131
131
|
},
|
|
132
|
+
"name": {
|
|
133
|
+
"title": "What's your name?",
|
|
134
|
+
"body": "Add your name so people know who you are.",
|
|
135
|
+
"firstLabel": "First name",
|
|
136
|
+
"firstPlaceholder": "Your first name",
|
|
137
|
+
"lastLabel": "Last name",
|
|
138
|
+
"lastPlaceholder": "Your last name",
|
|
139
|
+
"saveFailed": "Could not save your name"
|
|
140
|
+
},
|
|
132
141
|
"avatar": {
|
|
133
142
|
"title": "Make It Yours",
|
|
134
143
|
"body": "Add an avatar so people recognize you. It will show anywhere you show up here. Skip if you want — you can add it later.",
|
|
@@ -849,6 +849,15 @@
|
|
|
849
849
|
"title": "Reputación = Confianza y crecimiento",
|
|
850
850
|
"body": "Oxy Trust es un sistema de reputación que reacciona a lo que haces. Las acciones útiles, respetuosas y constructivas la aumentan. Las acciones dañinas o de poco esfuerzo la reducen. Más reputación puede desbloquear beneficios; poca reputación puede limitar funciones. Mantiene la justicia y recompensa la contribución real."
|
|
851
851
|
},
|
|
852
|
+
"name": {
|
|
853
|
+
"title": "¿Cuál es tu nombre?",
|
|
854
|
+
"body": "Añade tu nombre para que la gente sepa quién eres.",
|
|
855
|
+
"firstLabel": "Nombre",
|
|
856
|
+
"firstPlaceholder": "Tu nombre",
|
|
857
|
+
"lastLabel": "Apellidos",
|
|
858
|
+
"lastPlaceholder": "Tus apellidos",
|
|
859
|
+
"saveFailed": "No se pudo guardar tu nombre"
|
|
860
|
+
},
|
|
852
861
|
"avatar": {
|
|
853
862
|
"title": "Hazlo tuyo",
|
|
854
863
|
"body": "Añade un avatar para que te reconozcan. Se mostrará donde aparezcas aquí. Puedes omitirlo — puedes añadirlo más tarde.",
|
package/dist/esm/index.js
CHANGED
|
@@ -104,7 +104,7 @@ export { buildAccountsArray, createQuickAccount, getAccountDisplayName, getAccou
|
|
|
104
104
|
// ---------------------------------------------------------------------------
|
|
105
105
|
// Cross-domain SSO infrastructure
|
|
106
106
|
// ---------------------------------------------------------------------------
|
|
107
|
-
export { autoDetectAuthWebUrl, registrableApex
|
|
107
|
+
export { autoDetectAuthWebUrl, registrableApex } from './utils/fapiAutoDetect.js';
|
|
108
108
|
// Central cross-domain SSO (opaque single-use code bounce via auth.oxy.so)
|
|
109
109
|
export { CENTRAL_AUTH_URL, CENTRAL_IDP_APEX, resolveCentralAuthUrl } from './utils/authWebUrl.js';
|
|
110
110
|
export { parseSsoReturnFragment, consumeSsoReturn } from './utils/ssoReturn.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isReactNative } from '../utils/platform.js';
|
|
1
2
|
export function OxyServicesAssetsMixin(Base) {
|
|
2
3
|
return class extends Base {
|
|
3
4
|
constructor(...args) {
|
|
@@ -40,8 +41,8 @@ export function OxyServicesAssetsMixin(Base) {
|
|
|
40
41
|
*
|
|
41
42
|
* For a CDN-signed URL fetched from the API, use {@link getFileDownloadUrlAsync}.
|
|
42
43
|
*/
|
|
43
|
-
getFileDownloadUrl(fileId, variant, expiresIn) {
|
|
44
|
-
const token = this.getClient().getAccessToken();
|
|
44
|
+
getFileDownloadUrl(fileId, variant, expiresIn, options = {}) {
|
|
45
|
+
const token = options.omitToken ? undefined : this.getClient().getAccessToken();
|
|
45
46
|
// Public case: no auth token and no expiry requested → clean CDN URL.
|
|
46
47
|
// CloudFront serves the public media origin under `${cloudURL}/<id>`.
|
|
47
48
|
if (!token && !expiresIn) {
|
|
@@ -189,10 +190,32 @@ export function OxyServicesAssetsMixin(Base) {
|
|
|
189
190
|
formData.append('file', file, fileName);
|
|
190
191
|
}
|
|
191
192
|
else if ('uri' in file && typeof file.uri === 'string') {
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
193
|
+
const descriptor = file;
|
|
194
|
+
if (isReactNative()) {
|
|
195
|
+
// React Native file descriptor — RN's FormData handles {uri, type, name} natively.
|
|
196
|
+
// It reads the file from disk during the multipart request — no in-JS Blob
|
|
197
|
+
// conversion (which would fail on Hermes for ArrayBuffer-backed Blobs).
|
|
198
|
+
formData.append('file', descriptor, fileName);
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
// Web (browser/Node): the browser's FormData cannot read bytes from a plain
|
|
202
|
+
// { uri } object — it would serialize "[object Object]" and the server would
|
|
203
|
+
// store a 0-byte asset. Materialize the uri into a real Blob first. `fetch`
|
|
204
|
+
// resolves blob:, data:, and http(s): uris on web, so all picker outputs work.
|
|
205
|
+
const res = await fetch(descriptor.uri);
|
|
206
|
+
if (!res.ok) {
|
|
207
|
+
throw new Error(`Failed to read file from uri (status ${res.status})`);
|
|
208
|
+
}
|
|
209
|
+
const fetched = await res.blob();
|
|
210
|
+
// Preserve the descriptor's declared MIME type when the fetched blob has none.
|
|
211
|
+
const blob = fetched.type === '' && descriptor.type
|
|
212
|
+
? new Blob([fetched], { type: descriptor.type })
|
|
213
|
+
: fetched;
|
|
214
|
+
if (blob.size === 0) {
|
|
215
|
+
throw new Error('Cannot upload an empty file');
|
|
216
|
+
}
|
|
217
|
+
formData.append('file', blob, fileName);
|
|
218
|
+
}
|
|
196
219
|
}
|
|
197
220
|
else {
|
|
198
221
|
throw new Error('Unsupported file input: expected File, Blob, or { uri, type?, name?, size? } descriptor');
|
|
@@ -688,33 +688,45 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
688
688
|
}
|
|
689
689
|
return next(new Error('Invalid token'));
|
|
690
690
|
}
|
|
691
|
-
const
|
|
692
|
-
if (!
|
|
691
|
+
const claimedUserId = decoded.userId || decoded.id;
|
|
692
|
+
if (!claimedUserId) {
|
|
693
693
|
return next(new Error('Invalid token payload'));
|
|
694
694
|
}
|
|
695
695
|
// Check expiration — reject tokens at exact expiry second (use <=)
|
|
696
696
|
if (decoded.exp && decoded.exp <= Math.floor(Date.now() / 1000)) {
|
|
697
697
|
return next(new Error('Token expired'));
|
|
698
698
|
}
|
|
699
|
-
//
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
699
|
+
// A server-validated session is mandatory. A bare decoded JWT proves
|
|
700
|
+
// nothing — the signature is not verified here, so without a session
|
|
701
|
+
// round-trip a forged token could claim any user id.
|
|
702
|
+
if (!decoded.sessionId) {
|
|
703
|
+
return next(new Error('Session required'));
|
|
704
|
+
}
|
|
705
|
+
let userId = claimedUserId;
|
|
706
|
+
try {
|
|
707
|
+
const result = await oxyInstance.validateSession(decoded.sessionId, {
|
|
708
|
+
useHeaderValidation: true,
|
|
709
|
+
});
|
|
710
|
+
if (!result || !result.valid || !result.user) {
|
|
711
|
+
return next(new Error('Session invalid'));
|
|
708
712
|
}
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
}
|
|
716
|
-
return next(new Error('Session validation failed'));
|
|
713
|
+
// The session is the source of truth. The client-claimed user id
|
|
714
|
+
// must match the server-validated identity, otherwise a valid
|
|
715
|
+
// session could be paired with a forged user id.
|
|
716
|
+
const validatedUserId = getUserIdentityId(result.user);
|
|
717
|
+
if (!validatedUserId || validatedUserId !== claimedUserId) {
|
|
718
|
+
return next(new Error('Session user mismatch'));
|
|
717
719
|
}
|
|
720
|
+
userId = validatedUserId;
|
|
721
|
+
}
|
|
722
|
+
catch (validateErr) {
|
|
723
|
+
if (debug) {
|
|
724
|
+
logger.debug('[oxy.authSocket] Session validation failed', {
|
|
725
|
+
component: 'auth',
|
|
726
|
+
method: 'authSocket',
|
|
727
|
+
}, validateErr);
|
|
728
|
+
}
|
|
729
|
+
return next(new Error('Session validation failed'));
|
|
718
730
|
}
|
|
719
731
|
// Attach user data to socket. We expose BOTH `socket.data.userId`
|
|
720
732
|
// (the official Socket.IO data slot) and `socket.user` because
|
|
@@ -779,9 +791,9 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
779
791
|
* Express.js middleware that enforces a specific service-token scope.
|
|
780
792
|
*
|
|
781
793
|
* Mount AFTER `auth()` / `serviceAuth()` — relies on `req.serviceApp` and
|
|
782
|
-
* (when delegation is in effect) `req.serviceActingAs.scopes`.
|
|
783
|
-
*
|
|
784
|
-
* the app
|
|
794
|
+
* (when delegation is in effect) `req.serviceActingAs.scopes`. App-only
|
|
795
|
+
* service requests require the app scope. Delegated user requests require
|
|
796
|
+
* BOTH the app scope and the per-user delegation scope.
|
|
785
797
|
*
|
|
786
798
|
* Requests authenticated as a regular user (no service token) are rejected
|
|
787
799
|
* with 403 — scope-protected endpoints are service-to-service by design.
|
|
@@ -811,7 +823,12 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
811
823
|
});
|
|
812
824
|
return;
|
|
813
825
|
}
|
|
814
|
-
|
|
826
|
+
const appHasScope = appScopes.includes(scope);
|
|
827
|
+
const delegationHasScope = delegatedScopes.includes(scope);
|
|
828
|
+
const hasRequiredScope = req.serviceActingAs
|
|
829
|
+
? appHasScope && delegationHasScope
|
|
830
|
+
: appHasScope;
|
|
831
|
+
if (hasRequiredScope) {
|
|
815
832
|
next();
|
|
816
833
|
return;
|
|
817
834
|
}
|
|
@@ -869,6 +886,18 @@ async function verifyServiceTokenSignature(token, secret) {
|
|
|
869
886
|
* access token signed by the same shared secret could be replayed as a
|
|
870
887
|
* service token because no claim binding existed.
|
|
871
888
|
*/
|
|
889
|
+
/**
|
|
890
|
+
* Resolve the canonical user id from a validated session's user object.
|
|
891
|
+
*
|
|
892
|
+
* The API serializer emits `id`, but some upstream shapes carry the raw Mongo
|
|
893
|
+
* `_id` instead. We accept either, but only a non-empty string — anything else
|
|
894
|
+
* means the validated identity is unusable and the caller must reject.
|
|
895
|
+
*/
|
|
896
|
+
function getUserIdentityId(user) {
|
|
897
|
+
const candidate = user.id
|
|
898
|
+
?? user._id;
|
|
899
|
+
return typeof candidate === 'string' && candidate.length > 0 ? candidate : null;
|
|
900
|
+
}
|
|
872
901
|
function verifyServiceTokenClaims(decoded, expected) {
|
|
873
902
|
if (decoded.type !== 'service') {
|
|
874
903
|
throw new ServiceTokenClaimError(`Service token has unexpected type '${String(decoded.type)}'`);
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strict CORS allowlist for Oxy backends.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS EXISTS
|
|
5
|
+
* ---------------
|
|
6
|
+
* App backends kept hand-rolling CORS, and the unsafe patterns recurred:
|
|
7
|
+
* - `Access-Control-Allow-Origin: *` together with credentials (which is
|
|
8
|
+
* spec-invalid AND a credential-leak vector), or
|
|
9
|
+
* - a "reflect whatever Origin the request carried" fallback (effectively
|
|
10
|
+
* `*` for credentialed requests — the Allo wildcard-fallback class).
|
|
11
|
+
*
|
|
12
|
+
* `createOxyCors` returns a self-contained Express middleware (no `cors`
|
|
13
|
+
* package dependency) that:
|
|
14
|
+
* - allows the Oxy apex origin family (anything under `*.${CENTRAL_IDP_APEX}`,
|
|
15
|
+
* i.e. `oxy.so` — covering `auth.oxy.so`, `api.oxy.so`, `accounts.oxy.so`,
|
|
16
|
+
* `console.oxy.so`, `inbox.oxy.so`, the marketing site, …) reusing the
|
|
17
|
+
* central-origin constants already in core, NOT a fresh hardcoded list,
|
|
18
|
+
* - allows the caller's explicit `appOrigins`,
|
|
19
|
+
* - DENIES everything else (no reflection, never a wildcard with credentials),
|
|
20
|
+
* - echoes back the EXACT matched origin (so credentialed requests work) and
|
|
21
|
+
* sets `Vary: Origin` for correct caching,
|
|
22
|
+
* - answers CORS preflight (`OPTIONS`) with `204`.
|
|
23
|
+
*
|
|
24
|
+
* Node/Express-only: exported solely from `@oxyhq/core/server`.
|
|
25
|
+
*/
|
|
26
|
+
import { CENTRAL_IDP_APEX } from '../utils/authWebUrl.js';
|
|
27
|
+
import { registrableApex } from '../utils/fapiAutoDetect.js';
|
|
28
|
+
/** Default HTTP methods allowed across origins. */
|
|
29
|
+
const DEFAULT_ALLOWED_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'];
|
|
30
|
+
/** Default request headers a browser may send on a credentialed cross-origin call. */
|
|
31
|
+
const DEFAULT_ALLOWED_HEADERS = [
|
|
32
|
+
'Content-Type',
|
|
33
|
+
'Authorization',
|
|
34
|
+
'X-Requested-With',
|
|
35
|
+
'X-Oxy-User-Id',
|
|
36
|
+
'X-Oxy-Internal',
|
|
37
|
+
'X-CSRF-Token',
|
|
38
|
+
];
|
|
39
|
+
/** How long (seconds) a browser may cache a successful preflight. */
|
|
40
|
+
const DEFAULT_MAX_AGE_SECONDS = 86400;
|
|
41
|
+
/**
|
|
42
|
+
* Whether `candidate` belongs to the Oxy apex origin family — i.e. its
|
|
43
|
+
* registrable apex equals {@link CENTRAL_IDP_APEX} (`oxy.so`). This matches the
|
|
44
|
+
* apex itself (`https://oxy.so`) and any subdomain (`https://auth.oxy.so`,
|
|
45
|
+
* `https://api.oxy.so`, …) over http or https, ports allowed. Returns false on
|
|
46
|
+
* any parse failure (fail closed).
|
|
47
|
+
*/
|
|
48
|
+
function isOxyFamilyOrigin(candidate) {
|
|
49
|
+
let hostname;
|
|
50
|
+
let protocol;
|
|
51
|
+
try {
|
|
52
|
+
const url = new URL(candidate);
|
|
53
|
+
hostname = url.hostname.toLowerCase();
|
|
54
|
+
protocol = url.protocol;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
if (protocol !== 'https:' && protocol !== 'http:')
|
|
60
|
+
return false;
|
|
61
|
+
if (hostname === CENTRAL_IDP_APEX)
|
|
62
|
+
return true;
|
|
63
|
+
return registrableApex(hostname) === CENTRAL_IDP_APEX;
|
|
64
|
+
}
|
|
65
|
+
/** Normalize a raw origin string to its canonical `scheme://host[:port]` form. */
|
|
66
|
+
function normalizeOrigin(raw) {
|
|
67
|
+
try {
|
|
68
|
+
return new URL(raw).origin;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Build the origin-matching predicate: true iff `origin` is in the Oxy apex
|
|
76
|
+
* family OR exactly matches one of the configured app origins.
|
|
77
|
+
*/
|
|
78
|
+
function buildOriginAllowed(appOrigins) {
|
|
79
|
+
const explicit = new Set();
|
|
80
|
+
for (const raw of appOrigins) {
|
|
81
|
+
const normalized = normalizeOrigin(raw);
|
|
82
|
+
if (normalized)
|
|
83
|
+
explicit.add(normalized);
|
|
84
|
+
}
|
|
85
|
+
return (origin) => {
|
|
86
|
+
const normalized = normalizeOrigin(origin);
|
|
87
|
+
if (normalized === null)
|
|
88
|
+
return false;
|
|
89
|
+
if (explicit.has(normalized))
|
|
90
|
+
return true;
|
|
91
|
+
return isOxyFamilyOrigin(normalized);
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Create a strict Oxy CORS middleware. See module docs.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* app.use(createOxyCors({ appOrigins: ['https://app.example.com'] }));
|
|
100
|
+
* ```
|
|
101
|
+
*/
|
|
102
|
+
export function createOxyCors(options = {}) {
|
|
103
|
+
const { appOrigins = [], allowCredentials = true, methods = DEFAULT_ALLOWED_METHODS, allowedHeaders = DEFAULT_ALLOWED_HEADERS, exposedHeaders = [], maxAgeSeconds = DEFAULT_MAX_AGE_SECONDS, } = options;
|
|
104
|
+
const isOriginAllowed = buildOriginAllowed(appOrigins);
|
|
105
|
+
const methodsHeader = methods.join(', ');
|
|
106
|
+
const allowedHeadersHeader = allowedHeaders.join(', ');
|
|
107
|
+
const exposedHeadersHeader = exposedHeaders.join(', ');
|
|
108
|
+
return (req, res, next) => {
|
|
109
|
+
const origin = req.headers.origin;
|
|
110
|
+
// Same-origin or non-browser requests carry no Origin header — pass through
|
|
111
|
+
// untouched (no ACAO header is emitted, which is correct for them).
|
|
112
|
+
if (typeof origin !== 'string' || origin.length === 0) {
|
|
113
|
+
if (req.method === 'OPTIONS') {
|
|
114
|
+
res.sendStatus(204);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
next();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
// Origin is present. Caching correctness: this response varies by Origin.
|
|
121
|
+
res.setHeader('Vary', 'Origin');
|
|
122
|
+
if (!isOriginAllowed(origin)) {
|
|
123
|
+
// DENY: do NOT reflect the origin, do NOT emit a wildcard. The browser
|
|
124
|
+
// will block the cross-origin read. Preflights for denied origins get a
|
|
125
|
+
// 204 with no CORS headers (the actual request then fails CORS).
|
|
126
|
+
if (req.method === 'OPTIONS') {
|
|
127
|
+
res.sendStatus(204);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
next();
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
// ALLOW: echo the EXACT matched origin — never `*`, even without credentials.
|
|
134
|
+
res.setHeader('Access-Control-Allow-Origin', origin);
|
|
135
|
+
if (allowCredentials) {
|
|
136
|
+
res.setHeader('Access-Control-Allow-Credentials', 'true');
|
|
137
|
+
}
|
|
138
|
+
if (exposedHeadersHeader) {
|
|
139
|
+
res.setHeader('Access-Control-Expose-Headers', exposedHeadersHeader);
|
|
140
|
+
}
|
|
141
|
+
if (req.method === 'OPTIONS') {
|
|
142
|
+
res.setHeader('Access-Control-Allow-Methods', methodsHeader);
|
|
143
|
+
// Honour the browser's requested headers when present, else the default set.
|
|
144
|
+
const requested = req.headers['access-control-request-headers'];
|
|
145
|
+
res.setHeader('Access-Control-Allow-Headers', typeof requested === 'string' && requested.length > 0 ? requested : allowedHeadersHeader);
|
|
146
|
+
res.setHeader('Access-Control-Max-Age', String(maxAgeSeconds));
|
|
147
|
+
res.sendStatus(204);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
next();
|
|
151
|
+
};
|
|
152
|
+
}
|
package/dist/esm/server/index.js
CHANGED
|
@@ -16,3 +16,9 @@
|
|
|
16
16
|
*/
|
|
17
17
|
export { createOptionalOxyAuth, createOxyAuthMiddleware, getOxyUserId, getRequiredOxyUserId, isOxyAuthenticated, requireOxyAuth, } from './auth.js';
|
|
18
18
|
export { createOxyRateLimit } from './rateLimit.js';
|
|
19
|
+
// SSRF-safe upstream fetch + URL validation (Node-only).
|
|
20
|
+
export { assertSafePublicUrl, isBlockedIp, safeFetch, SsrfRejection, UpstreamError, ALLOWED_PORTS, ALLOWED_PROTOCOLS, BLOCKED_HOSTNAMES, DEFAULT_USER_AGENT, MAX_REDIRECTS, MAX_URL_LENGTH, UPSTREAM_HEADERS_TIMEOUT_MS, } from './safeFetch.js';
|
|
21
|
+
// Strict CORS allowlist (Oxy apex family + explicit app origins).
|
|
22
|
+
export { createOxyCors } from './cors.js';
|
|
23
|
+
// Constant-time secret comparison.
|
|
24
|
+
export { verifySecret } from './verifySecret.js';
|