formacao
This commit is contained in:
+18
-9
@@ -6,7 +6,7 @@ var PREFIX = "Bearer";
|
||||
var HEADER = "Authorization";
|
||||
var bearerAuth = (options) => {
|
||||
if (!("token" in options || "verifyToken" in options)) {
|
||||
throw new Error('bearer auth middleware requires options for "token"');
|
||||
throw new Error('bearer auth middleware requires options for "token" or "verifyToken"');
|
||||
}
|
||||
if (!options.realm) {
|
||||
options.realm = "";
|
||||
@@ -15,9 +15,9 @@ var bearerAuth = (options) => {
|
||||
options.prefix = PREFIX;
|
||||
}
|
||||
const realm = options.realm?.replace(/"/g, '\\"');
|
||||
const prefixRegexStr = options.prefix === "" ? "" : `${options.prefix} +`;
|
||||
const regexp = new RegExp(`^${prefixRegexStr}(${TOKEN_STRINGS}) *$`, "i");
|
||||
const wwwAuthenticatePrefix = options.prefix === "" ? "" : `${options.prefix} `;
|
||||
const prefix = options.prefix;
|
||||
const tokenRegexp = new RegExp(`^${TOKEN_STRINGS}$`);
|
||||
const wwwAuthenticatePrefix = prefix === "" ? "" : `${prefix} `;
|
||||
const throwHTTPException = async (c, status, wwwAuthenticateHeader, messageOption) => {
|
||||
const wwwAuthenticateHeaderValue = typeof wwwAuthenticateHeader === "function" ? await wwwAuthenticateHeader(c) : wwwAuthenticateHeader;
|
||||
const headers = {
|
||||
@@ -43,8 +43,17 @@ var bearerAuth = (options) => {
|
||||
options.noAuthenticationHeader?.message || options.noAuthenticationHeaderMessage || "Unauthorized"
|
||||
);
|
||||
} else {
|
||||
const match = regexp.exec(headerToken);
|
||||
if (!match) {
|
||||
let tokenValue;
|
||||
if (prefix === "") {
|
||||
tokenValue = headerToken;
|
||||
} else {
|
||||
const headerLower = headerToken.toLowerCase();
|
||||
const prefixLower = prefix.toLowerCase();
|
||||
if (headerLower.startsWith(prefixLower) && headerToken[prefix.length] === " ") {
|
||||
tokenValue = headerToken.slice(prefix.length).trimStart();
|
||||
}
|
||||
}
|
||||
if (!tokenValue || !tokenRegexp.test(tokenValue)) {
|
||||
await throwHTTPException(
|
||||
c,
|
||||
400,
|
||||
@@ -54,12 +63,12 @@ var bearerAuth = (options) => {
|
||||
} else {
|
||||
let equal = false;
|
||||
if ("verifyToken" in options) {
|
||||
equal = await options.verifyToken(match[1], c);
|
||||
equal = await options.verifyToken(tokenValue, c);
|
||||
} else if (typeof options.token === "string") {
|
||||
equal = await timingSafeEqual(options.token, match[1], options.hashFunction);
|
||||
equal = await timingSafeEqual(options.token, tokenValue, options.hashFunction);
|
||||
} else if (Array.isArray(options.token) && options.token.length > 0) {
|
||||
for (const token of options.token) {
|
||||
if (await timingSafeEqual(token, match[1], options.hashFunction)) {
|
||||
if (await timingSafeEqual(token, tokenValue, options.hashFunction)) {
|
||||
equal = true;
|
||||
break;
|
||||
}
|
||||
|
||||
+21
-30
@@ -1,12 +1,6 @@
|
||||
// src/middleware/body-limit/index.ts
|
||||
import { HTTPException } from "../../http-exception.js";
|
||||
var ERROR_MESSAGE = "Payload Too Large";
|
||||
var BodyLimitError = class extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = "BodyLimitError";
|
||||
}
|
||||
};
|
||||
var bodyLimit = (options) => {
|
||||
const onError = options.onError || (() => {
|
||||
const res = new Response(ERROR_MESSAGE, {
|
||||
@@ -21,40 +15,37 @@ var bodyLimit = (options) => {
|
||||
}
|
||||
const hasTransferEncoding = c.req.raw.headers.has("transfer-encoding");
|
||||
const hasContentLength = c.req.raw.headers.has("content-length");
|
||||
if (hasTransferEncoding && hasContentLength) {
|
||||
}
|
||||
if (hasContentLength && !hasTransferEncoding) {
|
||||
const contentLength = parseInt(c.req.raw.headers.get("content-length") || "0", 10);
|
||||
return contentLength > maxSize ? onError(c) : next();
|
||||
}
|
||||
let size = 0;
|
||||
const chunks = [];
|
||||
const rawReader = c.req.raw.body.getReader();
|
||||
const reader = new ReadableStream({
|
||||
async start(controller) {
|
||||
try {
|
||||
for (; ; ) {
|
||||
const { done, value } = await rawReader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
size += value.length;
|
||||
if (size > maxSize) {
|
||||
controller.error(new BodyLimitError(ERROR_MESSAGE));
|
||||
break;
|
||||
}
|
||||
controller.enqueue(value);
|
||||
for (; ; ) {
|
||||
const { done, value } = await rawReader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
size += value.length;
|
||||
if (size > maxSize) {
|
||||
return onError(c);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
const requestInit = {
|
||||
body: new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of chunks) {
|
||||
controller.enqueue(chunk);
|
||||
}
|
||||
} finally {
|
||||
controller.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
const requestInit = { body: reader, duplex: "half" };
|
||||
}),
|
||||
duplex: "half"
|
||||
};
|
||||
c.req.raw = new Request(c.req.raw, requestInit);
|
||||
await next();
|
||||
if (c.error instanceof BodyLimitError) {
|
||||
c.res = await onError(c);
|
||||
}
|
||||
return next();
|
||||
};
|
||||
};
|
||||
export {
|
||||
|
||||
+40
-27
@@ -1,30 +1,30 @@
|
||||
// src/middleware/cache/index.ts
|
||||
var defaultCacheableStatusCodes = [200];
|
||||
var shouldSkipCache = (res) => {
|
||||
const vary = res.headers.get("Vary");
|
||||
if (vary && vary.includes("*")) {
|
||||
return true;
|
||||
var shouldSkipCacheControl = (cacheControl) => !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl);
|
||||
var parseVaryDirectives = (vary) => {
|
||||
if (vary == null) {
|
||||
return [];
|
||||
}
|
||||
const cacheControl = res.headers.get("Cache-Control");
|
||||
if (cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl)) {
|
||||
return true;
|
||||
}
|
||||
if (res.headers.has("Set-Cookie")) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return (Array.isArray(vary) ? vary : vary.split(",")).map((directive) => directive.trim().toLowerCase()).filter(Boolean);
|
||||
};
|
||||
var shouldSkipCache = (res, optionsVaryDirectives, responseVary) => responseVary.length && (!optionsVaryDirectives || responseVary.some((name) => !optionsVaryDirectives.has(name))) || shouldSkipCacheControl(res.headers.get("Cache-Control")) || res.headers.has("Set-Cookie");
|
||||
var cache = (options) => {
|
||||
if (!globalThis.caches) {
|
||||
console.log("Cache Middleware is not enabled because caches is not defined.");
|
||||
if (options.onCacheNotAvailable === false) {
|
||||
} else if (options.onCacheNotAvailable) {
|
||||
options.onCacheNotAvailable();
|
||||
} else {
|
||||
console.log("Cache Middleware is not enabled because caches is not defined.");
|
||||
}
|
||||
return async (_c, next) => await next();
|
||||
}
|
||||
if (options.wait === void 0) {
|
||||
options.wait = false;
|
||||
}
|
||||
const cacheControlDirectives = options.cacheControl?.split(",").map((directive) => directive.toLowerCase());
|
||||
const varyDirectives = Array.isArray(options.vary) ? options.vary : options.vary?.split(",").map((directive) => directive.trim());
|
||||
if (options.vary?.includes("*")) {
|
||||
const optionsVaryList = parseVaryDirectives(options.vary);
|
||||
const varyDirectives = optionsVaryList.length ? new Set(optionsVaryList) : void 0;
|
||||
if (varyDirectives?.has("*")) {
|
||||
throw new Error(
|
||||
'Middleware vary configuration cannot include "*", as it disallows effective caching.'
|
||||
);
|
||||
@@ -32,7 +32,7 @@ var cache = (options) => {
|
||||
const cacheableStatusCodes = new Set(
|
||||
options.cacheableStatusCodes ?? defaultCacheableStatusCodes
|
||||
);
|
||||
const addHeader = (c) => {
|
||||
const addHeader = (c, responseVary) => {
|
||||
if (cacheControlDirectives) {
|
||||
const existingDirectives = c.res.headers.get("Cache-Control")?.split(",").map((d) => d.trim().split("=", 1)[0]) ?? [];
|
||||
for (const directive of cacheControlDirectives) {
|
||||
@@ -44,24 +44,36 @@ var cache = (options) => {
|
||||
}
|
||||
}
|
||||
if (varyDirectives) {
|
||||
const existingDirectives = c.res.headers.get("Vary")?.split(",").map((d) => d.trim()) ?? [];
|
||||
const vary = Array.from(
|
||||
new Set(
|
||||
[...existingDirectives, ...varyDirectives].map((directive) => directive.toLowerCase())
|
||||
)
|
||||
).sort();
|
||||
if (vary.includes("*")) {
|
||||
c.header("Vary", "*");
|
||||
if (responseVary.length === 0) {
|
||||
c.header("Vary", Array.from(varyDirectives).join(", "));
|
||||
} else {
|
||||
c.header("Vary", vary.join(", "));
|
||||
const merged = new Set(varyDirectives);
|
||||
for (const directive of responseVary) {
|
||||
merged.add(directive);
|
||||
}
|
||||
if (merged.has("*")) {
|
||||
c.header("Vary", "*");
|
||||
} else {
|
||||
c.header("Vary", Array.from(merged).join(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
return async function cache2(c, next) {
|
||||
if (c.req.method !== "GET" || c.req.raw.headers.has("Authorization")) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
let key = c.req.url;
|
||||
if (options.keyGenerator) {
|
||||
key = await options.keyGenerator(c);
|
||||
}
|
||||
if (varyDirectives) {
|
||||
for (const directive of varyDirectives) {
|
||||
const value = c.req.raw.headers.get(directive) ?? "";
|
||||
key += `::${directive}=${encodeURIComponent(value)}`;
|
||||
}
|
||||
}
|
||||
const cacheName = typeof options.cacheName === "function" ? await options.cacheName(c) : options.cacheName;
|
||||
const cache3 = await caches.open(cacheName);
|
||||
const response = await cache3.match(key);
|
||||
@@ -72,8 +84,9 @@ var cache = (options) => {
|
||||
if (!cacheableStatusCodes.has(c.res.status)) {
|
||||
return;
|
||||
}
|
||||
addHeader(c);
|
||||
if (shouldSkipCache(c.res)) {
|
||||
const responseVary = parseVaryDirectives(c.res.headers.get("Vary"));
|
||||
addHeader(c, responseVary);
|
||||
if (shouldSkipCache(c.res, varyDirectives, responseVary)) {
|
||||
return;
|
||||
}
|
||||
const res = c.res.clone();
|
||||
|
||||
+34
-5
@@ -1,9 +1,37 @@
|
||||
// src/middleware/compress/index.ts
|
||||
import { parseAccept } from "../../utils/accept.js";
|
||||
import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from "../../utils/compress.js";
|
||||
var ENCODING_TYPES = ["gzip", "deflate"];
|
||||
var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i;
|
||||
var selectEncoding = (header, candidates) => {
|
||||
if (header === void 0) {
|
||||
return void 0;
|
||||
}
|
||||
const accepts = parseAccept(header);
|
||||
const wildcardQ = accepts.find((a) => a.type === "*")?.q;
|
||||
let best;
|
||||
for (const enc of candidates) {
|
||||
const explicit = accepts.find((a) => a.type.toLowerCase() === enc);
|
||||
const q = explicit ? explicit.q : wildcardQ ?? 0;
|
||||
if (q === 1) {
|
||||
return enc;
|
||||
} else if (q > 0 && (!best || q > best.q)) {
|
||||
best = { encoding: enc, q };
|
||||
}
|
||||
}
|
||||
return best?.encoding;
|
||||
};
|
||||
var compress = (options) => {
|
||||
const threshold = options?.threshold ?? 1024;
|
||||
const candidates = options?.encoding ? [options.encoding] : ENCODING_TYPES;
|
||||
const contentTypeFilter = options?.contentTypeFilter ?? COMPRESSIBLE_CONTENT_TYPE_REGEX;
|
||||
const shouldCompress = typeof contentTypeFilter === "function" ? (res) => {
|
||||
const type = res.headers.get("Content-Type");
|
||||
return type && contentTypeFilter(type);
|
||||
} : (res) => {
|
||||
const type = res.headers.get("Content-Type");
|
||||
return type && contentTypeFilter.test(type);
|
||||
};
|
||||
return async function compress2(ctx, next) {
|
||||
await next();
|
||||
const contentLength = ctx.res.headers.get("Content-Length");
|
||||
@@ -16,7 +44,7 @@ var compress = (options) => {
|
||||
return;
|
||||
}
|
||||
const accepted = ctx.req.header("Accept-Encoding");
|
||||
const encoding = options?.encoding ?? ENCODING_TYPES.find((encoding2) => accepted?.includes(encoding2));
|
||||
const encoding = selectEncoding(accepted, candidates);
|
||||
if (!encoding || !ctx.res.body) {
|
||||
return;
|
||||
}
|
||||
@@ -24,16 +52,17 @@ var compress = (options) => {
|
||||
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res);
|
||||
ctx.res.headers.delete("Content-Length");
|
||||
ctx.res.headers.set("Content-Encoding", encoding);
|
||||
const etag = ctx.res.headers.get("ETag");
|
||||
if (etag && !etag.startsWith("W/")) {
|
||||
ctx.res.headers.set("ETag", `W/${etag}`);
|
||||
}
|
||||
};
|
||||
};
|
||||
var shouldCompress = (res) => {
|
||||
const type = res.headers.get("Content-Type");
|
||||
return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type);
|
||||
};
|
||||
var shouldTransform = (res) => {
|
||||
const cacheControl = res.headers.get("Cache-Control");
|
||||
return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl);
|
||||
};
|
||||
export {
|
||||
COMPRESSIBLE_CONTENT_TYPE_REGEX,
|
||||
compress
|
||||
};
|
||||
|
||||
+2
-5
@@ -1,13 +1,10 @@
|
||||
// src/middleware/cors/index.ts
|
||||
var cors = (options) => {
|
||||
const defaults = {
|
||||
const opts = {
|
||||
origin: "*",
|
||||
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
|
||||
allowHeaders: [],
|
||||
exposeHeaders: []
|
||||
};
|
||||
const opts = {
|
||||
...defaults,
|
||||
exposeHeaders: [],
|
||||
...options
|
||||
};
|
||||
const findAllowOrigin = ((optsOrigin) => {
|
||||
|
||||
+79
-24
@@ -1,16 +1,53 @@
|
||||
// src/middleware/ip-restriction/index.ts
|
||||
import { HTTPException } from "../../http-exception.js";
|
||||
import {
|
||||
convertIPv4MappedIPv6ToIPv4,
|
||||
convertIPv4ToBinary,
|
||||
convertIPv6BinaryToString,
|
||||
convertIPv6ToBinary,
|
||||
distinctRemoteAddr
|
||||
distinctRemoteAddr,
|
||||
isIPv4MappedIPv6,
|
||||
INVALID_IP_ADDRESS_ERROR_CODE
|
||||
} from "../../utils/ipaddr.js";
|
||||
var IS_CIDR_NOTATION_REGEX = /\/[0-9]{0,3}$/;
|
||||
var IS_CIDR_NOTATION_REGEX = /\/[^/]*$/;
|
||||
var parseCidrPrefix = (rule, prefix, max) => {
|
||||
if (!/^[0-9]{1,3}$/.test(prefix)) {
|
||||
throw new TypeError(`Invalid rule: ${rule}`);
|
||||
}
|
||||
const parsedPrefix = parseInt(prefix);
|
||||
if (parsedPrefix > max) {
|
||||
throw new TypeError(`Invalid rule: ${rule}`);
|
||||
}
|
||||
return parsedPrefix;
|
||||
};
|
||||
var buildMatcher = (rules) => {
|
||||
const functionRules = [];
|
||||
const staticRules = /* @__PURE__ */ new Set();
|
||||
const staticIPv4Rules = /* @__PURE__ */ new Set();
|
||||
const staticIPv6Rules = /* @__PURE__ */ new Set();
|
||||
const cidrRules = [];
|
||||
const registerStaticRule = (rule) => {
|
||||
const type = distinctRemoteAddr(rule);
|
||||
if (type === void 0) {
|
||||
throw new TypeError(`Invalid rule: ${rule}`);
|
||||
}
|
||||
if (type === "IPv4") {
|
||||
const ipv4binary = convertIPv4ToBinary(rule);
|
||||
staticRules.add(rule);
|
||||
staticRules.add(`::ffff:${rule}`);
|
||||
staticIPv4Rules.add(ipv4binary);
|
||||
staticIPv6Rules.add(0xffffn << 32n | ipv4binary);
|
||||
} else {
|
||||
const ipv6binary = convertIPv6ToBinary(rule);
|
||||
const ipv6Addr = convertIPv6BinaryToString(ipv6binary);
|
||||
staticRules.add(ipv6Addr);
|
||||
staticIPv6Rules.add(ipv6binary);
|
||||
if (isIPv4MappedIPv6(ipv6binary)) {
|
||||
staticRules.add(ipv6Addr.substring(7));
|
||||
staticIPv4Rules.add(convertIPv4MappedIPv6ToIPv4(ipv6binary));
|
||||
}
|
||||
}
|
||||
};
|
||||
for (let rule of rules) {
|
||||
if (rule === "*") {
|
||||
return () => true;
|
||||
@@ -20,40 +57,51 @@ var buildMatcher = (rules) => {
|
||||
if (IS_CIDR_NOTATION_REGEX.test(rule)) {
|
||||
const separatedRule = rule.split("/");
|
||||
const addrStr = separatedRule[0];
|
||||
const type2 = distinctRemoteAddr(addrStr);
|
||||
if (type2 === void 0) {
|
||||
const type = distinctRemoteAddr(addrStr);
|
||||
if (type === void 0) {
|
||||
throw new TypeError(`Invalid rule: ${rule}`);
|
||||
}
|
||||
const isIPv4 = type2 === "IPv4";
|
||||
const prefix = parseInt(separatedRule[1]);
|
||||
let isIPv4 = type === "IPv4";
|
||||
let prefix = parseCidrPrefix(rule, separatedRule[1], isIPv4 ? 32 : 128);
|
||||
if (isIPv4 ? prefix === 32 : prefix === 128) {
|
||||
rule = addrStr;
|
||||
} else {
|
||||
const addr = (isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(addrStr);
|
||||
let addr = (isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(addrStr);
|
||||
if (type === "IPv6" && isIPv4MappedIPv6(addr) && prefix >= 96) {
|
||||
isIPv4 = true;
|
||||
addr = convertIPv4MappedIPv6ToIPv4(addr);
|
||||
prefix -= 96;
|
||||
}
|
||||
const mask = (1n << BigInt(prefix)) - 1n << BigInt((isIPv4 ? 32 : 128) - prefix);
|
||||
cidrRules.push([isIPv4, addr & mask, mask]);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const type = distinctRemoteAddr(rule);
|
||||
if (type === void 0) {
|
||||
throw new TypeError(`Invalid rule: ${rule}`);
|
||||
}
|
||||
staticRules.add(
|
||||
type === "IPv4" ? rule : convertIPv6BinaryToString(convertIPv6ToBinary(rule))
|
||||
// normalize IPv6 address (e.g. 0000:0000:0000:0000:0000:0000:0000:0001 => ::1)
|
||||
);
|
||||
registerStaticRule(rule);
|
||||
}
|
||||
}
|
||||
return (remote) => {
|
||||
if (staticRules.has(remote.addr)) {
|
||||
return true;
|
||||
}
|
||||
const remoteAddr = remote.binaryAddr ||= (remote.isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(remote.addr);
|
||||
const remoteIPv4Addr = remote.isIPv4 || isIPv4MappedIPv6(remoteAddr) ? remote.isIPv4 ? remoteAddr : convertIPv4MappedIPv6ToIPv4(remoteAddr) : void 0;
|
||||
if ((remote.isIPv4 ? staticIPv4Rules : staticIPv6Rules).has(remoteAddr)) {
|
||||
return true;
|
||||
}
|
||||
for (const [isIPv4, addr, mask] of cidrRules) {
|
||||
if (isIPv4 !== remote.isIPv4) {
|
||||
if (isIPv4) {
|
||||
if (remoteIPv4Addr === void 0) {
|
||||
continue;
|
||||
}
|
||||
if ((remoteIPv4Addr & mask) === addr) {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (remote.isIPv4) {
|
||||
continue;
|
||||
}
|
||||
const remoteAddr = remote.binaryAddr ||= (isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(remote.addr);
|
||||
if ((remoteAddr & mask) === addr) {
|
||||
return true;
|
||||
}
|
||||
@@ -83,14 +131,21 @@ var ipRestriction = (getIP, { denyList = [], allowList = [] }, onError) => {
|
||||
}
|
||||
const type = typeof connInfo !== "string" && connInfo.remote.addressType || distinctRemoteAddr(addr);
|
||||
const remoteData = { addr, type, isIPv4: type === "IPv4" };
|
||||
if (denyMatcher(remoteData)) {
|
||||
if (onError) {
|
||||
return onError({ addr, type }, c);
|
||||
try {
|
||||
if (denyMatcher(remoteData)) {
|
||||
if (onError) {
|
||||
return onError({ addr, type }, c);
|
||||
}
|
||||
throw blockError(c);
|
||||
}
|
||||
throw blockError(c);
|
||||
}
|
||||
if (allowMatcher(remoteData)) {
|
||||
return await next();
|
||||
if (allowMatcher(remoteData)) {
|
||||
return await next();
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError && e.code === INVALID_IP_ADDRESS_ERROR_CODE) {
|
||||
throw blockError(c);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
if (allowLength === 0) {
|
||||
return await next();
|
||||
|
||||
+1
@@ -4,6 +4,7 @@ import { Fragment, createContext, jsx, useContext } from "../../jsx/index.js";
|
||||
import { renderToReadableStream } from "../../jsx/streaming.js";
|
||||
var RequestContext = createContext(null);
|
||||
var createRenderer = (c, Layout, component, options) => (children, props) => {
|
||||
options = typeof options === "function" ? options(c) : options;
|
||||
const docType = typeof options?.docType === "string" ? options.docType : options?.docType === false ? "" : "<!DOCTYPE html>";
|
||||
const currentLayout = component ? jsx(
|
||||
(props2) => component(props2, c),
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ var jwk = (options, init) => {
|
||||
let token;
|
||||
if (credentials) {
|
||||
const parts = credentials.split(/\s+/);
|
||||
if (parts.length !== 2) {
|
||||
if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") {
|
||||
const errDescription = "invalid credentials structure";
|
||||
throw new HTTPException(401, {
|
||||
message: errDescription,
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ var jwt = (options) => {
|
||||
let token;
|
||||
if (credentials) {
|
||||
const parts = credentials.split(/\s+/);
|
||||
if (parts.length !== 2) {
|
||||
if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") {
|
||||
const errDescription = "invalid credentials structure";
|
||||
throw new HTTPException(401, {
|
||||
message: errDescription,
|
||||
|
||||
+10
-32
@@ -53,20 +53,12 @@ var normalizeLanguage = (lang, options) => {
|
||||
}
|
||||
};
|
||||
var detectFromQuery = (c, options) => {
|
||||
try {
|
||||
const query = c.req.query(options.lookupQueryString);
|
||||
return normalizeLanguage(query, options);
|
||||
} catch {
|
||||
return void 0;
|
||||
}
|
||||
const query = c.req.query(options.lookupQueryString);
|
||||
return normalizeLanguage(query, options);
|
||||
};
|
||||
var detectFromCookie = (c, options) => {
|
||||
try {
|
||||
const cookie = getCookie(c, options.lookupCookie);
|
||||
return normalizeLanguage(cookie, options);
|
||||
} catch {
|
||||
return void 0;
|
||||
}
|
||||
const cookie = getCookie(c, options.lookupCookie);
|
||||
return normalizeLanguage(cookie, options);
|
||||
};
|
||||
function detectFromHeader(c, options) {
|
||||
try {
|
||||
@@ -87,14 +79,10 @@ function detectFromHeader(c, options) {
|
||||
}
|
||||
}
|
||||
function detectFromPath(c, options) {
|
||||
try {
|
||||
const url = new URL(c.req.url);
|
||||
const pathSegments = url.pathname.split("/").filter(Boolean);
|
||||
const langSegment = pathSegments[options.lookupFromPathIndex];
|
||||
return normalizeLanguage(langSegment, options);
|
||||
} catch {
|
||||
return void 0;
|
||||
}
|
||||
const url = new URL(c.req.url);
|
||||
const pathSegments = url.pathname.split("/").filter(Boolean);
|
||||
const langSegment = pathSegments[options.lookupFromPathIndex];
|
||||
return normalizeLanguage(langSegment, options);
|
||||
}
|
||||
var detectors = {
|
||||
querystring: detectFromQuery,
|
||||
@@ -129,9 +117,6 @@ var detectLanguage = (c, options) => {
|
||||
let detectedLang;
|
||||
for (const detectorName of options.order) {
|
||||
const detector = detectors[detectorName];
|
||||
if (!detector) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
detectedLang = detector(c, options);
|
||||
if (detectedLang) {
|
||||
@@ -164,15 +149,8 @@ var languageDetector = (userOptions) => {
|
||||
};
|
||||
validateOptions(options);
|
||||
return async function languageDetector2(ctx, next) {
|
||||
try {
|
||||
const lang = detectLanguage(ctx, options);
|
||||
ctx.set("language", lang);
|
||||
} catch (error) {
|
||||
if (options.debug) {
|
||||
console.error("Language detection failed:", error);
|
||||
}
|
||||
ctx.set("language", options.fallbackLanguage);
|
||||
}
|
||||
const lang = detectLanguage(ctx, options);
|
||||
ctx.set("language", lang);
|
||||
await next();
|
||||
};
|
||||
};
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ var methodOverride = (options) => async function methodOverride2(c, next) {
|
||||
return app.fetch(request, c.env, getExecutionCtx(c));
|
||||
}
|
||||
}
|
||||
if (contentType === "application/x-www-form-urlencoded") {
|
||||
if (contentType?.startsWith("application/x-www-form-urlencoded")) {
|
||||
const params = await parseBody(clonedRequest);
|
||||
const method = params[methodFormName];
|
||||
if (method) {
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ var serveStatic = (options) => {
|
||||
} else {
|
||||
try {
|
||||
filename = tryDecodeURI(c.req.path);
|
||||
if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {
|
||||
if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) {
|
||||
throw new Error();
|
||||
}
|
||||
} catch {
|
||||
|
||||
+3
-1
@@ -31,7 +31,9 @@ var timing = (config) => {
|
||||
endTime(c, "total");
|
||||
}
|
||||
if (options.autoEnd) {
|
||||
timers.forEach((_, key) => endTime(c, key));
|
||||
timers.forEach((_, key) => {
|
||||
endTime(c, key);
|
||||
});
|
||||
}
|
||||
const enabled = typeof options.enabled === "function" ? options.enabled(c) : options.enabled;
|
||||
if (enabled) {
|
||||
|
||||
+2
-2
@@ -19,14 +19,14 @@ var trimTrailingSlash = (options) => {
|
||||
var appendTrailingSlash = (options) => {
|
||||
return async function appendTrailingSlash2(c, next) {
|
||||
if (options?.alwaysRedirect) {
|
||||
if ((c.req.method === "GET" || c.req.method === "HEAD") && c.req.path.at(-1) !== "/") {
|
||||
if ((c.req.method === "GET" || c.req.method === "HEAD") && c.req.path.at(-1) !== "/" && !options.skip?.(c.req.path)) {
|
||||
const url = new URL(c.req.url);
|
||||
url.pathname += "/";
|
||||
return c.redirect(url.toString(), 301);
|
||||
}
|
||||
}
|
||||
await next();
|
||||
if (!options?.alwaysRedirect && c.res.status === 404 && (c.req.method === "GET" || c.req.method === "HEAD") && c.req.path.at(-1) !== "/") {
|
||||
if (!options?.alwaysRedirect && c.res.status === 404 && (c.req.method === "GET" || c.req.method === "HEAD") && c.req.path.at(-1) !== "/" && !options?.skip?.(c.req.path)) {
|
||||
const url = new URL(c.req.url);
|
||||
url.pathname += "/";
|
||||
c.res = c.redirect(url.toString(), 301);
|
||||
|
||||
Reference in New Issue
Block a user