@smartcrab/server 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/base64.d.ts +14 -0
- package/dist/base64.js +56 -0
- package/dist/cookies.d.ts +33 -0
- package/dist/cookies.js +54 -0
- package/dist/errors.d.ts +86 -0
- package/dist/errors.js +72 -0
- package/dist/http.d.ts +32 -0
- package/dist/http.js +79 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +13 -0
- package/dist/oidc-client.d.ts +36 -0
- package/dist/oidc-client.js +414 -0
- package/dist/result.d.ts +39 -0
- package/dist/result.js +55 -0
- package/dist/sealing.d.ts +7 -0
- package/dist/sealing.js +76 -0
- package/dist/security.d.ts +49 -0
- package/dist/security.js +159 -0
- package/dist/server-auth.d.ts +129 -0
- package/dist/server-auth.js +586 -0
- package/dist/session.d.ts +42 -0
- package/dist/session.js +56 -0
- package/dist/webhook.d.ts +42 -0
- package/dist/webhook.js +95 -0
- package/package.json +44 -0
- package/src/base64.ts +58 -0
- package/src/cookies.ts +72 -0
- package/src/errors.ts +113 -0
- package/src/http.ts +112 -0
- package/src/index.ts +39 -0
- package/src/oidc-client.ts +551 -0
- package/src/result.ts +90 -0
- package/src/sealing.test.ts +57 -0
- package/src/sealing.ts +106 -0
- package/src/security.test.ts +134 -0
- package/src/security.ts +188 -0
- package/src/server-auth.test.ts +1108 -0
- package/src/server-auth.ts +887 -0
- package/src/session.ts +76 -0
- package/src/webhook.test.ts +96 -0
- package/src/webhook.ts +151 -0
package/src/sealing.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { base64UrlDecode, base64UrlEncode } from "./base64.js";
|
|
2
|
+
import type { ServerAuthError } from "./errors.js";
|
|
3
|
+
import { Result, type ResultAsync } from "./result.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Session-value sealing (design.md §22.2 "HttpOnly Cookie管理").
|
|
7
|
+
*
|
|
8
|
+
* Chosen design (the assignment offered HMAC-signed payloads or a server-side
|
|
9
|
+
* store reference): the cookie value is an **AES-256-GCM encrypted** payload
|
|
10
|
+
* with a per-config key derived from `cookieSecret` via HKDF-SHA-256. This
|
|
11
|
+
* makes the value both opaque (confidential — access/refresh tokens never
|
|
12
|
+
* appear in the clear to the browser or to log scrapers) and
|
|
13
|
+
* integrity-protected (GCM's auth tag: any tampering fails decryption, and the
|
|
14
|
+
* SDK fails closed by treating the cookie as absent/invalid). A server-side
|
|
15
|
+
* session store was rejected to keep the BFF stateless across Workers
|
|
16
|
+
* isolates; rotation handling lives in the in-process refresh mutex instead
|
|
17
|
+
* (see server-auth.ts).
|
|
18
|
+
*
|
|
19
|
+
* Wire format: `v1.<base64url(iv)> . <base64url(ciphertext||tag)>`.
|
|
20
|
+
* The `v1` prefix allows future algorithm rotation; any other shape is
|
|
21
|
+
* rejected before touching WebCrypto.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const SEAL_VERSION = "v1";
|
|
25
|
+
const GCM_IV_BYTES = 12;
|
|
26
|
+
|
|
27
|
+
const textEncoder = new TextEncoder();
|
|
28
|
+
const textDecoder = new TextDecoder();
|
|
29
|
+
|
|
30
|
+
const HKDF_SALT = textEncoder.encode("@smartcrab/server/session-seal/v1");
|
|
31
|
+
const HKDF_INFO = textEncoder.encode("aes-256-gcm cookie seal");
|
|
32
|
+
|
|
33
|
+
export interface Sealer {
|
|
34
|
+
readonly seal: (payload: unknown) => ResultAsync<string, ServerAuthError>;
|
|
35
|
+
readonly unseal: (value: string) => ResultAsync<unknown, ServerAuthError>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const importKeyMaterial = Result.fn({
|
|
39
|
+
try: async (secret: string): Promise<CryptoKey> =>
|
|
40
|
+
crypto.subtle.importKey("raw", textEncoder.encode(secret), "HKDF", false, ["deriveKey"]),
|
|
41
|
+
catch: (): ServerAuthError => ({ type: "sealing_failed" }),
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const deriveAesKey = Result.fn({
|
|
45
|
+
try: async (material: CryptoKey): Promise<CryptoKey> =>
|
|
46
|
+
crypto.subtle.deriveKey(
|
|
47
|
+
{ name: "HKDF", hash: "SHA-256", salt: HKDF_SALT, info: HKDF_INFO },
|
|
48
|
+
material,
|
|
49
|
+
{ name: "AES-GCM", length: 256 },
|
|
50
|
+
false,
|
|
51
|
+
["encrypt", "decrypt"],
|
|
52
|
+
),
|
|
53
|
+
catch: (): ServerAuthError => ({ type: "sealing_failed" }),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const encrypt = Result.fn({
|
|
57
|
+
try: async (input: { readonly key: CryptoKey; readonly payload: unknown }): Promise<string> => {
|
|
58
|
+
const iv = new Uint8Array(GCM_IV_BYTES);
|
|
59
|
+
crypto.getRandomValues(iv);
|
|
60
|
+
const ciphertext = await crypto.subtle.encrypt(
|
|
61
|
+
{ name: "AES-GCM", iv },
|
|
62
|
+
input.key,
|
|
63
|
+
textEncoder.encode(JSON.stringify(input.payload)),
|
|
64
|
+
);
|
|
65
|
+
return `${SEAL_VERSION}.${base64UrlEncode(iv)}.${base64UrlEncode(new Uint8Array(ciphertext))}`;
|
|
66
|
+
},
|
|
67
|
+
catch: (): ServerAuthError => ({ type: "sealing_failed" }),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const decrypt = Result.fn({
|
|
71
|
+
try: async (input: { readonly key: CryptoKey; readonly value: string }): Promise<unknown> => {
|
|
72
|
+
const [version, ivPart, ciphertextPart, ...rest] = input.value.split(".");
|
|
73
|
+
if (
|
|
74
|
+
version !== SEAL_VERSION ||
|
|
75
|
+
ivPart === undefined ||
|
|
76
|
+
ciphertextPart === undefined ||
|
|
77
|
+
rest.length > 0
|
|
78
|
+
) {
|
|
79
|
+
throw new Error("malformed sealed value");
|
|
80
|
+
}
|
|
81
|
+
const iv = base64UrlDecode(ivPart);
|
|
82
|
+
const ciphertext = base64UrlDecode(ciphertextPart);
|
|
83
|
+
if (iv.byteLength !== GCM_IV_BYTES) {
|
|
84
|
+
throw new Error("malformed sealed value");
|
|
85
|
+
}
|
|
86
|
+
const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, input.key, ciphertext);
|
|
87
|
+
const parsed: unknown = JSON.parse(textDecoder.decode(plaintext));
|
|
88
|
+
return parsed;
|
|
89
|
+
},
|
|
90
|
+
catch: (): ServerAuthError => ({ type: "seal_verification_failed" }),
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
export const createSealer = (secret: string): Sealer => {
|
|
94
|
+
// The HKDF derivation is deterministic per secret; cache the derived key so
|
|
95
|
+
// the hot path (every authenticated request) does one AES-GCM operation only.
|
|
96
|
+
let cachedKey: ResultAsync<CryptoKey, ServerAuthError> | null = null;
|
|
97
|
+
const key = (): ResultAsync<CryptoKey, ServerAuthError> => {
|
|
98
|
+
cachedKey ??= Result.andThen(importKeyMaterial(secret), deriveAesKey);
|
|
99
|
+
return cachedKey;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
seal: (payload) => Result.andThen(key(), (aesKey) => encrypt({ key: aesKey, payload })),
|
|
104
|
+
unseal: (value) => Result.andThen(key(), (aesKey) => decrypt({ key: aesKey, value })),
|
|
105
|
+
};
|
|
106
|
+
};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
hasInvalidNavigationOrigin,
|
|
4
|
+
isRequestOriginValid,
|
|
5
|
+
sanitizeRedirectTarget,
|
|
6
|
+
timingSafeEqual,
|
|
7
|
+
} from "./security.js";
|
|
8
|
+
|
|
9
|
+
const APP = "https://app.example.com";
|
|
10
|
+
|
|
11
|
+
describe("sanitizeRedirectTarget (design.md §32.2 open redirect禁止)", () => {
|
|
12
|
+
test.each([
|
|
13
|
+
[null, "/"],
|
|
14
|
+
["", "/"],
|
|
15
|
+
["/dashboard", "/dashboard"],
|
|
16
|
+
["/settings?tab=security", "/settings?tab=security"],
|
|
17
|
+
["//evil.example.com", "/"],
|
|
18
|
+
["https://evil.example.com", "/"],
|
|
19
|
+
["http://localhost:3000/x", "/"],
|
|
20
|
+
["/\\evil.example.com", "/"],
|
|
21
|
+
["/path\r\ninjected", "/"],
|
|
22
|
+
["javascript:alert(1)", "/"],
|
|
23
|
+
["/%2f%2fevil.example.com", "/%2f%2fevil.example.com"],
|
|
24
|
+
])("sanitizeRedirectTarget(%j) → %j", (target, expected) => {
|
|
25
|
+
expect(sanitizeRedirectTarget(target, [], "/")).toBe(expected);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("overly long targets fall back", () => {
|
|
29
|
+
expect(sanitizeRedirectTarget(`/${"a".repeat(3000)}`, [], "/")).toBe("/");
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("byte-for-byte allowlisted absolute targets pass", () => {
|
|
33
|
+
expect(
|
|
34
|
+
sanitizeRedirectTarget(
|
|
35
|
+
"https://docs.example.com/welcome",
|
|
36
|
+
["https://docs.example.com/welcome"],
|
|
37
|
+
"/",
|
|
38
|
+
),
|
|
39
|
+
).toBe("https://docs.example.com/welcome");
|
|
40
|
+
// Not byte-for-byte identical → rejected.
|
|
41
|
+
expect(
|
|
42
|
+
sanitizeRedirectTarget(
|
|
43
|
+
"https://docs.example.com/welcome/",
|
|
44
|
+
["https://docs.example.com/welcome"],
|
|
45
|
+
"/",
|
|
46
|
+
),
|
|
47
|
+
).toBe("/");
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe("timingSafeEqual", () => {
|
|
52
|
+
test("equal strings match", () => {
|
|
53
|
+
expect(timingSafeEqual("abc123", "abc123")).toBe(true);
|
|
54
|
+
});
|
|
55
|
+
test("different strings of the same length do not match", () => {
|
|
56
|
+
expect(timingSafeEqual("abc123", "abc124")).toBe(false);
|
|
57
|
+
});
|
|
58
|
+
test("different lengths do not match", () => {
|
|
59
|
+
expect(timingSafeEqual("short", "muchlongerstring")).toBe(false);
|
|
60
|
+
});
|
|
61
|
+
test("unicode is compared by UTF-8 bytes", () => {
|
|
62
|
+
expect(timingSafeEqual("日本語", "日本語")).toBe(true);
|
|
63
|
+
expect(timingSafeEqual("日本語", "日本")).toBe(false);
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("isRequestOriginValid (CSRF — design.md §32.2)", () => {
|
|
68
|
+
test("safe methods pass without an Origin", () => {
|
|
69
|
+
expect(isRequestOriginValid(new Request(`${APP}/auth/login`), [])).toBe(true);
|
|
70
|
+
});
|
|
71
|
+
test("POST with matching Origin passes", () => {
|
|
72
|
+
const request = new Request(`${APP}/auth/login`, {
|
|
73
|
+
method: "POST",
|
|
74
|
+
headers: { origin: APP },
|
|
75
|
+
});
|
|
76
|
+
expect(isRequestOriginValid(request, [])).toBe(true);
|
|
77
|
+
});
|
|
78
|
+
test("POST with a foreign Origin is rejected", () => {
|
|
79
|
+
const request = new Request(`${APP}/auth/login`, {
|
|
80
|
+
method: "POST",
|
|
81
|
+
headers: { origin: "https://evil.example.com" },
|
|
82
|
+
});
|
|
83
|
+
expect(isRequestOriginValid(request, [])).toBe(false);
|
|
84
|
+
});
|
|
85
|
+
test("POST with an allowlisted Origin passes", () => {
|
|
86
|
+
const request = new Request(`${APP}/auth/login`, {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: { origin: "https://admin.example.com" },
|
|
89
|
+
});
|
|
90
|
+
expect(isRequestOriginValid(request, ["https://admin.example.com"])).toBe(true);
|
|
91
|
+
});
|
|
92
|
+
test('POST with Origin "null" is rejected', () => {
|
|
93
|
+
const request = new Request(`${APP}/auth/login`, {
|
|
94
|
+
method: "POST",
|
|
95
|
+
headers: { origin: "null" },
|
|
96
|
+
});
|
|
97
|
+
expect(isRequestOriginValid(request, [])).toBe(false);
|
|
98
|
+
});
|
|
99
|
+
test("POST falls back to a same-origin Referer", () => {
|
|
100
|
+
const request = new Request(`${APP}/auth/login`, {
|
|
101
|
+
method: "POST",
|
|
102
|
+
headers: { referer: `${APP}/page` },
|
|
103
|
+
});
|
|
104
|
+
expect(isRequestOriginValid(request, [])).toBe(true);
|
|
105
|
+
});
|
|
106
|
+
test("POST with a foreign Referer is rejected", () => {
|
|
107
|
+
const request = new Request(`${APP}/auth/login`, {
|
|
108
|
+
method: "POST",
|
|
109
|
+
headers: { referer: "https://evil.example.com/page" },
|
|
110
|
+
});
|
|
111
|
+
expect(isRequestOriginValid(request, [])).toBe(false);
|
|
112
|
+
});
|
|
113
|
+
test("POST without Origin and Referer fails closed", () => {
|
|
114
|
+
expect(isRequestOriginValid(new Request(`${APP}/auth/login`, { method: "POST" }), [])).toBe(
|
|
115
|
+
false,
|
|
116
|
+
);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
describe("hasInvalidNavigationOrigin", () => {
|
|
121
|
+
test("GET without Origin is a normal navigation", () => {
|
|
122
|
+
expect(hasInvalidNavigationOrigin(new Request(`${APP}/auth/callback`), [])).toBe(false);
|
|
123
|
+
});
|
|
124
|
+
test("GET with a foreign Origin is rejected", () => {
|
|
125
|
+
const request = new Request(`${APP}/auth/callback`, {
|
|
126
|
+
headers: { origin: "https://evil.example.com" },
|
|
127
|
+
});
|
|
128
|
+
expect(hasInvalidNavigationOrigin(request, [])).toBe(true);
|
|
129
|
+
});
|
|
130
|
+
test("GET with its own Origin passes", () => {
|
|
131
|
+
const request = new Request(`${APP}/auth/callback`, { headers: { origin: APP } });
|
|
132
|
+
expect(hasInvalidNavigationOrigin(request, [])).toBe(false);
|
|
133
|
+
});
|
|
134
|
+
});
|
package/src/security.ts
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { base64UrlEncode } from "./base64.js";
|
|
2
|
+
import type { ServerAuthError } from "./errors.js";
|
|
3
|
+
import { Result, type ResultAsync } from "./result.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Web security primitives (design.md §32.1, §32.2):
|
|
7
|
+
*
|
|
8
|
+
* - PKCE S256 material + `state`/`nonce` generation (§32.1: "state / nonce必須"),
|
|
9
|
+
* - timing-safe comparison for `state` (design.md §15.9: "callback後は`state`を定数時間比較"),
|
|
10
|
+
* - Origin/Referer validation — the SDK's chosen CSRF defence for the mutation
|
|
11
|
+
* handlers (§32.2 offers "CSRF token" and "Origin / Referer検証"; see the
|
|
12
|
+
* note in `isRequestOriginValid`),
|
|
13
|
+
* - post-login/logout redirect-target sanitization (§32.2: "open redirect禁止").
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const textEncoder = new TextEncoder();
|
|
17
|
+
|
|
18
|
+
/** Cryptographically random opaque string (base64url, default 256 bits). */
|
|
19
|
+
export const generateOpaqueToken = (bytes = 32): string => {
|
|
20
|
+
const buffer = new Uint8Array(bytes);
|
|
21
|
+
crypto.getRandomValues(buffer);
|
|
22
|
+
return base64UrlEncode(buffer);
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const sha256Base64Url = Result.fn({
|
|
26
|
+
try: async (value: string): Promise<string> => {
|
|
27
|
+
const digest = await crypto.subtle.digest("SHA-256", textEncoder.encode(value));
|
|
28
|
+
return base64UrlEncode(new Uint8Array(digest));
|
|
29
|
+
},
|
|
30
|
+
catch: (): ServerAuthError => ({ type: "crypto_operation_failed", operation: "sha256_digest" }),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
export interface PkceMaterial {
|
|
34
|
+
/** 64 base64url chars (48 random bytes) — inside the RFC 7636 43..128 window. */
|
|
35
|
+
readonly verifier: string;
|
|
36
|
+
readonly challenge: string;
|
|
37
|
+
readonly state: string;
|
|
38
|
+
readonly nonce: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const generatePkceMaterial = (): ResultAsync<PkceMaterial, ServerAuthError> => {
|
|
42
|
+
const verifier = generateOpaqueToken(48);
|
|
43
|
+
return Result.mapAsync(sha256Base64Url(verifier), (challenge) => ({
|
|
44
|
+
verifier,
|
|
45
|
+
challenge,
|
|
46
|
+
state: generateOpaqueToken(32),
|
|
47
|
+
nonce: generateOpaqueToken(32),
|
|
48
|
+
}));
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Length-agnostic-ish constant-time string comparison. Lengths leak (they are
|
|
53
|
+
* not secret: both sides are 256-bit random values), contents do not.
|
|
54
|
+
*/
|
|
55
|
+
export const timingSafeEqual = (a: string, b: string): boolean => {
|
|
56
|
+
const aBytes = textEncoder.encode(a);
|
|
57
|
+
const bBytes = textEncoder.encode(b);
|
|
58
|
+
if (aBytes.byteLength !== bBytes.byteLength) return false;
|
|
59
|
+
let diff = 0;
|
|
60
|
+
for (let i = 0; i < aBytes.byteLength; i += 1) {
|
|
61
|
+
diff |= (aBytes[i] ?? 0) ^ (bBytes[i] ?? 0);
|
|
62
|
+
}
|
|
63
|
+
return diff === 0;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// Origin / Referer validation (CSRF — design.md §32.2)
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Extracts the `scheme://host[:port]` prefix from an absolute URL string
|
|
74
|
+
* without `new URL` (which throws on invalid input and would force an async
|
|
75
|
+
* `Result.fn` boundary into this synchronous check). Fail-closed: anything
|
|
76
|
+
* unparseable yields `null` and is rejected by the caller. Ambiguous input
|
|
77
|
+
* (e.g. userinfo tricks like `https://evil@real/`) simply never matches the
|
|
78
|
+
* expected origin, which is the safe direction.
|
|
79
|
+
*/
|
|
80
|
+
const extractOriginPrefix = (url: string): string | null => {
|
|
81
|
+
const match = /^([a-z][a-z0-9+.-]*:\/\/[^\/?#]+)/i.exec(url);
|
|
82
|
+
const origin = match?.[1];
|
|
83
|
+
return origin === undefined ? null : origin.toLowerCase();
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const requestOrigin = (request: Request): string | null => extractOriginPrefix(request.url);
|
|
87
|
+
|
|
88
|
+
const isOriginAllowed = (
|
|
89
|
+
origin: string,
|
|
90
|
+
ownOrigin: string,
|
|
91
|
+
extraAllowedOrigins: readonly string[],
|
|
92
|
+
): boolean => origin === ownOrigin || extraAllowedOrigins.includes(origin);
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The SDK's CSRF defence for mutation handlers, chosen and documented per the
|
|
96
|
+
* assignment (§32.2 "CSRF token" **or** Origin/Referer validation):
|
|
97
|
+
*
|
|
98
|
+
* 1. `SameSite=Lax` on every cookie (see cookies.ts) already blocks cross-site
|
|
99
|
+
* POSTs from carrying the session — the browser-enforced first layer.
|
|
100
|
+
* 2. This check is the explicit second layer: for unsafe methods (POST etc.)
|
|
101
|
+
* the `Origin` header must match the request's own origin (or an explicitly
|
|
102
|
+
* allowlisted origin); if `Origin` is absent we fall back to the `Referer`
|
|
103
|
+
* origin; if neither is present the request is rejected (fail closed).
|
|
104
|
+
* 3. Safe methods (GET/HEAD/OPTIONS) pass — they are top-level navigations
|
|
105
|
+
* protected by `state` + PKCE + the single-use handshake cookie instead.
|
|
106
|
+
*
|
|
107
|
+
* Returns a boolean rather than a Result: the check is pure.
|
|
108
|
+
*/
|
|
109
|
+
export const isRequestOriginValid = (
|
|
110
|
+
request: Request,
|
|
111
|
+
extraAllowedOrigins: readonly string[],
|
|
112
|
+
): boolean => {
|
|
113
|
+
if (SAFE_METHODS.has(request.method)) return true;
|
|
114
|
+
const ownOrigin = requestOrigin(request);
|
|
115
|
+
if (ownOrigin === null) return false;
|
|
116
|
+
const origin = request.headers.get("origin");
|
|
117
|
+
if (origin !== null) {
|
|
118
|
+
if (origin === "null") return false;
|
|
119
|
+
return isOriginAllowed(origin.toLowerCase(), ownOrigin, extraAllowedOrigins);
|
|
120
|
+
}
|
|
121
|
+
const referer = request.headers.get("referer");
|
|
122
|
+
if (referer !== null) {
|
|
123
|
+
const refererOrigin = extractOriginPrefix(referer);
|
|
124
|
+
return refererOrigin !== null && isOriginAllowed(refererOrigin, ownOrigin, extraAllowedOrigins);
|
|
125
|
+
}
|
|
126
|
+
return false;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Stricter-than-navigation check used on GET handlers: if an `Origin` header
|
|
131
|
+
* is present at all on a GET (some fetch-based flows send one), it must match.
|
|
132
|
+
* Plain browser navigations send no `Origin` on GET and pass.
|
|
133
|
+
*/
|
|
134
|
+
export const hasInvalidNavigationOrigin = (
|
|
135
|
+
request: Request,
|
|
136
|
+
extraAllowedOrigins: readonly string[],
|
|
137
|
+
): boolean => {
|
|
138
|
+
const origin = request.headers.get("origin");
|
|
139
|
+
if (origin === null) return false;
|
|
140
|
+
const ownOrigin = requestOrigin(request);
|
|
141
|
+
if (ownOrigin === null || origin === "null") return true;
|
|
142
|
+
return !isOriginAllowed(origin.toLowerCase(), ownOrigin, extraAllowedOrigins);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
// Redirect-target sanitization (design.md §32.2: "open redirect禁止")
|
|
147
|
+
// ---------------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
const MAX_TARGET_LENGTH = 2048;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* A target is safe when it is a relative path starting with exactly one `/`
|
|
153
|
+
* (protocol-relative `//evil.example` is rejected), contains no backslashes
|
|
154
|
+
* (browsers treat `\` as `/`, enabling `\\evil.example` smuggling) and no
|
|
155
|
+
* control characters (header-injection defence).
|
|
156
|
+
*/
|
|
157
|
+
const isSafeRelativePath = (value: string): boolean => {
|
|
158
|
+
if (!value.startsWith("/") || value.startsWith("//")) return false;
|
|
159
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
160
|
+
const code = value.charCodeAt(i);
|
|
161
|
+
if (code <= 0x1f || code === 0x7f || code === 0x5c) return false;
|
|
162
|
+
}
|
|
163
|
+
return true;
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Post-login/post-logout targets may only be relative paths or byte-for-byte
|
|
168
|
+
* members of the configured allowlist (design.md §32.2 "open redirect禁止",
|
|
169
|
+
* §15.9 "byte-for-byte完全一致" applied to the allowlist). Anything else
|
|
170
|
+
* silently degrades to `fallback` — the SDK never redirects to an
|
|
171
|
+
* attacker-supplied absolute URL.
|
|
172
|
+
*/
|
|
173
|
+
export const sanitizeRedirectTarget = (
|
|
174
|
+
target: string | null,
|
|
175
|
+
allowlist: readonly string[],
|
|
176
|
+
fallback: string,
|
|
177
|
+
): string => {
|
|
178
|
+
if (target === null || target.length === 0 || target.length > MAX_TARGET_LENGTH) return fallback;
|
|
179
|
+
if (isSafeRelativePath(target)) return target;
|
|
180
|
+
if (allowlist.includes(target)) return target;
|
|
181
|
+
return fallback;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/** True when `value` is a safe relative path or an https absolute URL. */
|
|
185
|
+
export const isAllowedConfiguredTarget = (value: string): boolean => {
|
|
186
|
+
if (isSafeRelativePath(value)) return true;
|
|
187
|
+
return value.startsWith("https://");
|
|
188
|
+
};
|