@bostonuniversity/edge-origin-trust 0.0.0-stage → 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 +338 -0
- package/README.md +281 -2
- package/dist/allowList.d.ts +55 -0
- package/dist/allowList.js +151 -0
- package/dist/allowList.js.map +1 -0
- package/dist/cdk/EdgeOriginApp.d.ts +128 -0
- package/dist/cdk/EdgeOriginApp.js +139 -0
- package/dist/cdk/EdgeOriginApp.js.map +1 -0
- package/dist/challengeCache.d.ts +39 -0
- package/dist/challengeCache.js +77 -0
- package/dist/challengeCache.js.map +1 -0
- package/dist/gate.d.ts +83 -0
- package/dist/gate.js +119 -0
- package/dist/gate.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +40 -0
- package/dist/index.js.map +1 -0
- package/dist/responses.d.ts +64 -0
- package/dist/responses.js +103 -0
- package/dist/responses.js.map +1 -0
- package/dist/spa.d.ts +43 -0
- package/dist/spa.js +192 -0
- package/dist/spa.js.map +1 -0
- package/dist/trustBoundary.d.ts +69 -0
- package/dist/trustBoundary.js +159 -0
- package/dist/trustBoundary.js.map +1 -0
- package/dist/types.d.ts +26 -0
- package/dist/types.js +7 -0
- package/dist/types.js.map +1 -0
- package/fixtures/eppn.vectors.json +68 -0
- package/package.json +66 -4
package/dist/gate.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { ChallengeCache } from './challengeCache';
|
|
2
|
+
/** Default name of the shared-secret header the edge injects. */
|
|
3
|
+
export declare const CHALLENGE_HEADER_DEFAULT = "cloudfront-challenge";
|
|
4
|
+
/** Default name of the cookie carrying the session JWT. The edge's own literal. */
|
|
5
|
+
export declare const TOKEN_COOKIE_DEFAULT = "auth-token-cookie";
|
|
6
|
+
/**
|
|
7
|
+
* Error codes, deliberately distinct at their respective statuses. `forbidden` means "you did not
|
|
8
|
+
* transit the edge"; `unauthenticated` means "you did, but nobody is logged in". A consuming app's
|
|
9
|
+
* own authorization refusal is a third thing again (`not_authorized` at 403) — see the app's write
|
|
10
|
+
* surfaces. Collapsing any two of these makes an operator's failure indistinguishable from an
|
|
11
|
+
* attacker's.
|
|
12
|
+
*/
|
|
13
|
+
export declare const GATE_ERRORS: {
|
|
14
|
+
readonly forbidden: "forbidden";
|
|
15
|
+
readonly unauthenticated: "unauthenticated";
|
|
16
|
+
};
|
|
17
|
+
/** Who the edge says this is. Only produced once both doors are closed. */
|
|
18
|
+
export interface EdgeIdentity {
|
|
19
|
+
/** The decoded `user-details` payload, or null if absent/undecodable. */
|
|
20
|
+
userDetails: unknown;
|
|
21
|
+
/** The eppn — the allow-list key — or null if the payload carries no principal. */
|
|
22
|
+
eppn: string | null;
|
|
23
|
+
}
|
|
24
|
+
export interface TrustedEdgeConfig<R> {
|
|
25
|
+
/** The runtime challenge-secret cache. Its TTL is what makes rotation redeploy-free. */
|
|
26
|
+
challengeCache: ChallengeCache;
|
|
27
|
+
/** Header name carrying the shared secret. Defaults to the edge's own literal. */
|
|
28
|
+
challengeHeader?: string;
|
|
29
|
+
/** Build a JSON response. The module composes its own status/body pairs through this. */
|
|
30
|
+
json: (statusCode: number, body: unknown) => R;
|
|
31
|
+
/**
|
|
32
|
+
* The refusal for a request that transited the edge but carries no session. A 401, never a
|
|
33
|
+
* redirect.
|
|
34
|
+
*
|
|
35
|
+
* The app supplies the whole decision because only it knows its own request taxonomy, and that
|
|
36
|
+
* taxonomy has at least three arms once a bundle is involved:
|
|
37
|
+
*
|
|
38
|
+
* unauthenticated: (p) =>
|
|
39
|
+
* p.includes('/api/') || isAssetRequest(p) // isAssetRequest is exported from ./spa
|
|
40
|
+
* ? json(401, { error: GATE_ERRORS.unauthenticated })
|
|
41
|
+
* : loginPage(p)
|
|
42
|
+
*
|
|
43
|
+
* A two-arm predicate — API path or not — is one arm too few, and naming it after APIs is what
|
|
44
|
+
* makes the third easy to miss: an expired session requesting a hashed bundle would be handed an
|
|
45
|
+
* HTML document, the same shape as the defect `spa.ts` exists to prevent, one status code away.
|
|
46
|
+
* Hence a whole decision rather than a predicate.
|
|
47
|
+
*/
|
|
48
|
+
unauthenticated: (rawPath: string) => R;
|
|
49
|
+
/**
|
|
50
|
+
* Verify the session JWT rather than taking `authenticated: true` on trust. Opt-in.
|
|
51
|
+
*
|
|
52
|
+
* The key is public, so it can come from wherever suits the consumer. `createChallengeCache` will
|
|
53
|
+
* serve it from the same secret and TTL as the challenge:
|
|
54
|
+
*
|
|
55
|
+
* verifyToken: { publicKey: () => challengeCache.getPublicKey() }
|
|
56
|
+
*
|
|
57
|
+
* Fails closed: a missing cookie, an absent key, or a bad signature all refuse the request. There
|
|
58
|
+
* is deliberately no fallback to the header — a silent one would be undetectable from outside.
|
|
59
|
+
*/
|
|
60
|
+
verifyToken?: {
|
|
61
|
+
/** PEM public key, or a thunk resolving one. A thunk is re-read per request, so rotation lands. */
|
|
62
|
+
publicKey: string | (() => Promise<string | undefined> | string | undefined);
|
|
63
|
+
/** Cookie carrying the token. Defaults to the edge's own literal. */
|
|
64
|
+
cookieName?: string;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/** Either an established identity, or the response to return instead. */
|
|
68
|
+
export type TrustedEdgeResult<R> = {
|
|
69
|
+
ok: true;
|
|
70
|
+
identity: EdgeIdentity;
|
|
71
|
+
} | {
|
|
72
|
+
ok: false;
|
|
73
|
+
response: R;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Close both doors. Returns the established identity on success, or the response to return.
|
|
77
|
+
*
|
|
78
|
+
* Callers must return `response` immediately when `ok` is false — there is no partial-pass state.
|
|
79
|
+
* Authorization (may this identity write?) is deliberately NOT here: it is per-surface, and a
|
|
80
|
+
* wayfinding app may need only "can you see it" where an editor needs "can you write". Derive it
|
|
81
|
+
* from the returned `eppn` with `capabilitiesFor`.
|
|
82
|
+
*/
|
|
83
|
+
export declare function requireTrustedEdge<R>(headers: Record<string, string | undefined>, config: TrustedEdgeConfig<R>, rawPath: string): Promise<TrustedEdgeResult<R>>;
|
package/dist/gate.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.GATE_ERRORS = exports.TOKEN_COOKIE_DEFAULT = exports.CHALLENGE_HEADER_DEFAULT = void 0;
|
|
7
|
+
exports.requireTrustedEdge = requireTrustedEdge;
|
|
8
|
+
/**
|
|
9
|
+
* The request gate — the two doors every consuming app has to close, in the order that makes them safe.
|
|
10
|
+
*
|
|
11
|
+
* ## Two doors, two different questions
|
|
12
|
+
*
|
|
13
|
+
* **Back door** — a request sent straight at the Function URL, bypassing CloudFront. Closed by
|
|
14
|
+
* validating `cloudfront-challenge` against the shared secret. This is not an authentication
|
|
15
|
+
* failure, so it must NOT bounce to login: a 403 is the honest answer to "you did not transit the
|
|
16
|
+
* edge."
|
|
17
|
+
*
|
|
18
|
+
* **Front door** — a viewer coming through CloudFront who sets `authenticated: true` as a request
|
|
19
|
+
* header. The challenge check cannot catch this, because the edge injects a legitimate challenge
|
|
20
|
+
* alongside the forged header. What closes it is the SP (`@bostonuniversity/shibboleth-sp`): it
|
|
21
|
+
* writes `authenticated` on every path — `'false'` on the unauthenticated pass-through — replacing any
|
|
22
|
+
* value the viewer sent.
|
|
23
|
+
*
|
|
24
|
+
* ## Why the order below is load-bearing, not stylistic
|
|
25
|
+
*
|
|
26
|
+
* Challenge, then `authenticated`, then — and only then — identity. `requireTrustedEdge` is the only
|
|
27
|
+
* place that order is expressed, which is why callers should take the identity it returns rather than
|
|
28
|
+
* decoding the headers again themselves. Identity comes from `user-details` ALONE, or with
|
|
29
|
+
* `verifyToken` from the verified token, which is the same object.
|
|
30
|
+
*
|
|
31
|
+
* The order matters because of what can reach the origin without the SP having written it. Before
|
|
32
|
+
* shibboleth-sp 1.0.7, the SP did not write or clear `user-details` on the unauthenticated
|
|
33
|
+
* pass-through, and it skipped a blank claim header rather than clearing it. So a viewer-supplied
|
|
34
|
+
* `user-details`, or a claim header such as `eduPersonPrincipalName`, could reach the origin when
|
|
35
|
+
* nobody was signed in. Decoding identity before checking `authenticated` would have read an
|
|
36
|
+
* attacker's claimed eppn. That is also why the individual claim headers are never read here:
|
|
37
|
+
* `user-details` is written from the validated token as a whole and cannot be blank on the
|
|
38
|
+
* authenticated path.
|
|
39
|
+
*
|
|
40
|
+
* From 1.0.7 the SP strips every header it may set — `authenticated`, `user-details`, the claim
|
|
41
|
+
* headers, the login and logout headers, and the challenge — before it decides anything, so none of
|
|
42
|
+
* them reaches the origin from a viewer.
|
|
43
|
+
*
|
|
44
|
+
* **Nothing here should be relaxed because of that.** This package must stay safe behind edges built
|
|
45
|
+
* with older SP versions; an origin cannot verify that any upstream clearing actually happened; and
|
|
46
|
+
* checking `authenticated` before decoding costs nothing. The SP is a separate release train, so its
|
|
47
|
+
* header behaviour is a dependency this package states but does not test. With `verifyToken` the
|
|
48
|
+
* dependency stops mattering for identity: a forged header cannot pass a signature check.
|
|
49
|
+
*/
|
|
50
|
+
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
|
51
|
+
const trustBoundary_1 = require("./trustBoundary");
|
|
52
|
+
/** Default name of the shared-secret header the edge injects. */
|
|
53
|
+
exports.CHALLENGE_HEADER_DEFAULT = 'cloudfront-challenge';
|
|
54
|
+
/** Default name of the cookie carrying the session JWT. The edge's own literal. */
|
|
55
|
+
exports.TOKEN_COOKIE_DEFAULT = 'auth-token-cookie';
|
|
56
|
+
/**
|
|
57
|
+
* Error codes, deliberately distinct at their respective statuses. `forbidden` means "you did not
|
|
58
|
+
* transit the edge"; `unauthenticated` means "you did, but nobody is logged in". A consuming app's
|
|
59
|
+
* own authorization refusal is a third thing again (`not_authorized` at 403) — see the app's write
|
|
60
|
+
* surfaces. Collapsing any two of these makes an operator's failure indistinguishable from an
|
|
61
|
+
* attacker's.
|
|
62
|
+
*/
|
|
63
|
+
exports.GATE_ERRORS = {
|
|
64
|
+
forbidden: 'forbidden',
|
|
65
|
+
unauthenticated: 'unauthenticated',
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Close both doors. Returns the established identity on success, or the response to return.
|
|
69
|
+
*
|
|
70
|
+
* Callers must return `response` immediately when `ok` is false — there is no partial-pass state.
|
|
71
|
+
* Authorization (may this identity write?) is deliberately NOT here: it is per-surface, and a
|
|
72
|
+
* wayfinding app may need only "can you see it" where an editor needs "can you write". Derive it
|
|
73
|
+
* from the returned `eppn` with `capabilitiesFor`.
|
|
74
|
+
*/
|
|
75
|
+
async function requireTrustedEdge(headers, config, rawPath) {
|
|
76
|
+
const { challengeCache, challengeHeader = exports.CHALLENGE_HEADER_DEFAULT, json, unauthenticated, verifyToken, } = config;
|
|
77
|
+
// (1) Back door. Fails closed: an empty accepted list (cold cache, unreadable secret) rejects.
|
|
78
|
+
// Runs whether or not tokens are verified: an unauthenticated request carries no token, so
|
|
79
|
+
// verification has nothing to check on that path.
|
|
80
|
+
const accepted = await challengeCache.getValues();
|
|
81
|
+
if (!(0, trustBoundary_1.challengeMatchesAny)(headers[challengeHeader], accepted)) {
|
|
82
|
+
return { ok: false, response: json(403, { error: exports.GATE_ERRORS.forbidden }) };
|
|
83
|
+
}
|
|
84
|
+
// (2) Front door. Must precede any read of `user-details` — see the header comment.
|
|
85
|
+
if (headers['authenticated'] !== 'true') {
|
|
86
|
+
return { ok: false, response: unauthenticated(rawPath) };
|
|
87
|
+
}
|
|
88
|
+
// (3) Identity — verified where the app asked for it, asserted otherwise.
|
|
89
|
+
if (verifyToken) {
|
|
90
|
+
const { publicKey, cookieName = exports.TOKEN_COOKIE_DEFAULT } = verifyToken;
|
|
91
|
+
const token = (0, trustBoundary_1.cookieValue)(headers['cookie'], cookieName);
|
|
92
|
+
if (!token) {
|
|
93
|
+
console.warn(`[edge-origin-trust] ${cookieName} absent; refusing.`);
|
|
94
|
+
return { ok: false, response: unauthenticated(rawPath) };
|
|
95
|
+
}
|
|
96
|
+
const key = typeof publicKey === 'function' ? await publicKey() : publicKey;
|
|
97
|
+
if (!key) {
|
|
98
|
+
console.error('[edge-origin-trust] no JWT public key available; cannot verify, refusing.');
|
|
99
|
+
return { ok: false, response: unauthenticated(rawPath) };
|
|
100
|
+
}
|
|
101
|
+
let verified;
|
|
102
|
+
try {
|
|
103
|
+
// `algorithms` is pinned deliberately. A token that nominates its own algorithm can ask for
|
|
104
|
+
// `none`, or for HS256 — which would verify an attacker-signed token against the public key
|
|
105
|
+
// used as an HMAC secret.
|
|
106
|
+
verified = jsonwebtoken_1.default.verify(token, key, { algorithms: ['RS256'] });
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
console.warn('[edge-origin-trust] token verification failed:', e?.name || 'error');
|
|
110
|
+
return { ok: false, response: unauthenticated(rawPath) };
|
|
111
|
+
}
|
|
112
|
+
// Same object the SP base64-encodes into `user-details`, so eppnOf and EdgeIdentity are
|
|
113
|
+
// unchanged either way.
|
|
114
|
+
return { ok: true, identity: { userDetails: verified, eppn: (0, trustBoundary_1.eppnOf)(verified) } };
|
|
115
|
+
}
|
|
116
|
+
const userDetails = (0, trustBoundary_1.decodeUserDetails)(headers['user-details']);
|
|
117
|
+
return { ok: true, identity: { userDetails, eppn: (0, trustBoundary_1.eppnOf)(userDetails) } };
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=gate.js.map
|
package/dist/gate.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gate.js","sourceRoot":"","sources":["../src/gate.ts"],"names":[],"mappings":";;;;;;AAkIA,gDA4DC;AA9LD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,gEAA+B;AAC/B,mDAA8F;AAG9F,iEAAiE;AACpD,QAAA,wBAAwB,GAAG,sBAAsB,CAAC;AAE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E,CAAC","sourcesContent":["/**\n * The request gate — the two doors every consuming app has to close, in the order that makes them safe.\n *\n * ## Two doors, two different questions\n *\n * **Back door** — a request sent straight at the Function URL, bypassing CloudFront. Closed by\n * validating `cloudfront-challenge` against the shared secret. This is not an authentication\n * failure, so it must NOT bounce to login: a 403 is the honest answer to \"you did not transit the\n * edge.\"\n *\n * **Front door** — a viewer coming through CloudFront who sets `authenticated: true` as a request\n * header. The challenge check cannot catch this, because the edge injects a legitimate challenge\n * alongside the forged header. What closes it is the SP (`@bostonuniversity/shibboleth-sp`): it\n * writes `authenticated` on every path — `'false'` on the unauthenticated pass-through — replacing any\n * value the viewer sent.\n *\n * ## Why the order below is load-bearing, not stylistic\n *\n * Challenge, then `authenticated`, then — and only then — identity. `requireTrustedEdge` is the only\n * place that order is expressed, which is why callers should take the identity it returns rather than\n * decoding the headers again themselves. Identity comes from `user-details` ALONE, or with\n * `verifyToken` from the verified token, which is the same object.\n *\n * The order matters because of what can reach the origin without the SP having written it. Before\n * shibboleth-sp 1.0.7, the SP did not write or clear `user-details` on the unauthenticated\n * pass-through, and it skipped a blank claim header rather than clearing it. So a viewer-supplied\n * `user-details`, or a claim header such as `eduPersonPrincipalName`, could reach the origin when\n * nobody was signed in. Decoding identity before checking `authenticated` would have read an\n * attacker's claimed eppn. That is also why the individual claim headers are never read here:\n * `user-details` is written from the validated token as a whole and cannot be blank on the\n * authenticated path.\n *\n * From 1.0.7 the SP strips every header it may set — `authenticated`, `user-details`, the claim\n * headers, the login and logout headers, and the challenge — before it decides anything, so none of\n * them reaches the origin from a viewer.\n *\n * **Nothing here should be relaxed because of that.** This package must stay safe behind edges built\n * with older SP versions; an origin cannot verify that any upstream clearing actually happened; and\n * checking `authenticated` before decoding costs nothing. The SP is a separate release train, so its\n * header behaviour is a dependency this package states but does not test. With `verifyToken` the\n * dependency stops mattering for identity: a forged header cannot pass a signature check.\n */\nimport jwt from 'jsonwebtoken';\nimport { challengeMatchesAny, cookieValue, decodeUserDetails, eppnOf } from './trustBoundary';\nimport type { ChallengeCache } from './challengeCache';\n\n/** Default name of the shared-secret header the edge injects. */\nexport const CHALLENGE_HEADER_DEFAULT = 'cloudfront-challenge';\n\n/** Default name of the cookie carrying the session JWT. The edge's own literal. */\nexport const TOKEN_COOKIE_DEFAULT = 'auth-token-cookie';\n\n/**\n * Error codes, deliberately distinct at their respective statuses. `forbidden` means \"you did not\n * transit the edge\"; `unauthenticated` means \"you did, but nobody is logged in\". A consuming app's\n * own authorization refusal is a third thing again (`not_authorized` at 403) — see the app's write\n * surfaces. Collapsing any two of these makes an operator's failure indistinguishable from an\n * attacker's.\n */\nexport const GATE_ERRORS = {\n forbidden: 'forbidden',\n unauthenticated: 'unauthenticated',\n} as const;\n\n/** Who the edge says this is. Only produced once both doors are closed. */\nexport interface EdgeIdentity {\n /** The decoded `user-details` payload, or null if absent/undecodable. */\n userDetails: unknown;\n /** The eppn — the allow-list key — or null if the payload carries no principal. */\n eppn: string | null;\n}\n\nexport interface TrustedEdgeConfig<R> {\n /** The runtime challenge-secret cache. Its TTL is what makes rotation redeploy-free. */\n challengeCache: ChallengeCache;\n /** Header name carrying the shared secret. Defaults to the edge's own literal. */\n challengeHeader?: string;\n /** Build a JSON response. The module composes its own status/body pairs through this. */\n json: (statusCode: number, body: unknown) => R;\n /**\n * The refusal for a request that transited the edge but carries no session. A 401, never a\n * redirect.\n *\n * The app supplies the whole decision because only it knows its own request taxonomy, and that\n * taxonomy has at least three arms once a bundle is involved:\n *\n * unauthenticated: (p) =>\n * p.includes('/api/') || isAssetRequest(p) // isAssetRequest is exported from ./spa\n * ? json(401, { error: GATE_ERRORS.unauthenticated })\n * : loginPage(p)\n *\n * A two-arm predicate — API path or not — is one arm too few, and naming it after APIs is what\n * makes the third easy to miss: an expired session requesting a hashed bundle would be handed an\n * HTML document, the same shape as the defect `spa.ts` exists to prevent, one status code away.\n * Hence a whole decision rather than a predicate.\n */\n unauthenticated: (rawPath: string) => R;\n\n /**\n * Verify the session JWT rather than taking `authenticated: true` on trust. Opt-in.\n *\n * The key is public, so it can come from wherever suits the consumer. `createChallengeCache` will\n * serve it from the same secret and TTL as the challenge:\n *\n * verifyToken: { publicKey: () => challengeCache.getPublicKey() }\n *\n * Fails closed: a missing cookie, an absent key, or a bad signature all refuse the request. There\n * is deliberately no fallback to the header — a silent one would be undetectable from outside.\n */\n verifyToken?: {\n /** PEM public key, or a thunk resolving one. A thunk is re-read per request, so rotation lands. */\n publicKey: string | (() => Promise<string | undefined> | string | undefined);\n /** Cookie carrying the token. Defaults to the edge's own literal. */\n cookieName?: string;\n };\n}\n\n/** Either an established identity, or the response to return instead. */\nexport type TrustedEdgeResult<R> =\n | { ok: true; identity: EdgeIdentity }\n | { ok: false; response: R };\n\n/**\n * Close both doors. Returns the established identity on success, or the response to return.\n *\n * Callers must return `response` immediately when `ok` is false — there is no partial-pass state.\n * Authorization (may this identity write?) is deliberately NOT here: it is per-surface, and a\n * wayfinding app may need only \"can you see it\" where an editor needs \"can you write\". Derive it\n * from the returned `eppn` with `capabilitiesFor`.\n */\nexport async function requireTrustedEdge<R>(\n headers: Record<string, string | undefined>,\n config: TrustedEdgeConfig<R>,\n rawPath: string,\n): Promise<TrustedEdgeResult<R>> {\n const {\n challengeCache,\n challengeHeader = CHALLENGE_HEADER_DEFAULT,\n json,\n unauthenticated,\n verifyToken,\n } = config;\n\n // (1) Back door. Fails closed: an empty accepted list (cold cache, unreadable secret) rejects.\n // Runs whether or not tokens are verified: an unauthenticated request carries no token, so\n // verification has nothing to check on that path.\n const accepted = await challengeCache.getValues();\n if (!challengeMatchesAny(headers[challengeHeader], accepted)) {\n return { ok: false, response: json(403, { error: GATE_ERRORS.forbidden }) };\n }\n\n // (2) Front door. Must precede any read of `user-details` — see the header comment.\n if (headers['authenticated'] !== 'true') {\n return { ok: false, response: unauthenticated(rawPath) };\n }\n\n // (3) Identity — verified where the app asked for it, asserted otherwise.\n if (verifyToken) {\n const { publicKey, cookieName = TOKEN_COOKIE_DEFAULT } = verifyToken;\n\n const token = cookieValue(headers['cookie'], cookieName);\n if (!token) {\n console.warn(`[edge-origin-trust] ${cookieName} absent; refusing.`);\n return { ok: false, response: unauthenticated(rawPath) };\n }\n\n const key = typeof publicKey === 'function' ? await publicKey() : publicKey;\n if (!key) {\n console.error('[edge-origin-trust] no JWT public key available; cannot verify, refusing.');\n return { ok: false, response: unauthenticated(rawPath) };\n }\n\n let verified: unknown;\n try {\n // `algorithms` is pinned deliberately. A token that nominates its own algorithm can ask for\n // `none`, or for HS256 — which would verify an attacker-signed token against the public key\n // used as an HMAC secret.\n verified = jwt.verify(token, key, { algorithms: ['RS256'] });\n } catch (e) {\n console.warn('[edge-origin-trust] token verification failed:', (e as Error)?.name || 'error');\n return { ok: false, response: unauthenticated(rawPath) };\n }\n\n // Same object the SP base64-encodes into `user-details`, so eppnOf and EdgeIdentity are\n // unchanged either way.\n return { ok: true, identity: { userDetails: verified, eppn: eppnOf(verified) } };\n }\n\n const userDetails = decodeUserDetails(headers['user-details']);\n return { ok: true, identity: { userDetails, eppn: eppnOf(userDetails) } };\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The core runtime surface: establishing trust in a request that arrived through the edge.
|
|
3
|
+
*
|
|
4
|
+
* Validate the challenge header, read the identity the edge injected, gate the request, and set the
|
|
5
|
+
* response headers. Any app the edge routes to needs all of this. Two further capabilities are opt-in
|
|
6
|
+
* by subpath, because not every app serves a bundle or authorizes writes:
|
|
7
|
+
*
|
|
8
|
+
* import { createSpaServer } from '@bostonuniversity/edge-origin-trust/spa';
|
|
9
|
+
* import { createAllowList, capabilitiesFor } from '@bostonuniversity/edge-origin-trust/allowList';
|
|
10
|
+
*
|
|
11
|
+
* Runtime surface only. The CDK construct is a separate entry point
|
|
12
|
+
* (`@bostonuniversity/edge-origin-trust/cdk/EdgeOriginApp`) so aws-cdk-lib stays out of handler
|
|
13
|
+
* bundles, and the shared eppn vectors are published at
|
|
14
|
+
* `@bostonuniversity/edge-origin-trust/fixtures/eppn.vectors.json`.
|
|
15
|
+
*/
|
|
16
|
+
export { lowerCaseKeys, challengeMatches, challengeMatchesAny, cookieValue, decodeUserDetails, decodeInjectedUrl, eppnOf, } from './trustBoundary';
|
|
17
|
+
export { requireTrustedEdge, CHALLENGE_HEADER_DEFAULT, TOKEN_COOKIE_DEFAULT, GATE_ERRORS, } from './gate';
|
|
18
|
+
export type { EdgeIdentity, TrustedEdgeConfig, TrustedEdgeResult } from './gate';
|
|
19
|
+
export { createChallengeCache } from './challengeCache';
|
|
20
|
+
export type { ChallengeCache, ChallengeCacheConfig } from './challengeCache';
|
|
21
|
+
export { json, html, notFound, htmlEscape, securityHeaders } from './responses';
|
|
22
|
+
export type { OriginResponse, SecurityHeaderOptions } from './responses';
|
|
23
|
+
export type { ValidationIssue } from './types';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.securityHeaders = exports.htmlEscape = exports.notFound = exports.html = exports.json = exports.createChallengeCache = exports.GATE_ERRORS = exports.TOKEN_COOKIE_DEFAULT = exports.CHALLENGE_HEADER_DEFAULT = exports.requireTrustedEdge = exports.eppnOf = exports.decodeInjectedUrl = exports.decodeUserDetails = exports.cookieValue = exports.challengeMatchesAny = exports.challengeMatches = exports.lowerCaseKeys = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* The core runtime surface: establishing trust in a request that arrived through the edge.
|
|
6
|
+
*
|
|
7
|
+
* Validate the challenge header, read the identity the edge injected, gate the request, and set the
|
|
8
|
+
* response headers. Any app the edge routes to needs all of this. Two further capabilities are opt-in
|
|
9
|
+
* by subpath, because not every app serves a bundle or authorizes writes:
|
|
10
|
+
*
|
|
11
|
+
* import { createSpaServer } from '@bostonuniversity/edge-origin-trust/spa';
|
|
12
|
+
* import { createAllowList, capabilitiesFor } from '@bostonuniversity/edge-origin-trust/allowList';
|
|
13
|
+
*
|
|
14
|
+
* Runtime surface only. The CDK construct is a separate entry point
|
|
15
|
+
* (`@bostonuniversity/edge-origin-trust/cdk/EdgeOriginApp`) so aws-cdk-lib stays out of handler
|
|
16
|
+
* bundles, and the shared eppn vectors are published at
|
|
17
|
+
* `@bostonuniversity/edge-origin-trust/fixtures/eppn.vectors.json`.
|
|
18
|
+
*/
|
|
19
|
+
var trustBoundary_1 = require("./trustBoundary");
|
|
20
|
+
Object.defineProperty(exports, "lowerCaseKeys", { enumerable: true, get: function () { return trustBoundary_1.lowerCaseKeys; } });
|
|
21
|
+
Object.defineProperty(exports, "challengeMatches", { enumerable: true, get: function () { return trustBoundary_1.challengeMatches; } });
|
|
22
|
+
Object.defineProperty(exports, "challengeMatchesAny", { enumerable: true, get: function () { return trustBoundary_1.challengeMatchesAny; } });
|
|
23
|
+
Object.defineProperty(exports, "cookieValue", { enumerable: true, get: function () { return trustBoundary_1.cookieValue; } });
|
|
24
|
+
Object.defineProperty(exports, "decodeUserDetails", { enumerable: true, get: function () { return trustBoundary_1.decodeUserDetails; } });
|
|
25
|
+
Object.defineProperty(exports, "decodeInjectedUrl", { enumerable: true, get: function () { return trustBoundary_1.decodeInjectedUrl; } });
|
|
26
|
+
Object.defineProperty(exports, "eppnOf", { enumerable: true, get: function () { return trustBoundary_1.eppnOf; } });
|
|
27
|
+
var gate_1 = require("./gate");
|
|
28
|
+
Object.defineProperty(exports, "requireTrustedEdge", { enumerable: true, get: function () { return gate_1.requireTrustedEdge; } });
|
|
29
|
+
Object.defineProperty(exports, "CHALLENGE_HEADER_DEFAULT", { enumerable: true, get: function () { return gate_1.CHALLENGE_HEADER_DEFAULT; } });
|
|
30
|
+
Object.defineProperty(exports, "TOKEN_COOKIE_DEFAULT", { enumerable: true, get: function () { return gate_1.TOKEN_COOKIE_DEFAULT; } });
|
|
31
|
+
Object.defineProperty(exports, "GATE_ERRORS", { enumerable: true, get: function () { return gate_1.GATE_ERRORS; } });
|
|
32
|
+
var challengeCache_1 = require("./challengeCache");
|
|
33
|
+
Object.defineProperty(exports, "createChallengeCache", { enumerable: true, get: function () { return challengeCache_1.createChallengeCache; } });
|
|
34
|
+
var responses_1 = require("./responses");
|
|
35
|
+
Object.defineProperty(exports, "json", { enumerable: true, get: function () { return responses_1.json; } });
|
|
36
|
+
Object.defineProperty(exports, "html", { enumerable: true, get: function () { return responses_1.html; } });
|
|
37
|
+
Object.defineProperty(exports, "notFound", { enumerable: true, get: function () { return responses_1.notFound; } });
|
|
38
|
+
Object.defineProperty(exports, "htmlEscape", { enumerable: true, get: function () { return responses_1.htmlEscape; } });
|
|
39
|
+
Object.defineProperty(exports, "securityHeaders", { enumerable: true, get: function () { return responses_1.securityHeaders; } });
|
|
40
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,iDAQyB;AAPvB,8GAAA,aAAa,OAAA;AACb,iHAAA,gBAAgB,OAAA;AAChB,oHAAA,mBAAmB,OAAA;AACnB,4GAAA,WAAW,OAAA;AACX,kHAAA,iBAAiB,OAAA;AACjB,kHAAA,iBAAiB,OAAA;AACjB,uGAAA,MAAM,OAAA;AAGR,+BAKgB;AAJd,0GAAA,kBAAkB,OAAA;AAClB,gHAAA,wBAAwB,OAAA;AACxB,4GAAA,oBAAoB,OAAA;AACpB,mGAAA,WAAW,OAAA;AAIb,mDAAwD;AAA/C,sHAAA,oBAAoB,OAAA;AAG7B,yCAAgF;AAAvE,iGAAA,IAAI,OAAA;AAAE,iGAAA,IAAI,OAAA;AAAE,qGAAA,QAAQ,OAAA;AAAE,uGAAA,UAAU,OAAA;AAAE,4GAAA,eAAe,OAAA","sourcesContent":["/**\n * The core runtime surface: establishing trust in a request that arrived through the edge.\n *\n * Validate the challenge header, read the identity the edge injected, gate the request, and set the\n * response headers. Any app the edge routes to needs all of this. Two further capabilities are opt-in\n * by subpath, because not every app serves a bundle or authorizes writes:\n *\n * import { createSpaServer } from '@bostonuniversity/edge-origin-trust/spa';\n * import { createAllowList, capabilitiesFor } from '@bostonuniversity/edge-origin-trust/allowList';\n *\n * Runtime surface only. The CDK construct is a separate entry point\n * (`@bostonuniversity/edge-origin-trust/cdk/EdgeOriginApp`) so aws-cdk-lib stays out of handler\n * bundles, and the shared eppn vectors are published at\n * `@bostonuniversity/edge-origin-trust/fixtures/eppn.vectors.json`.\n */\nexport {\n lowerCaseKeys,\n challengeMatches,\n challengeMatchesAny,\n cookieValue,\n decodeUserDetails,\n decodeInjectedUrl,\n eppnOf,\n} from './trustBoundary';\n\nexport {\n requireTrustedEdge,\n CHALLENGE_HEADER_DEFAULT,\n TOKEN_COOKIE_DEFAULT,\n GATE_ERRORS,\n} from './gate';\nexport type { EdgeIdentity, TrustedEdgeConfig, TrustedEdgeResult } from './gate';\n\nexport { createChallengeCache } from './challengeCache';\nexport type { ChallengeCache, ChallengeCacheConfig } from './challengeCache';\n\nexport { json, html, notFound, htmlEscape, securityHeaders } from './responses';\nexport type { OriginResponse, SecurityHeaderOptions } from './responses';\n\nexport type { ValidationIssue } from './types';\n"]}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response helpers, carrying the security headers by default.
|
|
3
|
+
*
|
|
4
|
+
* A security default applied in one place is worth more than the same default documented in five.
|
|
5
|
+
* Don't count on the CDN in front of the app to add these: a distribution with no response headers
|
|
6
|
+
* policy adds none. So these helpers set `nosniff`, a CSP, frame protection and `Referrer-Policy`
|
|
7
|
+
* themselves, and every app that imports them gets the full set without knowing to ask.
|
|
8
|
+
*
|
|
9
|
+
* Scope line: this library owns the headers an app sets on its own responses. What reaches the origin
|
|
10
|
+
* at all — the origin request policy, an edge-wide response headers policy — belongs to the edge and
|
|
11
|
+
* is deliberately not handled here.
|
|
12
|
+
*/
|
|
13
|
+
/** Structurally compatible with LambdaFunctionURLResult, without importing aws-lambda types. */
|
|
14
|
+
export interface OriginResponse {
|
|
15
|
+
statusCode: number;
|
|
16
|
+
headers: Record<string, string>;
|
|
17
|
+
body: string;
|
|
18
|
+
isBase64Encoded?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export interface SecurityHeaderOptions {
|
|
21
|
+
/**
|
|
22
|
+
* `frame-ancestors` value. Defaults to `'none'`.
|
|
23
|
+
*
|
|
24
|
+
* This is the one that matters most for an operator tool that mutates production. Without it any
|
|
25
|
+
* page on the internet can frame the app, and an authenticated operator who visits an attacker's
|
|
26
|
+
* page can be induced to click a destructive confirmation inside an invisible frame.
|
|
27
|
+
*/
|
|
28
|
+
frameAncestors?: string;
|
|
29
|
+
/** Extra `connect-src` origins, if a consuming app genuinely calls out. Same-origin is the default. */
|
|
30
|
+
connectSrc?: string[];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The shared header set. `style-src` allows inline styles because CSS-in-JS (Chakra, emotion) injects
|
|
34
|
+
* `<style>` at runtime; that is a real weakening and it is deliberate rather than accidental. Scripts
|
|
35
|
+
* get no exemption at all: `script-src 'self'` with no nonce. A page needing a value the browser
|
|
36
|
+
* cannot know — the viewer's own domain, say — should build it server-side from the headers the edge
|
|
37
|
+
* injects rather than synthesize it in an inline script.
|
|
38
|
+
*/
|
|
39
|
+
export declare function securityHeaders(opts?: SecurityHeaderOptions): Record<string, string>;
|
|
40
|
+
/**
|
|
41
|
+
* A JSON response. Never cached, by the browser or by a shared cache such as CloudFront. A cache
|
|
42
|
+
* behaviour can keep a response that has no `Cache-Control` and answer later requests with it
|
|
43
|
+
* without asking the origin. Without `no-store`, a cached copy could hand back a stale allow-list,
|
|
44
|
+
* or one caller's identity to another.
|
|
45
|
+
*/
|
|
46
|
+
export declare function json(statusCode: number, body: unknown, opts?: SecurityHeaderOptions & {
|
|
47
|
+
headers?: Record<string, string>;
|
|
48
|
+
}): OriginResponse;
|
|
49
|
+
/**
|
|
50
|
+
* An HTML response for a complete document the caller has already built.
|
|
51
|
+
*
|
|
52
|
+
* `no-store` by default. Every document this serves depends on sign-in state (a login page, a
|
|
53
|
+
* no-bundle placeholder), so a cached copy could show a stale login page to someone who is signed in.
|
|
54
|
+
*/
|
|
55
|
+
export declare function html(statusCode: number, document: string, opts?: SecurityHeaderOptions & {
|
|
56
|
+
headers?: Record<string, string>;
|
|
57
|
+
}): OriginResponse;
|
|
58
|
+
/**
|
|
59
|
+
* A plain-text 404. Deliberately not HTML: this is what a missing static asset returns, and a
|
|
60
|
+
* browser that asked for a JavaScript module must not be handed a document.
|
|
61
|
+
*/
|
|
62
|
+
export declare function notFound(message?: string): OriginResponse;
|
|
63
|
+
/** Escape HTML special characters. Every app that renders a page needs this. */
|
|
64
|
+
export declare function htmlEscape(value: string): string;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.securityHeaders = securityHeaders;
|
|
4
|
+
exports.json = json;
|
|
5
|
+
exports.html = html;
|
|
6
|
+
exports.notFound = notFound;
|
|
7
|
+
exports.htmlEscape = htmlEscape;
|
|
8
|
+
/**
|
|
9
|
+
* The shared header set. `style-src` allows inline styles because CSS-in-JS (Chakra, emotion) injects
|
|
10
|
+
* `<style>` at runtime; that is a real weakening and it is deliberate rather than accidental. Scripts
|
|
11
|
+
* get no exemption at all: `script-src 'self'` with no nonce. A page needing a value the browser
|
|
12
|
+
* cannot know — the viewer's own domain, say — should build it server-side from the headers the edge
|
|
13
|
+
* injects rather than synthesize it in an inline script.
|
|
14
|
+
*/
|
|
15
|
+
function securityHeaders(opts = {}) {
|
|
16
|
+
const { frameAncestors = "'none'", connectSrc = [] } = opts;
|
|
17
|
+
const connect = ["'self'", ...connectSrc].join(' ');
|
|
18
|
+
const csp = [
|
|
19
|
+
"default-src 'self'",
|
|
20
|
+
"script-src 'self'",
|
|
21
|
+
"style-src 'self' 'unsafe-inline'",
|
|
22
|
+
"img-src 'self' data:",
|
|
23
|
+
"font-src 'self' data:",
|
|
24
|
+
`connect-src ${connect}`,
|
|
25
|
+
"object-src 'none'",
|
|
26
|
+
"base-uri 'none'",
|
|
27
|
+
"form-action 'self'",
|
|
28
|
+
`frame-ancestors ${frameAncestors}`,
|
|
29
|
+
].join('; ');
|
|
30
|
+
return {
|
|
31
|
+
// Without this, an HTML document served where a script was requested stops being merely
|
|
32
|
+
// confusing and becomes a content-sniffing surface. See the asset branch in spa.ts.
|
|
33
|
+
'x-content-type-options': 'nosniff',
|
|
34
|
+
'content-security-policy': csp,
|
|
35
|
+
// Belt and braces for anything that predates frame-ancestors support.
|
|
36
|
+
'x-frame-options': 'DENY',
|
|
37
|
+
// An app's URLs can carry internal paths and names; do not leak them cross-origin.
|
|
38
|
+
'referrer-policy': 'strict-origin-when-cross-origin',
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A JSON response. Never cached, by the browser or by a shared cache such as CloudFront. A cache
|
|
43
|
+
* behaviour can keep a response that has no `Cache-Control` and answer later requests with it
|
|
44
|
+
* without asking the origin. Without `no-store`, a cached copy could hand back a stale allow-list,
|
|
45
|
+
* or one caller's identity to another.
|
|
46
|
+
*/
|
|
47
|
+
function json(statusCode, body, opts = {}) {
|
|
48
|
+
const { headers: extra, ...security } = opts;
|
|
49
|
+
return {
|
|
50
|
+
statusCode,
|
|
51
|
+
headers: {
|
|
52
|
+
'content-type': 'application/json; charset=utf-8',
|
|
53
|
+
'cache-control': 'no-store',
|
|
54
|
+
...securityHeaders(security),
|
|
55
|
+
...extra,
|
|
56
|
+
},
|
|
57
|
+
body: JSON.stringify(body),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* An HTML response for a complete document the caller has already built.
|
|
62
|
+
*
|
|
63
|
+
* `no-store` by default. Every document this serves depends on sign-in state (a login page, a
|
|
64
|
+
* no-bundle placeholder), so a cached copy could show a stale login page to someone who is signed in.
|
|
65
|
+
*/
|
|
66
|
+
function html(statusCode, document, opts = {}) {
|
|
67
|
+
const { headers: extra, ...security } = opts;
|
|
68
|
+
return {
|
|
69
|
+
statusCode,
|
|
70
|
+
headers: {
|
|
71
|
+
'content-type': 'text/html; charset=utf-8',
|
|
72
|
+
'cache-control': 'no-store',
|
|
73
|
+
...securityHeaders(security),
|
|
74
|
+
...extra,
|
|
75
|
+
},
|
|
76
|
+
body: document,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A plain-text 404. Deliberately not HTML: this is what a missing static asset returns, and a
|
|
81
|
+
* browser that asked for a JavaScript module must not be handed a document.
|
|
82
|
+
*/
|
|
83
|
+
function notFound(message = 'Not found') {
|
|
84
|
+
return {
|
|
85
|
+
statusCode: 404,
|
|
86
|
+
headers: {
|
|
87
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
88
|
+
'cache-control': 'no-store',
|
|
89
|
+
...securityHeaders(),
|
|
90
|
+
},
|
|
91
|
+
body: message,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** Escape HTML special characters. Every app that renders a page needs this. */
|
|
95
|
+
function htmlEscape(value) {
|
|
96
|
+
return String(value)
|
|
97
|
+
.replace(/&/g, '&')
|
|
98
|
+
.replace(/</g, '<')
|
|
99
|
+
.replace(/>/g, '>')
|
|
100
|
+
.replace(/"/g, '"')
|
|
101
|
+
.replace(/'/g, ''');
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=responses.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"responses.js","sourceRoot":"","sources":["../src/responses.ts"],"names":[],"mappings":";;AAwCA,0CA2BC;AAQD,oBAgBC;AAQD,oBAgBC;AAMD,4BAUC;AAGD,gCAOC;AA5GD;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,OAA8B,EAAE;IAC9D,MAAM,EAAE,cAAc,GAAG,QAAQ,EAAE,UAAU,GAAG,EAAE,EAAE,GAAG,IA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G,KAAK;SACT;QACD,IAAI,EAAE,QAAQ;KACf,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAgB,QAAQ,CAAC,OAAO,GAAG,WAAW;IAC5C,OAAO;QACL,UAAU,EAAE,GAAG;QACf,OAAO,EAAE;YACP,cAAc,EAAE,2BAA2B;YAC3C,eAAe,EAAE,UAAU;YAC3B,GAAG,eAAe,EAAE;SACrB;QACD,IAAI,EAAE,OAAO;KACd,CAAC;AACJ,CAAC;AAED,gFAAgF;AAChF,SAAgB,UAAU,CAAC,KAAa;IACtC,OAAO,MAAM,CAAC,KAAK,CAAC;SACjB,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;SACtB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;SACvB,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * Response helpers, carrying the security headers by default.\n *\n * A security default applied in one place is worth more than the same default documented in five.\n * Don't count on the CDN in front of the app to add these: a distribution with no response headers\n * policy adds none. So these helpers set `nosniff`, a CSP, frame protection and `Referrer-Policy`\n * themselves, and every app that imports them gets the full set without knowing to ask.\n *\n * Scope line: this library owns the headers an app sets on its own responses. What reaches the origin\n * at all — the origin request policy, an edge-wide response headers policy — belongs to the edge and\n * is deliberately not handled here.\n */\n/** Structurally compatible with LambdaFunctionURLResult, without importing aws-lambda types. */\nexport interface OriginResponse {\n statusCode: number;\n headers: Record<string, string>;\n body: string;\n isBase64Encoded?: boolean;\n}\n\nexport interface SecurityHeaderOptions {\n /**\n * `frame-ancestors` value. Defaults to `'none'`.\n *\n * This is the one that matters most for an operator tool that mutates production. Without it any\n * page on the internet can frame the app, and an authenticated operator who visits an attacker's\n * page can be induced to click a destructive confirmation inside an invisible frame.\n */\n frameAncestors?: string;\n /** Extra `connect-src` origins, if a consuming app genuinely calls out. Same-origin is the default. */\n connectSrc?: string[];\n}\n\n/**\n * The shared header set. `style-src` allows inline styles because CSS-in-JS (Chakra, emotion) injects\n * `<style>` at runtime; that is a real weakening and it is deliberate rather than accidental. Scripts\n * get no exemption at all: `script-src 'self'` with no nonce. A page needing a value the browser\n * cannot know — the viewer's own domain, say — should build it server-side from the headers the edge\n * injects rather than synthesize it in an inline script.\n */\nexport function securityHeaders(opts: SecurityHeaderOptions = {}): Record<string, string> {\n const { frameAncestors = \"'none'\", connectSrc = [] } = opts;\n const connect = [\"'self'\", ...connectSrc].join(' ');\n\n const csp = [\n \"default-src 'self'\",\n \"script-src 'self'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data:\",\n \"font-src 'self' data:\",\n `connect-src ${connect}`,\n \"object-src 'none'\",\n \"base-uri 'none'\",\n \"form-action 'self'\",\n `frame-ancestors ${frameAncestors}`,\n ].join('; ');\n\n return {\n // Without this, an HTML document served where a script was requested stops being merely\n // confusing and becomes a content-sniffing surface. See the asset branch in spa.ts.\n 'x-content-type-options': 'nosniff',\n 'content-security-policy': csp,\n // Belt and braces for anything that predates frame-ancestors support.\n 'x-frame-options': 'DENY',\n // An app's URLs can carry internal paths and names; do not leak them cross-origin.\n 'referrer-policy': 'strict-origin-when-cross-origin',\n };\n}\n\n/**\n * A JSON response. Never cached, by the browser or by a shared cache such as CloudFront. A cache\n * behaviour can keep a response that has no `Cache-Control` and answer later requests with it\n * without asking the origin. Without `no-store`, a cached copy could hand back a stale allow-list,\n * or one caller's identity to another.\n */\nexport function json(\n statusCode: number,\n body: unknown,\n opts: SecurityHeaderOptions & { headers?: Record<string, string> } = {},\n): OriginResponse {\n const { headers: extra, ...security } = opts;\n return {\n statusCode,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n ...securityHeaders(security),\n ...extra,\n },\n body: JSON.stringify(body),\n };\n}\n\n/**\n * An HTML response for a complete document the caller has already built.\n *\n * `no-store` by default. Every document this serves depends on sign-in state (a login page, a\n * no-bundle placeholder), so a cached copy could show a stale login page to someone who is signed in.\n */\nexport function html(\n statusCode: number,\n document: string,\n opts: SecurityHeaderOptions & { headers?: Record<string, string> } = {},\n): OriginResponse {\n const { headers: extra, ...security } = opts;\n return {\n statusCode,\n headers: {\n 'content-type': 'text/html; charset=utf-8',\n 'cache-control': 'no-store',\n ...securityHeaders(security),\n ...extra,\n },\n body: document,\n };\n}\n\n/**\n * A plain-text 404. Deliberately not HTML: this is what a missing static asset returns, and a\n * browser that asked for a JavaScript module must not be handed a document.\n */\nexport function notFound(message = 'Not found'): OriginResponse {\n return {\n statusCode: 404,\n headers: {\n 'content-type': 'text/plain; charset=utf-8',\n 'cache-control': 'no-store',\n ...securityHeaders(),\n },\n body: message,\n };\n}\n\n/** Escape HTML special characters. Every app that renders a page needs this. */\nexport function htmlEscape(value: string): string {\n return String(value)\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n"]}
|
package/dist/spa.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type OriginResponse, type SecurityHeaderOptions } from './responses';
|
|
2
|
+
/**
|
|
3
|
+
* Directory name, beside the compiled handler, that a consuming app's build copies its bundle into.
|
|
4
|
+
*
|
|
5
|
+
* Shared because it is a two-sided contract: the CDK construct's bundling hook writes here and the
|
|
6
|
+
* handler reads from here. Two independent literals is how those silently stop agreeing.
|
|
7
|
+
*/
|
|
8
|
+
export declare const WEBAPP_DIR_NAME = "webapp";
|
|
9
|
+
export interface SpaServerConfig {
|
|
10
|
+
/** Absolute path to the built bundle. Usually `path.join(__dirname, WEBAPP_DIR_NAME)`. */
|
|
11
|
+
webappDir: string;
|
|
12
|
+
/**
|
|
13
|
+
* Response when no bundle is present at all — a deploy that skipped the frontend build. Distinct
|
|
14
|
+
* from a 404: the app is up and the request was fine, there is just nothing to serve.
|
|
15
|
+
*
|
|
16
|
+
* Takes no request context, deliberately. A consumer converting an existing page into this
|
|
17
|
+
* fallback will notice it can no longer show the caller's identity — that is the intended shape.
|
|
18
|
+
* The server is built once per container, so a request-dependent `noBundle` would invite
|
|
19
|
+
* per-request state onto a long-lived object, and the page is about the deployment rather than
|
|
20
|
+
* about whoever happened to hit it.
|
|
21
|
+
*/
|
|
22
|
+
noBundle: () => OriginResponse;
|
|
23
|
+
/** Security-header options applied to served files (e.g. a `connect-src` a consuming app needs). */
|
|
24
|
+
security?: SecurityHeaderOptions;
|
|
25
|
+
}
|
|
26
|
+
export interface SpaServer {
|
|
27
|
+
/** Resolve a request path to an asset, the SPA shell, a 404, or the no-bundle response. */
|
|
28
|
+
serve(rawPath: string): OriginResponse;
|
|
29
|
+
/**
|
|
30
|
+
* Read one file from the bundle, or null. Exposed for tests and for a consuming app that needs to
|
|
31
|
+
* serve something by an explicit name. Refuses anything that escapes `webappDir`.
|
|
32
|
+
*/
|
|
33
|
+
readFile(relPath: string): OriginResponse | null;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Does this request want a file rather than a page? For the gate's `unauthenticated` arm, so an
|
|
37
|
+
* expired session requesting a bundle gets a machine-readable 401 instead of an HTML document.
|
|
38
|
+
*
|
|
39
|
+
* Exported because the alternative is every SPA consumer re-deriving the asset rule and drifting from
|
|
40
|
+
* the one `serve` actually applies.
|
|
41
|
+
*/
|
|
42
|
+
export declare function isAssetRequest(rawPath: string): boolean;
|
|
43
|
+
export declare function createSpaServer(config: SpaServerConfig): SpaServer;
|