@emoney-bff/next-bff 0.0.0-stage → 0.1.0
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/README.md +53 -2
- package/dist/client-ip.d.ts +1 -0
- package/dist/client-ip.js +18 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/proxy.d.ts +38 -0
- package/dist/proxy.js +81 -0
- package/package.json +30 -4
package/README.md
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @emoney-bff/next-bff
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Secure backend-for-frontend (BFF) proxy for emoney Next.js apps. The browser calls
|
|
4
|
+
`/api/proxy/<backend path>` on its own origin; the Next server adds the user's token and the
|
|
5
|
+
app's credentials and forwards the request. The token and app key never reach the browser.
|
|
6
|
+
|
|
7
|
+
## What it enforces
|
|
8
|
+
- **Path:** each segment is `[A-Za-z0-9_.+=-]`, no `.`/`..`/`--`, so requests can't leave the backend prefix or carry injection characters.
|
|
9
|
+
- **CSRF:** every non-GET request must be `application/json`.
|
|
10
|
+
- **Session:** no token → 401. A backend 401/403 ends the session (`clearSessionCookies`), except paths marked as business 403s.
|
|
11
|
+
- **Request headers:** only `accept`, `accept-language`, `content-type`, `lang`, `user-agent` reach the backend, plus `access_token`, `app_key`, `domain`, `client_ip` set by the proxy. Cookies and client-sent `client_ip`/`access_token` are dropped.
|
|
12
|
+
- **Response headers:** only `content-type` and `content-disposition` reach the browser.
|
|
13
|
+
- **Errors:** timeout → 504, unreachable → 502, with no internal details. Use `onError` to report them.
|
|
14
|
+
- **Client IP:** `clientIp(headers)` returns the right-most public `X-Forwarded-For` hop. The left-most hop is client-controlled.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
```
|
|
18
|
+
bun add @emoney-bff/next-bff
|
|
19
|
+
```
|
|
20
|
+
It is a public npm package, so no token or `.npmrc` is needed.
|
|
21
|
+
|
|
22
|
+
## Use
|
|
23
|
+
`app/api/proxy/[...path]/route.ts`:
|
|
24
|
+
```ts
|
|
25
|
+
import { createBackendProxy } from '@emoney-bff/next-bff';
|
|
26
|
+
|
|
27
|
+
const proxy = createBackendProxy({
|
|
28
|
+
baseUrl: process.env.EMONEY_API_URL!,
|
|
29
|
+
appKey: process.env.APP_KEY!, // server-only env, never NEXT_PUBLIC_
|
|
30
|
+
domain: process.env.APP_DOMAIN!,
|
|
31
|
+
getAccessToken: async (req) => /* read it from your httpOnly session cookie */,
|
|
32
|
+
clearSessionCookies: ['session=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax'],
|
|
33
|
+
isBusiness403: (path) => path.startsWith('travel_rule/'),
|
|
34
|
+
onError: (error, ctx) => Sentry.captureException(error, { tags: ctx }),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export const GET = proxy.GET;
|
|
38
|
+
export const POST = proxy.POST;
|
|
39
|
+
export const PUT = proxy.PUT;
|
|
40
|
+
export const PATCH = proxy.PATCH;
|
|
41
|
+
export const DELETE = proxy.DELETE;
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Develop and release
|
|
45
|
+
```
|
|
46
|
+
npm install
|
|
47
|
+
npm test
|
|
48
|
+
```
|
|
49
|
+
To release (needs an npm account in the `emoney-bff` org and 2FA):
|
|
50
|
+
```
|
|
51
|
+
npm version patch # or minor / major; commits and tags
|
|
52
|
+
npm publish # runs tests, typecheck and build first
|
|
53
|
+
git push --follow-tags
|
|
54
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function clientIp(headers: Headers): string;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Our own hops (load balancer, ingress, the Next server) are on private networks, so reading
|
|
2
|
+
// X-Forwarded-For from the right, the first public address is the client. Anything left of it
|
|
3
|
+
// was sent by the client and can be faked, which is why the left-most entry must never be used.
|
|
4
|
+
// 100.64/10 is included because EKS custom networking puts pods there.
|
|
5
|
+
const PRIVATE = /^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.|::1$|f[cd][0-9a-f]{0,2}:|fe80:)/i;
|
|
6
|
+
// ponytail: assumes every proxy in front of the app has a private IP. With CloudFront in front,
|
|
7
|
+
// read `cloudfront-viewer-address` instead (its right-most hop is a public edge IP).
|
|
8
|
+
export function clientIp(headers) {
|
|
9
|
+
const hops = (headers.get('x-forwarded-for') ?? '')
|
|
10
|
+
.split(',')
|
|
11
|
+
.map((hop) => hop.trim().replace(/^::ffff:/i, ''))
|
|
12
|
+
.filter(Boolean);
|
|
13
|
+
for (let i = hops.length - 1; i >= 0; i--) {
|
|
14
|
+
if (!PRIVATE.test(hops[i]))
|
|
15
|
+
return hops[i];
|
|
16
|
+
}
|
|
17
|
+
return hops[0] ?? '127.0.0.1';
|
|
18
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/proxy.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export type BackendProxyOptions = {
|
|
2
|
+
/** Backend prefix every request stays under, e.g. `https://api.example.com/api`. */
|
|
3
|
+
baseUrl: string;
|
|
4
|
+
appKey: string;
|
|
5
|
+
domain: string;
|
|
6
|
+
/** The signed-in user's backend token, or null/undefined when there is no session. */
|
|
7
|
+
getAccessToken(request: Request): Promise<string | null | undefined>;
|
|
8
|
+
/** Set-Cookie values that end the session. Sent when there is no token or the backend rejects it. */
|
|
9
|
+
clearSessionCookies?: string[];
|
|
10
|
+
/** A 403 from these paths is business state, not an expired session. */
|
|
11
|
+
isBusiness403?(path: string): boolean;
|
|
12
|
+
/** Reports network failures and timeouts (e.g. to Sentry). Details never reach the browser. */
|
|
13
|
+
onError?(error: unknown, context: {
|
|
14
|
+
method: string;
|
|
15
|
+
path: string;
|
|
16
|
+
}): void;
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
};
|
|
19
|
+
export type ProxyRouteContext = {
|
|
20
|
+
params: Promise<{
|
|
21
|
+
path: string[];
|
|
22
|
+
}>;
|
|
23
|
+
};
|
|
24
|
+
export type ProxyHandler = (request: Request, context: ProxyRouteContext) => Promise<Response>;
|
|
25
|
+
/** True when the path cannot leave the backend prefix or carry injection characters. */
|
|
26
|
+
export declare function isSafePath(segments: readonly string[]): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Route handlers for `app/api/<name>/[...path]/route.ts`:
|
|
29
|
+
* `/api/<name>/user/balance?x=1` → `<baseUrl>/user/balance?x=1`, with the user's token and the
|
|
30
|
+
* app's credentials added on the server.
|
|
31
|
+
*/
|
|
32
|
+
export declare function createBackendProxy(options: BackendProxyOptions): {
|
|
33
|
+
GET: ProxyHandler;
|
|
34
|
+
POST: ProxyHandler;
|
|
35
|
+
PUT: ProxyHandler;
|
|
36
|
+
PATCH: ProxyHandler;
|
|
37
|
+
DELETE: ProxyHandler;
|
|
38
|
+
};
|
package/dist/proxy.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { clientIp } from "./client-ip.js";
|
|
2
|
+
// Browser headers the backend may see. Cookies, Authorization, X-Forwarded-*, client_ip,
|
|
3
|
+
// access_token, app_key… are all dropped: the backend only gets what this proxy sets.
|
|
4
|
+
const FORWARDED_REQUEST_HEADERS = ['accept', 'accept-language', 'content-type', 'lang', 'user-agent'];
|
|
5
|
+
// Backend headers the browser may see. Set-Cookie, Server, CORS headers… are dropped.
|
|
6
|
+
const RETURNED_RESPONSE_HEADERS = ['content-type', 'content-disposition'];
|
|
7
|
+
// One path segment: ids, codes, base64-like tokens. No '/', '%', spaces, quotes or ';'.
|
|
8
|
+
const SAFE_SEGMENT = /^[A-Za-z0-9_.+=-]+$/;
|
|
9
|
+
/** True when the path cannot leave the backend prefix or carry injection characters. */
|
|
10
|
+
export function isSafePath(segments) {
|
|
11
|
+
return (segments.length > 0 &&
|
|
12
|
+
segments.every((s) => SAFE_SEGMENT.test(s) && s !== '.' && s !== '..' && !s.includes('--')));
|
|
13
|
+
}
|
|
14
|
+
function json(status, body, cookies = []) {
|
|
15
|
+
const headers = new Headers({ 'content-type': 'application/json' });
|
|
16
|
+
for (const cookie of cookies)
|
|
17
|
+
headers.append('set-cookie', cookie);
|
|
18
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Route handlers for `app/api/<name>/[...path]/route.ts`:
|
|
22
|
+
* `/api/<name>/user/balance?x=1` → `<baseUrl>/user/balance?x=1`, with the user's token and the
|
|
23
|
+
* app's credentials added on the server.
|
|
24
|
+
*/
|
|
25
|
+
export function createBackendProxy(options) {
|
|
26
|
+
const base = options.baseUrl.replace(/\/+$/, '');
|
|
27
|
+
const endSession = options.clearSessionCookies ?? [];
|
|
28
|
+
const handle = async (request, { params }) => {
|
|
29
|
+
const { method } = request;
|
|
30
|
+
const segments = (await params).path ?? [];
|
|
31
|
+
const path = segments.join('/');
|
|
32
|
+
if (!isSafePath(segments))
|
|
33
|
+
return json(400, { error: 'Invalid request' });
|
|
34
|
+
// A cross-site form can only send form or text bodies. Requiring JSON forces a CORS
|
|
35
|
+
// preflight, which this route never answers.
|
|
36
|
+
if (method !== 'GET' && !request.headers.get('content-type')?.includes('application/json')) {
|
|
37
|
+
return json(415, { error: 'Unsupported media type' });
|
|
38
|
+
}
|
|
39
|
+
const accessToken = await options.getAccessToken(request);
|
|
40
|
+
if (!accessToken)
|
|
41
|
+
return json(401, { error: 'Unauthorized' }, endSession);
|
|
42
|
+
const headers = new Headers();
|
|
43
|
+
for (const name of FORWARDED_REQUEST_HEADERS) {
|
|
44
|
+
const value = request.headers.get(name);
|
|
45
|
+
if (value)
|
|
46
|
+
headers.set(name, value);
|
|
47
|
+
}
|
|
48
|
+
headers.set('access_token', accessToken);
|
|
49
|
+
headers.set('app_key', options.appKey);
|
|
50
|
+
headers.set('domain', options.domain);
|
|
51
|
+
headers.set('client_ip', clientIp(request.headers));
|
|
52
|
+
let upstream;
|
|
53
|
+
try {
|
|
54
|
+
const body = method === 'GET' ? undefined : (await request.text()) || undefined;
|
|
55
|
+
upstream = await fetch(`${base}/${path}${new URL(request.url).search}`, {
|
|
56
|
+
method,
|
|
57
|
+
headers,
|
|
58
|
+
body,
|
|
59
|
+
cache: 'no-store',
|
|
60
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
options.onError?.(error, { method, path });
|
|
65
|
+
const timedOut = error instanceof Error && error.name === 'TimeoutError';
|
|
66
|
+
return json(timedOut ? 504 : 502, { error: timedOut ? 'Upstream timeout' : 'Upstream unavailable' });
|
|
67
|
+
}
|
|
68
|
+
const responseHeaders = new Headers();
|
|
69
|
+
for (const name of RETURNED_RESPONSE_HEADERS) {
|
|
70
|
+
const value = upstream.headers.get(name);
|
|
71
|
+
if (value)
|
|
72
|
+
responseHeaders.set(name, value);
|
|
73
|
+
}
|
|
74
|
+
const sessionRejected = upstream.status === 401 || (upstream.status === 403 && !options.isBusiness403?.(path));
|
|
75
|
+
if (sessionRejected)
|
|
76
|
+
for (const cookie of endSession)
|
|
77
|
+
responseHeaders.append('set-cookie', cookie);
|
|
78
|
+
return new Response(upstream.body, { status: upstream.status, headers: responseHeaders });
|
|
79
|
+
};
|
|
80
|
+
return { GET: handle, POST: handle, PUT: handle, PATCH: handle, DELETE: handle };
|
|
81
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@emoney-bff/next-bff",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Secure backend-for-frontend proxy and client-IP helper for emoney Next.js apps",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=22.18"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "tsc",
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"test": "node --test src/*.test.ts",
|
|
23
|
+
"prepublishOnly": "npm test && npm run typecheck && npm run build"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^26.6.11",
|
|
27
|
+
"typescript": "~5.9.3"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
}
|
|
32
|
+
}
|