@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/dist/spa.js ADDED
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.WEBAPP_DIR_NAME = void 0;
37
+ exports.isAssetRequest = isAssetRequest;
38
+ exports.createSpaServer = createSpaServer;
39
+ /**
40
+ * Serving a single-page app from the Lambda, behind the gate.
41
+ *
42
+ * ## The two-jobs-with-opposite-defaults problem
43
+ *
44
+ * An SPA server has two jobs whose correct behaviour on a miss is exactly opposite: an unknown
45
+ * *route* should fall back to the shell so the client router can handle it, and an unknown *file*
46
+ * should 404. Telling those apart is the entire job of `serve`.
47
+ *
48
+ * Any implementation that reaches one shared fallback line from both branches gets this wrong, and
49
+ * the failure is inscrutable rather than loud: a request for a hashed bundle that no longer exists is
50
+ * handed the HTML document, at status 200, with `content-type: text/html`.
51
+ *
52
+ * The realistic trigger is a tab held open across a deploy: `index.html` is served `no-cache`, but a
53
+ * page already loaded in memory keeps requesting the bundle it was built with, and the new deploy no
54
+ * longer contains it. The browser asked for a JavaScript module and got HTML at 200, so it reports a
55
+ * MIME-type failure rather than a missing file, and the operator sees an app that appears broken when
56
+ * the true state is "reload me."
57
+ *
58
+ * ## Cache policy
59
+ *
60
+ * Only resolved reads are cached, which bounds the map by the number of real files in the bundle and
61
+ * needs no eviction. Caching misses as well would be negative caching keyed on caller-supplied input:
62
+ * distinct nonexistent paths, path-traversal rejections included, would accumulate entries for the
63
+ * life of the warm container.
64
+ */
65
+ const fs_1 = require("fs");
66
+ const path = __importStar(require("path"));
67
+ const responses_1 = require("./responses");
68
+ /**
69
+ * Directory name, beside the compiled handler, that a consuming app's build copies its bundle into.
70
+ *
71
+ * Shared because it is a two-sided contract: the CDK construct's bundling hook writes here and the
72
+ * handler reads from here. Two independent literals is how those silently stop agreeing.
73
+ */
74
+ exports.WEBAPP_DIR_NAME = 'webapp';
75
+ const CONTENT_TYPES = {
76
+ '.html': { type: 'text/html; charset=utf-8', binary: false },
77
+ '.js': { type: 'text/javascript; charset=utf-8', binary: false },
78
+ '.mjs': { type: 'text/javascript; charset=utf-8', binary: false },
79
+ '.css': { type: 'text/css; charset=utf-8', binary: false },
80
+ '.json': { type: 'application/json; charset=utf-8', binary: false },
81
+ '.svg': { type: 'image/svg+xml', binary: false },
82
+ '.map': { type: 'application/json; charset=utf-8', binary: false },
83
+ '.txt': { type: 'text/plain; charset=utf-8', binary: false },
84
+ '.ico': { type: 'image/x-icon', binary: true },
85
+ '.png': { type: 'image/png', binary: true },
86
+ '.jpg': { type: 'image/jpeg', binary: true },
87
+ '.jpeg': { type: 'image/jpeg', binary: true },
88
+ '.webp': { type: 'image/webp', binary: true },
89
+ '.woff': { type: 'font/woff', binary: true },
90
+ '.woff2': { type: 'font/woff2', binary: true },
91
+ '.otf': { type: 'font/otf', binary: true },
92
+ '.ttf': { type: 'font/ttf', binary: true },
93
+ };
94
+ /**
95
+ * True if the last path segment names a file this server knows how to serve.
96
+ *
97
+ * Keyed off `CONTENT_TYPES` rather than "has a dot". The job here is narrow — catching the handful of
98
+ * top-level files a bundler emits outside `assets/` (`favicon.ico`, `robots.txt`, `vite.svg`) — and an
99
+ * any-dot rule is far wider than that job. It swallows ordinary routes whose last segment happens to
100
+ * contain a dot, which for an app whose identifiers are hostnames is not a corner case: a route like
101
+ * `/clusters/www-test.bu.edu` matches `.edu` under an any-dot rule and 404s where the app should have
102
+ * rendered.
103
+ *
104
+ * Tying the rule to the extensions the server can actually serve makes it exactly as wide as its job:
105
+ * an unknown extension is a route, and adding a servable type extends both at once.
106
+ */
107
+ function looksLikeFile(rawPath) {
108
+ const base = rawPath.split('/').filter(Boolean).pop();
109
+ if (!base)
110
+ return false;
111
+ const dot = base.lastIndexOf('.');
112
+ if (dot <= 0)
113
+ return false;
114
+ return base.slice(dot).toLowerCase() in CONTENT_TYPES;
115
+ }
116
+ /**
117
+ * Does this request want a file rather than a page? For the gate's `unauthenticated` arm, so an
118
+ * expired session requesting a bundle gets a machine-readable 401 instead of an HTML document.
119
+ *
120
+ * Exported because the alternative is every SPA consumer re-deriving the asset rule and drifting from
121
+ * the one `serve` actually applies.
122
+ */
123
+ function isAssetRequest(rawPath) {
124
+ return rawPath.includes('/assets/') || looksLikeFile(rawPath);
125
+ }
126
+ function createSpaServer(config) {
127
+ const { webappDir, noBundle, security = {} } = config;
128
+ const cache = new Map();
129
+ function readFile(relPath) {
130
+ const hit = cache.get(relPath);
131
+ if (hit)
132
+ return hit;
133
+ // Traversal guard. Not cached either way: the check is a string comparison, and caching a
134
+ // rejection would mean caller-supplied keys could grow the map without bound.
135
+ const full = path.normalize(path.join(webappDir, relPath));
136
+ if (full !== webappDir && !full.startsWith(webappDir + path.sep))
137
+ return null;
138
+ const ext = path.extname(full).toLowerCase();
139
+ const ct = CONTENT_TYPES[ext] || { type: 'application/octet-stream', binary: true };
140
+ // Vite content-hashes these, so they can be cached forever. Everything else must revalidate,
141
+ // or a tab held across a deploy keeps a stale index.html pointing at purged bundles.
142
+ const immutable = relPath.startsWith('assets/');
143
+ let buf;
144
+ try {
145
+ buf = (0, fs_1.readFileSync)(full);
146
+ }
147
+ catch {
148
+ return null; // missing, unreadable, or a directory — all "not there" from here
149
+ }
150
+ const result = {
151
+ statusCode: 200,
152
+ headers: {
153
+ 'content-type': ct.type,
154
+ 'cache-control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache',
155
+ // Security headers on static assets too. `serve` can return a document where a script was
156
+ // requested only as a bug; nosniff is what keeps that from becoming a sniffing surface.
157
+ ...(0, responses_1.securityHeaders)(security),
158
+ },
159
+ body: ct.binary ? buf.toString('base64') : buf.toString('utf8'),
160
+ isBase64Encoded: ct.binary,
161
+ };
162
+ // Only resolved reads are cached, so the map is bounded by the bundle's real file count.
163
+ cache.set(relPath, result);
164
+ return result;
165
+ }
166
+ return {
167
+ readFile,
168
+ serve(rawPath) {
169
+ const assetsIdx = rawPath.indexOf('/assets/');
170
+ if (assetsIdx >= 0) {
171
+ // A hashed asset. Present → serve it; absent → 404, NEVER the shell. This is the branch a
172
+ // shared fallback line gets wrong.
173
+ return readFile(rawPath.slice(assetsIdx + 1)) ?? (0, responses_1.notFound)('Asset not found. Reload the page.');
174
+ }
175
+ if (looksLikeFile(rawPath)) {
176
+ // A top-level static file Vite may emit (favicon.ico, vite.svg, robots.txt, …). Same rule:
177
+ // a file that is not there is a 404, not a document.
178
+ const base = rawPath.split('/').filter(Boolean).pop();
179
+ if (base !== 'index.html') {
180
+ const asset = readFile(base);
181
+ if (asset)
182
+ return asset;
183
+ return (0, responses_1.notFound)();
184
+ }
185
+ }
186
+ // An unknown ROUTE. This is the branch where falling back to the shell is correct — the client
187
+ // router owns it.
188
+ return readFile('index.html') ?? noBundle();
189
+ },
190
+ };
191
+ }
192
+ //# sourceMappingURL=spa.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spa.js","sourceRoot":"","sources":["../src/spa.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHA,wCAEC;AAED,0CAuEC;AA7LD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,2BAAkC;AAClC,2CAA6B;AAC7B,2CAAyG;AAEzG;;;;;GAKG;AACU,QAAA,eAAe,GAAG,QAAQ,CAAC;AAExC,MAAM,aAAa,GAAsD;IACvE,OAAO,EAAE,EAAE,IAAI,EAAE,0BAA0B,EAAE,MAAM,EAAE,KAAK,EAAE;IAC5D,KAAK,EAAE,EAAE,IAAI,EAAE,gCAAgC,EAAE,MAAM,EAAE,KAAK,EAAE;IAChE,MAAM,EAAE,EAAE,IAAI,EAAE,gCAAgC,EAAE,MAAM,EAAE,KAAK,EAAE;IACjE,MAAM,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE,MAAM,EAAE,KAAK,EAAE;IAC1D,OAAO,EAAE,EAAE,IAAI,EAAE,iCAAiC,EAAE,MAAM,EAAE,KAAK,EAAE;IACnE,MAAM,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,EAAE,KAAK,EAAE;IAChD,MAAM,EAAE,EAAE,IAAI,EAAE,iCAAiC,EAAE,MAAM,EAAE,KAAK,EAAE;IAClE,MAAM,EAAE,EAAE,IAAI,EAAE,2BAA2B,EAAE,MAAM,EAAE,KAAK,EAAE;IAC5D,MAAM,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,EAAE,IAAI,EAAE;IAC9C,MAAM,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE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A server has two jobs whose correct behaviour on a miss is exactly opposite: an unknown\n * *route* should fall back to the shell so the client router can handle it, and an unknown *file*\n * should 404. Telling those apart is the entire job of `serve`.\n *\n * Any implementation that reaches one shared fallback line from both branches gets this wrong, and\n * the failure is inscrutable rather than loud: a request for a hashed bundle that no longer exists is\n * handed the HTML document, at status 200, with `content-type: text/html`.\n *\n * The realistic trigger is a tab held open across a deploy: `index.html` is served `no-cache`, but a\n * page already loaded in memory keeps requesting the bundle it was built with, and the new deploy no\n * longer contains it. The browser asked for a JavaScript module and got HTML at 200, so it reports a\n * MIME-type failure rather than a missing file, and the operator sees an app that appears broken when\n * the true state is \"reload me.\"\n *\n * ## Cache policy\n *\n * Only resolved reads are cached, which bounds the map by the number of real files in the bundle and\n * needs no eviction. Caching misses as well would be negative caching keyed on caller-supplied input:\n * distinct nonexistent paths, path-traversal rejections included, would accumulate entries for the\n * life of the warm container.\n */\nimport { readFileSync } from 'fs';\nimport * as path from 'path';\nimport { notFound, securityHeaders, type OriginResponse, type SecurityHeaderOptions } from './responses';\n\n/**\n * Directory name, beside the compiled handler, that a consuming app's build copies its bundle into.\n *\n * Shared because it is a two-sided contract: the CDK construct's bundling hook writes here and the\n * handler reads from here. Two independent literals is how those silently stop agreeing.\n */\nexport const WEBAPP_DIR_NAME = 'webapp';\n\nconst CONTENT_TYPES: Record<string, { type: string; binary: boolean }> = {\n '.html': { type: 'text/html; charset=utf-8', binary: false },\n '.js': { type: 'text/javascript; charset=utf-8', binary: false },\n '.mjs': { type: 'text/javascript; charset=utf-8', binary: false },\n '.css': { type: 'text/css; charset=utf-8', binary: false },\n '.json': { type: 'application/json; charset=utf-8', binary: false },\n '.svg': { type: 'image/svg+xml', binary: false },\n '.map': { type: 'application/json; charset=utf-8', binary: false },\n '.txt': { type: 'text/plain; charset=utf-8', binary: false },\n '.ico': { type: 'image/x-icon', binary: true },\n '.png': { type: 'image/png', binary: true },\n '.jpg': { type: 'image/jpeg', binary: true },\n '.jpeg': { type: 'image/jpeg', binary: true },\n '.webp': { type: 'image/webp', binary: true },\n '.woff': { type: 'font/woff', binary: true },\n '.woff2': { type: 'font/woff2', binary: true },\n '.otf': { type: 'font/otf', binary: true },\n '.ttf': { type: 'font/ttf', binary: true },\n};\n\nexport interface SpaServerConfig {\n /** Absolute path to the built bundle. Usually `path.join(__dirname, WEBAPP_DIR_NAME)`. */\n webappDir: string;\n /**\n * Response when no bundle is present at all — a deploy that skipped the frontend build. Distinct\n * from a 404: the app is up and the request was fine, there is just nothing to serve.\n *\n * Takes no request context, deliberately. A consumer converting an existing page into this\n * fallback will notice it can no longer show the caller's identity — that is the intended shape.\n * The server is built once per container, so a request-dependent `noBundle` would invite\n * per-request state onto a long-lived object, and the page is about the deployment rather than\n * about whoever happened to hit it.\n */\n noBundle: () => OriginResponse;\n /** Security-header options applied to served files (e.g. a `connect-src` a consuming app needs). */\n security?: SecurityHeaderOptions;\n}\n\nexport interface SpaServer {\n /** Resolve a request path to an asset, the SPA shell, a 404, or the no-bundle response. */\n serve(rawPath: string): OriginResponse;\n /**\n * Read one file from the bundle, or null. Exposed for tests and for a consuming app that needs to\n * serve something by an explicit name. Refuses anything that escapes `webappDir`.\n */\n readFile(relPath: string): OriginResponse | null;\n}\n\n/**\n * True if the last path segment names a file this server knows how to serve.\n *\n * Keyed off `CONTENT_TYPES` rather than \"has a dot\". The job here is narrow — catching the handful of\n * top-level files a bundler emits outside `assets/` (`favicon.ico`, `robots.txt`, `vite.svg`) — and an\n * any-dot rule is far wider than that job. It swallows ordinary routes whose last segment happens to\n * contain a dot, which for an app whose identifiers are hostnames is not a corner case: a route like\n * `/clusters/www-test.bu.edu` matches `.edu` under an any-dot rule and 404s where the app should have\n * rendered.\n *\n * Tying the rule to the extensions the server can actually serve makes it exactly as wide as its job:\n * an unknown extension is a route, and adding a servable type extends both at once.\n */\nfunction looksLikeFile(rawPath: string): boolean {\n const base = rawPath.split('/').filter(Boolean).pop();\n if (!base) return false;\n const dot = base.lastIndexOf('.');\n if (dot <= 0) return false;\n return base.slice(dot).toLowerCase() in CONTENT_TYPES;\n}\n\n/**\n * Does this request want a file rather than a page? For the gate's `unauthenticated` arm, so an\n * expired session requesting a bundle gets a machine-readable 401 instead of an HTML document.\n *\n * Exported because the alternative is every SPA consumer re-deriving the asset rule and drifting from\n * the one `serve` actually applies.\n */\nexport function isAssetRequest(rawPath: string): boolean {\n return rawPath.includes('/assets/') || looksLikeFile(rawPath);\n}\n\nexport function createSpaServer(config: SpaServerConfig): SpaServer {\n const { webappDir, noBundle, security = {} } = config;\n const cache = new Map<string, OriginResponse>();\n\n function readFile(relPath: string): OriginResponse | null {\n const hit = cache.get(relPath);\n if (hit) return hit;\n\n // Traversal guard. Not cached either way: the check is a string comparison, and caching a\n // rejection would mean caller-supplied keys could grow the map without bound.\n const full = path.normalize(path.join(webappDir, relPath));\n if (full !== webappDir && !full.startsWith(webappDir + path.sep)) return null;\n\n const ext = path.extname(full).toLowerCase();\n const ct = CONTENT_TYPES[ext] || { type: 'application/octet-stream', binary: true };\n // Vite content-hashes these, so they can be cached forever. Everything else must revalidate,\n // or a tab held across a deploy keeps a stale index.html pointing at purged bundles.\n const immutable = relPath.startsWith('assets/');\n\n let buf: Buffer;\n try {\n buf = readFileSync(full);\n } catch {\n return null; // missing, unreadable, or a directory — all \"not there\" from here\n }\n\n const result: OriginResponse = {\n statusCode: 200,\n headers: {\n 'content-type': ct.type,\n 'cache-control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache',\n // Security headers on static assets too. `serve` can return a document where a script was\n // requested only as a bug; nosniff is what keeps that from becoming a sniffing surface.\n ...securityHeaders(security),\n },\n body: ct.binary ? buf.toString('base64') : buf.toString('utf8'),\n isBase64Encoded: ct.binary,\n };\n // Only resolved reads are cached, so the map is bounded by the bundle's real file count.\n cache.set(relPath, result);\n return result;\n }\n\n return {\n readFile,\n\n serve(rawPath: string): OriginResponse {\n const assetsIdx = rawPath.indexOf('/assets/');\n\n if (assetsIdx >= 0) {\n // A hashed asset. Present → serve it; absent → 404, NEVER the shell. This is the branch a\n // shared fallback line gets wrong.\n return readFile(rawPath.slice(assetsIdx + 1)) ?? notFound('Asset not found. Reload the page.');\n }\n\n if (looksLikeFile(rawPath)) {\n // A top-level static file Vite may emit (favicon.ico, vite.svg, robots.txt, …). Same rule:\n // a file that is not there is a 404, not a document.\n const base = rawPath.split('/').filter(Boolean).pop() as string;\n if (base !== 'index.html') {\n const asset = readFile(base);\n if (asset) return asset;\n return notFound();\n }\n }\n\n // An unknown ROUTE. This is the branch where falling back to the shell is correct — the client\n // router owns it.\n return readFile('index.html') ?? noBundle();\n },\n };\n}\n"]}
@@ -0,0 +1,69 @@
1
+ /** Lowercase all header keys so lookups are case-insensitive (HTTP header names are). */
2
+ export declare function lowerCaseKeys(h: Record<string, string | undefined>): Record<string, string | undefined>;
3
+ /**
4
+ * Constant-time compare of a presented challenge value against the expected shared secret. Pure.
5
+ * Fail-closed: an empty expected secret (cold challenge cache) or an absent/empty presented value
6
+ * both return false, so an inability to validate never reads as "valid".
7
+ */
8
+ export declare function challengeMatches(presented: string | undefined, expected: string): boolean;
9
+ /**
10
+ * Accept the presented challenge against ANY currently-valid value.
11
+ *
12
+ * The edge↔origin contract rotates the challenge through a dual-value window — checkers widen to
13
+ * accept {current, previous}, senders flip, then checkers narrow. Matching only one value would 403
14
+ * every request from a not-yet-flipped sender, taking the app down for the length of the window —
15
+ * including during the fast path for containing a leaked value. Empty list → fail closed.
16
+ */
17
+ export declare function challengeMatchesAny(presented: string | undefined, expected: string[]): boolean;
18
+ /** Decode the edge-injected `user-details` header (base64 JSON). Returns null if absent/invalid. */
19
+ export declare function decodeUserDetails(value?: string): unknown;
20
+ /**
21
+ * Decode an edge-injected URL header (login/logout URLs are encodeURIComponent-encoded).
22
+ *
23
+ * The decoded value is handed straight to a browser as an href, so it is validated here: only http(s)
24
+ * or a site-relative path is accepted. Rejecting returns null so callers fall back to their own
25
+ * `/login` / `/logout`. Defense-in-depth — the SP replaces these headers on every path, so a client
26
+ * cannot currently inject one — but this keeps a `javascript:` scheme unreachable without depending on
27
+ * that remaining true. `//host` is rejected too: protocol-relative, so it leaves the site.
28
+ */
29
+ export declare function decodeInjectedUrl(value?: string): string | null;
30
+ /**
31
+ * Pull the eppn (the allow-list key) out of the decoded `user-details` object.
32
+ *
33
+ * Shape confirmed against a live payload: the JWT nests claims under `auth-token.user`, each a
34
+ * single-element ARRAY (the shib multi-valued-attribute convention), e.g.
35
+ * { "auth-token": { user: { eduPersonPrincipalName: ["someone@bu.edu"], ... } }, iat, exp }
36
+ * The canonical principal is `eduPersonPrincipalName`. The shib schema is hardcoded on purpose — a
37
+ * consuming app CONSUMES the edge's contract, it does not configure it. Falls back to a flat
38
+ * `eppn`/`user` layout so a simpler payload (or a future schema change) still resolves.
39
+ *
40
+ * `user-details` is the ONLY identity source a consuming app may trust. The edge also injects the
41
+ * individual claims as separate mod_shib-style headers (`eduPersonPrincipalName`, `buPrincipal`, …),
42
+ * but before `@bostonuniversity/shibboleth-sp` 1.0.7 the SP skipped a blank claim rather than
43
+ * clearing it, so a viewer-supplied header of that name could reach the origin. `user-details` is
44
+ * written from the validated token as a whole and cannot be blank on the authenticated path.
45
+ *
46
+ * Callers must establish `authenticated === 'true'` BEFORE calling this — see requireTrustedEdge.
47
+ * Before 1.0.7 the unauthenticated pass-through left any viewer-supplied `user-details` in place, so
48
+ * decoding first and checking later would read an attacker's identity. 1.0.7 strips it, but an origin
49
+ * cannot verify which SP version it sits behind, so order remains the guard.
50
+ *
51
+ * A consuming app's frontend usually needs the same extraction in the browser, from the same payload.
52
+ * Those two implementations are kept in step by the shared vectors this package publishes at
53
+ * `fixtures/eppn.vectors.json` — test both sides against them, or they drift with nothing failing.
54
+ * See that file's `doc` field for the one known divergence.
55
+ */
56
+ export declare function eppnOf(userDetails: unknown): string | null;
57
+ /**
58
+ * Pull one cookie's value out of a `Cookie` header. Returns null when absent or empty.
59
+ *
60
+ * Two details that are easy to get wrong and are the reason this is a shared function rather than a
61
+ * line in each consumer:
62
+ *
63
+ * - **Split on the FIRST `=` only.** A JWT is base64url and carries none, but a neighbouring cookie
64
+ * may, and splitting on all of them truncates the value.
65
+ * - **Match the name exactly after trimming.** A prefix match would let a cookie named
66
+ * `auth-token-cookie-decoy` satisfy a lookup for `auth-token-cookie`, and the viewer controls
67
+ * what other cookies exist on the domain.
68
+ */
69
+ export declare function cookieValue(header: string | undefined, name: string): string | null;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lowerCaseKeys = lowerCaseKeys;
4
+ exports.challengeMatches = challengeMatches;
5
+ exports.challengeMatchesAny = challengeMatchesAny;
6
+ exports.decodeUserDetails = decodeUserDetails;
7
+ exports.decodeInjectedUrl = decodeInjectedUrl;
8
+ exports.eppnOf = eppnOf;
9
+ exports.cookieValue = cookieValue;
10
+ /**
11
+ * Pure trust-boundary + identity helpers for an application the edge routes to.
12
+ *
13
+ * These are the parts that are the same in every such app: comparing the challenge header against
14
+ * the shared secret, decoding the identity the edge injects, and validating the URLs it hands over.
15
+ * Nothing here reads the environment, touches the network, or holds state, so all of it is directly
16
+ * unit-testable and safe to import from anywhere in the module.
17
+ *
18
+ * Deliberately a leaf: the only import is `crypto`. Anything needing an SDK client, or knowing where
19
+ * one app is mounted, belongs to that app rather than here.
20
+ */
21
+ const crypto_1 = require("crypto");
22
+ /** Lowercase all header keys so lookups are case-insensitive (HTTP header names are). */
23
+ function lowerCaseKeys(h) {
24
+ const out = {};
25
+ for (const [k, v] of Object.entries(h))
26
+ out[k.toLowerCase()] = v;
27
+ return out;
28
+ }
29
+ /**
30
+ * Constant-time compare of a presented challenge value against the expected shared secret. Pure.
31
+ * Fail-closed: an empty expected secret (cold challenge cache) or an absent/empty presented value
32
+ * both return false, so an inability to validate never reads as "valid".
33
+ */
34
+ function challengeMatches(presented, expected) {
35
+ if (!expected)
36
+ return false; // cannot validate → fail closed
37
+ if (typeof presented !== 'string' || presented.length === 0)
38
+ return false;
39
+ const a = Buffer.from(presented);
40
+ const b = Buffer.from(expected);
41
+ return a.length === b.length && (0, crypto_1.timingSafeEqual)(a, b);
42
+ }
43
+ /**
44
+ * Accept the presented challenge against ANY currently-valid value.
45
+ *
46
+ * The edge↔origin contract rotates the challenge through a dual-value window — checkers widen to
47
+ * accept {current, previous}, senders flip, then checkers narrow. Matching only one value would 403
48
+ * every request from a not-yet-flipped sender, taking the app down for the length of the window —
49
+ * including during the fast path for containing a leaked value. Empty list → fail closed.
50
+ */
51
+ function challengeMatchesAny(presented, expected) {
52
+ // No early exit: check every candidate so the work does not vary with which one matches.
53
+ let matched = false;
54
+ for (const candidate of expected) {
55
+ if (challengeMatches(presented, candidate))
56
+ matched = true;
57
+ }
58
+ return matched;
59
+ }
60
+ /** Decode the edge-injected `user-details` header (base64 JSON). Returns null if absent/invalid. */
61
+ function decodeUserDetails(value) {
62
+ if (!value)
63
+ return null;
64
+ try {
65
+ return JSON.parse(Buffer.from(value, 'base64').toString('utf8'));
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ /**
72
+ * Decode an edge-injected URL header (login/logout URLs are encodeURIComponent-encoded).
73
+ *
74
+ * The decoded value is handed straight to a browser as an href, so it is validated here: only http(s)
75
+ * or a site-relative path is accepted. Rejecting returns null so callers fall back to their own
76
+ * `/login` / `/logout`. Defense-in-depth — the SP replaces these headers on every path, so a client
77
+ * cannot currently inject one — but this keeps a `javascript:` scheme unreachable without depending on
78
+ * that remaining true. `//host` is rejected too: protocol-relative, so it leaves the site.
79
+ */
80
+ function decodeInjectedUrl(value) {
81
+ if (!value)
82
+ return null;
83
+ let decoded;
84
+ try {
85
+ decoded = decodeURIComponent(value);
86
+ }
87
+ catch {
88
+ decoded = value;
89
+ }
90
+ decoded = decoded.trim();
91
+ if (!decoded)
92
+ return null;
93
+ if (decoded.startsWith('/') && !decoded.startsWith('//'))
94
+ return decoded;
95
+ return /^https?:\/\/./i.test(decoded) ? decoded : null;
96
+ }
97
+ /**
98
+ * Pull the eppn (the allow-list key) out of the decoded `user-details` object.
99
+ *
100
+ * Shape confirmed against a live payload: the JWT nests claims under `auth-token.user`, each a
101
+ * single-element ARRAY (the shib multi-valued-attribute convention), e.g.
102
+ * { "auth-token": { user: { eduPersonPrincipalName: ["someone@bu.edu"], ... } }, iat, exp }
103
+ * The canonical principal is `eduPersonPrincipalName`. The shib schema is hardcoded on purpose — a
104
+ * consuming app CONSUMES the edge's contract, it does not configure it. Falls back to a flat
105
+ * `eppn`/`user` layout so a simpler payload (or a future schema change) still resolves.
106
+ *
107
+ * `user-details` is the ONLY identity source a consuming app may trust. The edge also injects the
108
+ * individual claims as separate mod_shib-style headers (`eduPersonPrincipalName`, `buPrincipal`, …),
109
+ * but before `@bostonuniversity/shibboleth-sp` 1.0.7 the SP skipped a blank claim rather than
110
+ * clearing it, so a viewer-supplied header of that name could reach the origin. `user-details` is
111
+ * written from the validated token as a whole and cannot be blank on the authenticated path.
112
+ *
113
+ * Callers must establish `authenticated === 'true'` BEFORE calling this — see requireTrustedEdge.
114
+ * Before 1.0.7 the unauthenticated pass-through left any viewer-supplied `user-details` in place, so
115
+ * decoding first and checking later would read an attacker's identity. 1.0.7 strips it, but an origin
116
+ * cannot verify which SP version it sits behind, so order remains the guard.
117
+ *
118
+ * A consuming app's frontend usually needs the same extraction in the browser, from the same payload.
119
+ * Those two implementations are kept in step by the shared vectors this package publishes at
120
+ * `fixtures/eppn.vectors.json` — test both sides against them, or they drift with nothing failing.
121
+ * See that file's `doc` field for the one known divergence.
122
+ */
123
+ function eppnOf(userDetails) {
124
+ const root = (userDetails ?? null);
125
+ if (!root)
126
+ return null;
127
+ const authToken = root['auth-token'];
128
+ const claims = (authToken?.user ?? root.user ?? root);
129
+ const raw = claims?.['eduPersonPrincipalName'] ?? claims?.['eppn'] ?? root.eppn;
130
+ const value = Array.isArray(raw) ? raw.find((v) => typeof v === 'string' && v.length > 0) : raw;
131
+ return typeof value === 'string' && value.length > 0 ? value : null;
132
+ }
133
+ /**
134
+ * Pull one cookie's value out of a `Cookie` header. Returns null when absent or empty.
135
+ *
136
+ * Two details that are easy to get wrong and are the reason this is a shared function rather than a
137
+ * line in each consumer:
138
+ *
139
+ * - **Split on the FIRST `=` only.** A JWT is base64url and carries none, but a neighbouring cookie
140
+ * may, and splitting on all of them truncates the value.
141
+ * - **Match the name exactly after trimming.** A prefix match would let a cookie named
142
+ * `auth-token-cookie-decoy` satisfy a lookup for `auth-token-cookie`, and the viewer controls
143
+ * what other cookies exist on the domain.
144
+ */
145
+ function cookieValue(header, name) {
146
+ if (!header)
147
+ return null;
148
+ for (const part of header.split(';')) {
149
+ const eq = part.indexOf('=');
150
+ if (eq < 0)
151
+ continue;
152
+ if (part.slice(0, eq).trim() !== name)
153
+ continue;
154
+ const value = part.slice(eq + 1).trim();
155
+ return value.length > 0 ? value : null;
156
+ }
157
+ return null;
158
+ }
159
+ //# sourceMappingURL=trustBoundary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trustBoundary.js","sourceRoot":"","sources":["../src/trustBoundary.ts"],"names":[],"mappings":";;AAcA,sCAIC;AAOD,4CAMC;AAUD,kDAOC;AAGD,8CAOC;AAWD,8CAYC;AA4BD,wBAQC;AAcD,kCAUC;AA7ID;;;;;;;;;;GAUG;AACH,mCAAyC;AAEzC,yFAAyF;AACzF,SAAgB,aAAa,CAAC,CAAqC;IACjE,MAAM,GAAG,GAAuC,EAAE,CAAC;IACnD,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QAAE,GAAG,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,GAAG,CAAC,CAAC;IACjE,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;;;GAIG;AACH,SAAgB,gBAAgB,CAAC,SAA6B,EAAE,QAAgB;IAC9E,IAAI,CAAC,QAAQ;QAAE,OAAO,KAAK,CAAC,CAAC,gCAAgC;IAC7D,IAAI,OAAO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AAE,OAAO,IAAI,CAAC;IACzB,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACrC,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC7B,IAAI,EAAE,GAAG,CAAC;YAAE,SAAS;QACrB,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,IAAI;YAAE,SAAS;QAChD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Pure trust-boundary + identity helpers for an application the edge routes to.\n *\n * These are the parts that are the same in every such app: comparing the challenge header against\n * the shared secret, decoding the identity the edge injects, and validating the URLs it hands over.\n * Nothing here reads the environment, touches the network, or holds state, so all of it is directly\n * unit-testable and safe to import from anywhere in the module.\n *\n * Deliberately a leaf: the only import is `crypto`. Anything needing an SDK client, or knowing where\n * one app is mounted, belongs to that app rather than here.\n */\nimport { timingSafeEqual } from 'crypto';\n\n/** Lowercase all header keys so lookups are case-insensitive (HTTP header names are). */\nexport function lowerCaseKeys(h: Record<string, string | undefined>): Record<string, string | undefined> {\n const out: Record<string, string | undefined> = {};\n for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;\n return out;\n}\n\n/**\n * Constant-time compare of a presented challenge value against the expected shared secret. Pure.\n * Fail-closed: an empty expected secret (cold challenge cache) or an absent/empty presented value\n * both return false, so an inability to validate never reads as \"valid\".\n */\nexport function challengeMatches(presented: string | undefined, expected: string): boolean {\n if (!expected) return false; // cannot validate → fail closed\n if (typeof presented !== 'string' || presented.length === 0) return false;\n const a = Buffer.from(presented);\n const b = Buffer.from(expected);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\n/**\n * Accept the presented challenge against ANY currently-valid value.\n *\n * The edge↔origin contract rotates the challenge through a dual-value window — checkers widen to\n * accept {current, previous}, senders flip, then checkers narrow. Matching only one value would 403\n * every request from a not-yet-flipped sender, taking the app down for the length of the window —\n * including during the fast path for containing a leaked value. Empty list → fail closed.\n */\nexport function challengeMatchesAny(presented: string | undefined, expected: string[]): boolean {\n // No early exit: check every candidate so the work does not vary with which one matches.\n let matched = false;\n for (const candidate of expected) {\n if (challengeMatches(presented, candidate)) matched = true;\n }\n return matched;\n}\n\n/** Decode the edge-injected `user-details` header (base64 JSON). Returns null if absent/invalid. */\nexport function decodeUserDetails(value?: string): unknown {\n if (!value) return null;\n try {\n return JSON.parse(Buffer.from(value, 'base64').toString('utf8'));\n } catch {\n return null;\n }\n}\n\n/**\n * Decode an edge-injected URL header (login/logout URLs are encodeURIComponent-encoded).\n *\n * The decoded value is handed straight to a browser as an href, so it is validated here: only http(s)\n * or a site-relative path is accepted. Rejecting returns null so callers fall back to their own\n * `/login` / `/logout`. Defense-in-depth — the SP replaces these headers on every path, so a client\n * cannot currently inject one — but this keeps a `javascript:` scheme unreachable without depending on\n * that remaining true. `//host` is rejected too: protocol-relative, so it leaves the site.\n */\nexport function decodeInjectedUrl(value?: string): string | null {\n if (!value) return null;\n let decoded: string;\n try {\n decoded = decodeURIComponent(value);\n } catch {\n decoded = value;\n }\n decoded = decoded.trim();\n if (!decoded) return null;\n if (decoded.startsWith('/') && !decoded.startsWith('//')) return decoded;\n return /^https?:\\/\\/./i.test(decoded) ? decoded : null;\n}\n\n/**\n * Pull the eppn (the allow-list key) out of the decoded `user-details` object.\n *\n * Shape confirmed against a live payload: the JWT nests claims under `auth-token.user`, each a\n * single-element ARRAY (the shib multi-valued-attribute convention), e.g.\n * { \"auth-token\": { user: { eduPersonPrincipalName: [\"someone@bu.edu\"], ... } }, iat, exp }\n * The canonical principal is `eduPersonPrincipalName`. The shib schema is hardcoded on purpose — a\n * consuming app CONSUMES the edge's contract, it does not configure it. Falls back to a flat\n * `eppn`/`user` layout so a simpler payload (or a future schema change) still resolves.\n *\n * `user-details` is the ONLY identity source a consuming app may trust. The edge also injects the\n * individual claims as separate mod_shib-style headers (`eduPersonPrincipalName`, `buPrincipal`, …),\n * but before `@bostonuniversity/shibboleth-sp` 1.0.7 the SP skipped a blank claim rather than\n * clearing it, so a viewer-supplied header of that name could reach the origin. `user-details` is\n * written from the validated token as a whole and cannot be blank on the authenticated path.\n *\n * Callers must establish `authenticated === 'true'` BEFORE calling this — see requireTrustedEdge.\n * Before 1.0.7 the unauthenticated pass-through left any viewer-supplied `user-details` in place, so\n * decoding first and checking later would read an attacker's identity. 1.0.7 strips it, but an origin\n * cannot verify which SP version it sits behind, so order remains the guard.\n *\n * A consuming app's frontend usually needs the same extraction in the browser, from the same payload.\n * Those two implementations are kept in step by the shared vectors this package publishes at\n * `fixtures/eppn.vectors.json` — test both sides against them, or they drift with nothing failing.\n * See that file's `doc` field for the one known divergence.\n */\nexport function eppnOf(userDetails: unknown): string | null {\n const root = (userDetails ?? null) as Record<string, unknown> | null;\n if (!root) return null;\n const authToken = root['auth-token'] as { user?: unknown } | undefined;\n const claims = (authToken?.user ?? (root as { user?: unknown }).user ?? root) as Record<string, unknown>;\n const raw = claims?.['eduPersonPrincipalName'] ?? claims?.['eppn'] ?? (root as { eppn?: unknown }).eppn;\n const value = Array.isArray(raw) ? raw.find((v) => typeof v === 'string' && v.length > 0) : raw;\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n\n/**\n * Pull one cookie's value out of a `Cookie` header. Returns null when absent or empty.\n *\n * Two details that are easy to get wrong and are the reason this is a shared function rather than a\n * line in each consumer:\n *\n * - **Split on the FIRST `=` only.** A JWT is base64url and carries none, but a neighbouring cookie\n * may, and splitting on all of them truncates the value.\n * - **Match the name exactly after trimming.** A prefix match would let a cookie named\n * `auth-token-cookie-decoy` satisfy a lookup for `auth-token-cookie`, and the viewer controls\n * what other cookies exist on the domain.\n */\nexport function cookieValue(header: string | undefined, name: string): string | null {\n if (!header) return null;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq < 0) continue;\n if (part.slice(0, eq).trim() !== name) continue;\n const value = part.slice(eq + 1).trim();\n return value.length > 0 ? value : null;\n }\n return null;\n}\n"]}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Shared shapes. Deliberately small and free of domain meaning — anything here has to be true of an
3
+ * application not yet written.
4
+ */
5
+ /**
6
+ * One thing wrong with a request body, for a `422 { error, issues }` response. Generic on purpose:
7
+ * a consuming app's own validators return these too, so the app and this library speak one shape
8
+ * rather than two convertible ones.
9
+ */
10
+ export interface ValidationIssue {
11
+ field: string;
12
+ message: string;
13
+ }
14
+ /**
15
+ * Stored access model — familiar CMS roles; the ground truth of who may write. Identities are eppns,
16
+ * stored lowercased (see normalizeAllowList).
17
+ */
18
+ export interface AllowList {
19
+ admins: string[];
20
+ editors: string[];
21
+ }
22
+ /** Per-request capabilities a UI gates on. Derived from an eppn plus an AllowList. */
23
+ export interface Capabilities {
24
+ canEditRules: boolean;
25
+ canManageAccess: boolean;
26
+ }
package/dist/types.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ /**
3
+ * Shared shapes. Deliberately small and free of domain meaning — anything here has to be true of an
4
+ * application not yet written.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * Shared shapes. Deliberately small and free of domain meaning — anything here has to be true of an\n * application not yet written.\n */\n\n/**\n * One thing wrong with a request body, for a `422 { error, issues }` response. Generic on purpose:\n * a consuming app's own validators return these too, so the app and this library speak one shape\n * rather than two convertible ones.\n */\nexport interface ValidationIssue {\n field: string;\n message: string;\n}\n\n/**\n * Stored access model — familiar CMS roles; the ground truth of who may write. Identities are eppns,\n * stored lowercased (see normalizeAllowList).\n */\nexport interface AllowList {\n admins: string[];\n editors: string[];\n}\n\n/** Per-request capabilities a UI gates on. Derived from an eppn plus an AllowList. */\nexport interface Capabilities {\n canEditRules: boolean;\n canManageAccess: boolean;\n}\n"]}
@@ -0,0 +1,68 @@
1
+ {
2
+ "doc": {
3
+ "purpose": "Shared vectors for eppn extraction from the decoded edge-injected `user-details`. Pins the two copies that must resolve the SAME principal: this package's eppnOf (the allow-list authorization key) and a consuming app's own frontend mirror (the UI's identity). If they diverge, the UI would claim an identity the server would not authorize.",
4
+ "schema": "The JWT nests shib claims under `auth-token.user`, each a single-element ARRAY (shib multi-valued-attribute convention). Canonical principal is `eduPersonPrincipalName`, with an `eppn` fallback, and a flat `user`/root layout accepted for simpler payloads.",
5
+ "consumers": "Imported by path rather than through the package index, so a browser-side test does not pull in the Node/AWS surface. This package's own trustBoundary.test.ts loops BOTH arrays; a frontend mirror should loop `cases` only.",
6
+ "scope": "`cases` is the AGREEING SUBSET — every implementation of eppnOf must satisfy all of them. `serverOnlyCases` covers behaviour this package has and a frontend mirror deliberately lacks; it exists so the divergence is pinned by a test rather than described in a comment."
7
+ },
8
+ "cases": [
9
+ {
10
+ "name": "nested auth-token.user.eduPersonPrincipalName (array)",
11
+ "userDetails": { "auth-token": { "user": { "eduPersonPrincipalName": ["nested@bu.edu"] } }, "iat": 1, "exp": 2 },
12
+ "expected": "nested@bu.edu"
13
+ },
14
+ {
15
+ "name": "flat user.eduPersonPrincipalName (array)",
16
+ "userDetails": { "user": { "eduPersonPrincipalName": ["prof@bu.edu"] } },
17
+ "expected": "prof@bu.edu"
18
+ },
19
+ {
20
+ "name": "flat root eduPersonPrincipalName (array)",
21
+ "userDetails": { "eduPersonPrincipalName": ["root@bu.edu"] },
22
+ "expected": "root@bu.edu"
23
+ },
24
+ {
25
+ "name": "eduPersonPrincipalName as a plain string",
26
+ "userDetails": { "eduPersonPrincipalName": "plain@bu.edu" },
27
+ "expected": "plain@bu.edu"
28
+ },
29
+ {
30
+ "name": "eppn fallback when eduPersonPrincipalName absent",
31
+ "userDetails": { "auth-token": { "user": { "eppn": "fallback@bu.edu" } } },
32
+ "expected": "fallback@bu.edu"
33
+ },
34
+ {
35
+ "name": "array with leading empty string picks first non-empty",
36
+ "userDetails": { "eduPersonPrincipalName": ["", "second@bu.edu"] },
37
+ "expected": "second@bu.edu"
38
+ },
39
+ {
40
+ "name": "null user-details",
41
+ "userDetails": null,
42
+ "expected": null
43
+ },
44
+ {
45
+ "name": "empty object",
46
+ "userDetails": {},
47
+ "expected": null
48
+ },
49
+ {
50
+ "name": "empty principal array",
51
+ "userDetails": { "eduPersonPrincipalName": [] },
52
+ "expected": null
53
+ },
54
+ {
55
+ "name": "unrelated claims only (no principal anywhere)",
56
+ "userDetails": { "auth-token": { "user": { "mail": ["x@bu.edu"] } } },
57
+ "expected": null
58
+ }
59
+ ],
60
+ "serverOnlyCases": [
61
+ {
62
+ "name": "root-level eppn when auth-token.user resolves but carries no principal",
63
+ "note": "The third fallback: claims resolve to `auth-token.user`, that object has neither eduPersonPrincipalName nor eppn, so extraction reaches back to a root-level `eppn`. The frontend mirror stops at the claims object and returns null here. Divergence is one-directional and safe in that direction — the server may authorize an identity the UI cannot name, never the reverse.",
64
+ "userDetails": { "auth-token": { "user": { "mail": ["x@bu.edu"] } }, "eppn": "root-fallback@bu.edu" },
65
+ "expected": "root-fallback@bu.edu"
66
+ }
67
+ ]
68
+ }