@digilogiclabs/platform-core 1.20.3 → 1.23.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.
Files changed (38) hide show
  1. package/dist/{ConsoleEmail-CO0OM4UT.d.ts → ConsoleEmail-CgSIvRdj.d.mts} +5 -46
  2. package/dist/{ConsoleEmail-DDB28vyS.d.mts → ConsoleEmail-iJO7Cb_v.d.ts} +5 -46
  3. package/dist/{IAI-D8wA_i8N.d.mts → IAI-B7pp322X.d.mts} +1 -170
  4. package/dist/{IAI-D8wA_i8N.d.ts → IAI-B7pp322X.d.ts} +1 -170
  5. package/dist/ICache-BWSuTuhz.d.mts +66 -0
  6. package/dist/ICache-BWSuTuhz.d.ts +66 -0
  7. package/dist/IEmail-CsOcaQcb.d.mts +45 -0
  8. package/dist/IEmail-CsOcaQcb.d.ts +45 -0
  9. package/dist/ILogger-DLDBZaH4.d.mts +105 -0
  10. package/dist/ILogger-DLDBZaH4.d.ts +105 -0
  11. package/dist/{agents-DGciJI27.d.mts → agents-C7FPA8y9.d.mts} +3 -1
  12. package/dist/{agents-Cc65YUoW.d.ts → agents-qyQ3BtXy.d.ts} +3 -1
  13. package/dist/agents.d.mts +4 -2
  14. package/dist/agents.d.ts +4 -2
  15. package/dist/auth.d.mts +386 -1
  16. package/dist/auth.d.ts +386 -1
  17. package/dist/auth.js +451 -0
  18. package/dist/auth.js.map +1 -1
  19. package/dist/auth.mjs +434 -0
  20. package/dist/auth.mjs.map +1 -1
  21. package/dist/circuit-breaker-CP6kw0P5.d.ts +351 -0
  22. package/dist/circuit-breaker-CsQivd57.d.mts +351 -0
  23. package/dist/email-templates.d.mts +106 -1
  24. package/dist/email-templates.d.ts +106 -1
  25. package/dist/email-templates.js +608 -0
  26. package/dist/email-templates.js.map +1 -1
  27. package/dist/email-templates.mjs +596 -0
  28. package/dist/email-templates.mjs.map +1 -1
  29. package/dist/index.d.mts +14 -355
  30. package/dist/index.d.ts +14 -355
  31. package/dist/index.js +10 -7
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +10 -7
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/migrate.js +0 -0
  36. package/dist/testing.d.mts +6 -3
  37. package/dist/testing.d.ts +6 -3
  38. package/package.json +11 -11
package/dist/auth.mjs CHANGED
@@ -1541,6 +1541,24 @@ function createSecureHandlerFactory(factoryConfig) {
1541
1541
  const resolvedAuditAction = typeof auditCfg === "object" && auditCfg !== null ? auditCfg.action : auditCfg;
1542
1542
  const resolvedAuditResource = typeof auditCfg === "object" && auditCfg !== null ? auditCfg.resource : routeConfig.auditResource;
1543
1543
  const resolvedGetResourceId = typeof auditCfg === "object" && auditCfg !== null ? auditCfg.getResourceId : routeConfig.getResourceId;
1544
+ const emitBlockedAudit = async (reason) => {
1545
+ if (!factoryConfig.auditOnBlocked || !factoryConfig.auditLog) return;
1546
+ const action = factoryConfig.blockedAuditAction ?? "unauthorized_access";
1547
+ try {
1548
+ await factoryConfig.auditLog({
1549
+ actor: session?.user ? {
1550
+ id: session.user.id ?? "unknown",
1551
+ type: isLegacyToken ? "admin" : "user",
1552
+ email: session.user.email ?? void 0
1553
+ } : { id: "anonymous", type: "anonymous" },
1554
+ action,
1555
+ resource: resolvedAuditResource ? { type: resolvedAuditResource, id: "unknown" } : void 0,
1556
+ outcome: "blocked",
1557
+ reason
1558
+ });
1559
+ } catch {
1560
+ }
1561
+ };
1544
1562
  try {
1545
1563
  if (routeConfig.requireAuth || routeConfig.requireAdmin || routeConfig.requireRoles?.length) {
1546
1564
  session = await factoryConfig.getSession();
@@ -1551,6 +1569,7 @@ function createSecureHandlerFactory(factoryConfig) {
1551
1569
  isAdmin = true;
1552
1570
  } else {
1553
1571
  log.warn("Unauthorized access attempt");
1572
+ await emitBlockedAudit("No authenticated session or valid token");
1554
1573
  return Response.json(
1555
1574
  { error: "Unauthorized" },
1556
1575
  { status: 401, headers: { "X-Request-ID": requestId } }
@@ -1559,6 +1578,7 @@ function createSecureHandlerFactory(factoryConfig) {
1559
1578
  }
1560
1579
  if (routeConfig.requireAdmin && !isLegacyToken && !isAdmin) {
1561
1580
  log.warn("Admin access denied");
1581
+ await emitBlockedAudit("Missing admin role");
1562
1582
  return Response.json(
1563
1583
  { error: "Forbidden: Admin access required" },
1564
1584
  { status: 403, headers: { "X-Request-ID": requestId } }
@@ -1570,6 +1590,9 @@ function createSecureHandlerFactory(factoryConfig) {
1570
1590
  );
1571
1591
  if (!hasRole2) {
1572
1592
  log.warn("Role-based access denied");
1593
+ await emitBlockedAudit(
1594
+ `Missing required roles: ${routeConfig.requireRoles.join(", ")}`
1595
+ );
1573
1596
  return Response.json(
1574
1597
  { error: "Forbidden: Insufficient permissions" },
1575
1598
  { status: 403, headers: { "X-Request-ID": requestId } }
@@ -1728,6 +1751,43 @@ function createSecureHandlerFactory(factoryConfig) {
1728
1751
  handler
1729
1752
  );
1730
1753
  }
1754
+ function withRoleBasedApi(roles, config, handler) {
1755
+ return createSecureHandler(
1756
+ {
1757
+ rateLimit: factoryConfig.rateLimiter?.authDefault,
1758
+ ...config,
1759
+ requireAuth: true,
1760
+ requireRoles: roles
1761
+ },
1762
+ handler
1763
+ );
1764
+ }
1765
+ function withDebugApi(config, handler) {
1766
+ const { allowInProduction = false, ...routeConfig } = config;
1767
+ const inner = createSecureHandler(
1768
+ {
1769
+ rateLimit: factoryConfig.rateLimiter?.adminDefault,
1770
+ ...routeConfig,
1771
+ requireAuth: true,
1772
+ requireAdmin: true
1773
+ },
1774
+ handler
1775
+ );
1776
+ return async (request, routeContext) => {
1777
+ const isProduction = isDev === false;
1778
+ if (isProduction && !allowInProduction) {
1779
+ const requestId = getRequestId(request);
1780
+ return Response.json(
1781
+ {
1782
+ error: "Debug endpoints are disabled in production",
1783
+ code: "DEBUG_DISABLED"
1784
+ },
1785
+ { status: 403, headers: { "X-Request-ID": requestId } }
1786
+ );
1787
+ }
1788
+ return inner(request, routeContext);
1789
+ };
1790
+ }
1731
1791
  function withLegacyAdminApi(config, handler) {
1732
1792
  return createSecureHandler(
1733
1793
  {
@@ -1740,11 +1800,91 @@ function createSecureHandlerFactory(factoryConfig) {
1740
1800
  handler
1741
1801
  );
1742
1802
  }
1803
+ function withAiApi(config, handler) {
1804
+ return createSecureHandler(
1805
+ {
1806
+ rateLimit: factoryConfig.rateLimiter?.aiDefault,
1807
+ ...config,
1808
+ requireAuth: true
1809
+ },
1810
+ handler
1811
+ );
1812
+ }
1813
+ function withCronApi(config, handler) {
1814
+ const { allowVercelCron = true, ...routeConfig } = config;
1815
+ return async (request, routeContext) => {
1816
+ const requestId = getRequestId(request);
1817
+ const operation = routeConfig.operation || `CRON ${new URL(request.url).pathname}`;
1818
+ const log = makeLogger(request, operation);
1819
+ const userAgent = request.headers.get("user-agent") || "";
1820
+ const isVercelCron = allowVercelCron && userAgent.toLowerCase().includes("vercel");
1821
+ const isAdminToken = checkLegacyToken(request);
1822
+ let isCronSecret = false;
1823
+ if (factoryConfig.cronSecret) {
1824
+ try {
1825
+ const contentType = request.headers.get("content-type");
1826
+ if (contentType?.includes("application/json")) {
1827
+ const body = await request.clone().json();
1828
+ if (typeof body.cronSecret === "string" && constantTimeEqual(body.cronSecret, factoryConfig.cronSecret)) {
1829
+ isCronSecret = true;
1830
+ }
1831
+ }
1832
+ } catch {
1833
+ }
1834
+ if (!isCronSecret) {
1835
+ const qs = new URL(request.url).searchParams.get("cronSecret") || "";
1836
+ if (qs && constantTimeEqual(qs, factoryConfig.cronSecret)) {
1837
+ isCronSecret = true;
1838
+ }
1839
+ }
1840
+ }
1841
+ if (!isVercelCron && !isAdminToken && !isCronSecret) {
1842
+ log.warn("Unauthorized cron access attempt");
1843
+ return Response.json(
1844
+ { error: "Unauthorized" },
1845
+ { status: 401, headers: { "X-Request-ID": requestId } }
1846
+ );
1847
+ }
1848
+ log.info("Cron job authorized", {
1849
+ method: isVercelCron ? "vercel_cron" : isAdminToken ? "admin_token" : "cron_secret"
1850
+ });
1851
+ const params = await routeContext.params;
1852
+ const ctx = {
1853
+ session: null,
1854
+ isLegacyToken: isAdminToken,
1855
+ authMethod: isAdminToken ? "legacy_token" : "none",
1856
+ isAdmin: true,
1857
+ // cron implicitly trusted
1858
+ validated: {},
1859
+ logger: log,
1860
+ requestId,
1861
+ params
1862
+ };
1863
+ try {
1864
+ const response = await handler(request, ctx);
1865
+ response.headers.set("X-Request-ID", requestId);
1866
+ return response;
1867
+ } catch (error) {
1868
+ log.error("Cron handler error", {
1869
+ error: error instanceof Error ? error.message : String(error)
1870
+ });
1871
+ const { status, body } = classify(error, isDev);
1872
+ return Response.json(
1873
+ { error: body.error, code: body.code },
1874
+ { status, headers: { "X-Request-ID": requestId } }
1875
+ );
1876
+ }
1877
+ };
1878
+ }
1743
1879
  return {
1744
1880
  createSecureHandler,
1745
1881
  withPublicApi,
1746
1882
  withAuthenticatedApi,
1747
1883
  withAdminApi,
1884
+ withRoleBasedApi,
1885
+ withDebugApi,
1886
+ withAiApi,
1887
+ withCronApi,
1748
1888
  withLegacyAdminApi
1749
1889
  };
1750
1890
  }
@@ -1826,6 +1966,293 @@ function computeClaimDelta(current, newEmail, newName) {
1826
1966
  return changed ? delta : null;
1827
1967
  }
1828
1968
 
1969
+ // src/auth/tokens.ts
1970
+ import crypto2 from "crypto";
1971
+ var HMAC_HEX_CHARS = 16;
1972
+ function validateSecret(secret) {
1973
+ if (typeof secret !== "string" || secret.length < 16) {
1974
+ throw new Error(
1975
+ "signToken/verifyToken require a secret of at least 16 characters"
1976
+ );
1977
+ }
1978
+ }
1979
+ function computeHmac(secret, signedPart) {
1980
+ return crypto2.createHmac("sha256", secret).update(signedPart).digest("hex").slice(0, HMAC_HEX_CHARS);
1981
+ }
1982
+ function signToken(opts) {
1983
+ validateSecret(opts.secret);
1984
+ if (typeof opts.payload !== "string" || opts.payload.length === 0) {
1985
+ throw new Error("signToken requires a non-empty payload string");
1986
+ }
1987
+ const signedPart = opts.ttlSeconds !== void 0 ? `${opts.payload}.${Math.floor(Date.now() / 1e3)}` : opts.payload;
1988
+ const encoded = Buffer.from(signedPart, "utf-8").toString("base64url");
1989
+ const hmac = computeHmac(opts.secret, signedPart);
1990
+ return `${encoded}.${hmac}`;
1991
+ }
1992
+ function verifyToken(token, opts) {
1993
+ validateSecret(opts.secret);
1994
+ if (typeof token !== "string" || token.length === 0) {
1995
+ return { valid: false, reason: "malformed" };
1996
+ }
1997
+ const lastDot = token.lastIndexOf(".");
1998
+ if (lastDot <= 0 || lastDot === token.length - 1) {
1999
+ return { valid: false, reason: "malformed" };
2000
+ }
2001
+ const encoded = token.slice(0, lastDot);
2002
+ const providedHmac = token.slice(lastDot + 1);
2003
+ let signedPart;
2004
+ try {
2005
+ signedPart = Buffer.from(encoded, "base64url").toString("utf-8");
2006
+ } catch {
2007
+ return { valid: false, reason: "malformed" };
2008
+ }
2009
+ if (signedPart.length === 0) {
2010
+ return { valid: false, reason: "malformed" };
2011
+ }
2012
+ const expectedHmac = computeHmac(opts.secret, signedPart);
2013
+ if (providedHmac.length !== expectedHmac.length || !crypto2.timingSafeEqual(
2014
+ Buffer.from(providedHmac, "utf-8"),
2015
+ Buffer.from(expectedHmac, "utf-8")
2016
+ )) {
2017
+ return { valid: false, reason: "bad_signature" };
2018
+ }
2019
+ const tsDot = signedPart.lastIndexOf(".");
2020
+ let payload = signedPart;
2021
+ let issuedAt;
2022
+ if (tsDot > 0) {
2023
+ const tsCandidate = signedPart.slice(tsDot + 1);
2024
+ const tsNum = Number(tsCandidate);
2025
+ if (Number.isFinite(tsNum) && /^\d+$/.test(tsCandidate)) {
2026
+ payload = signedPart.slice(0, tsDot);
2027
+ issuedAt = tsNum;
2028
+ }
2029
+ }
2030
+ if (opts.maxAgeSeconds !== void 0 && issuedAt !== void 0) {
2031
+ const ageSeconds = Math.floor(Date.now() / 1e3) - issuedAt;
2032
+ if (ageSeconds > opts.maxAgeSeconds) {
2033
+ return { valid: false, reason: "expired" };
2034
+ }
2035
+ }
2036
+ return issuedAt !== void 0 ? { valid: true, payload, issuedAt } : { valid: true, payload };
2037
+ }
2038
+
2039
+ // src/auth/redirect.ts
2040
+ var DANGEROUS_PROTOCOLS = /* @__PURE__ */ new Set([
2041
+ "javascript:",
2042
+ "data:",
2043
+ "vbscript:",
2044
+ "file:"
2045
+ ]);
2046
+ function safeRedirect(candidate, opts) {
2047
+ if (typeof candidate !== "string" || candidate.length === 0) {
2048
+ return opts.fallback;
2049
+ }
2050
+ const trimmed = candidate.trim();
2051
+ if (trimmed.length === 0) {
2052
+ return opts.fallback;
2053
+ }
2054
+ if (trimmed.startsWith("//")) {
2055
+ return opts.fallback;
2056
+ }
2057
+ if (trimmed.startsWith("/")) {
2058
+ return trimmed;
2059
+ }
2060
+ let url;
2061
+ try {
2062
+ url = new URL(trimmed);
2063
+ } catch {
2064
+ return opts.fallback;
2065
+ }
2066
+ if (DANGEROUS_PROTOCOLS.has(url.protocol.toLowerCase())) {
2067
+ return opts.fallback;
2068
+ }
2069
+ const candidateOrigin = url.origin.toLowerCase();
2070
+ const allowed = opts.allowedOrigins.some(
2071
+ (o) => o.toLowerCase() === candidateOrigin
2072
+ );
2073
+ if (!allowed) {
2074
+ return opts.fallback;
2075
+ }
2076
+ return url.toString();
2077
+ }
2078
+
2079
+ // src/auth/honeypot.ts
2080
+ var DEFAULT_FIELD_NAME = "_hp";
2081
+ function isHoneypotFilled(body, fieldName = DEFAULT_FIELD_NAME) {
2082
+ if (body == null) return false;
2083
+ if (typeof FormData !== "undefined" && body instanceof FormData) {
2084
+ const value2 = body.get(fieldName);
2085
+ return typeof value2 === "string" && value2.trim().length > 0;
2086
+ }
2087
+ if (typeof body !== "object") return false;
2088
+ const value = body[fieldName];
2089
+ return typeof value === "string" && value.trim().length > 0;
2090
+ }
2091
+
2092
+ // src/auth/health-route.ts
2093
+ var DEFAULT_TIMEOUT_MS = 2e3;
2094
+ async function withTimeoutOrError(probe, timeoutMs) {
2095
+ try {
2096
+ const result = await Promise.race([
2097
+ probe(),
2098
+ new Promise(
2099
+ (_, reject) => setTimeout(() => reject(new Error("probe timed out")), timeoutMs)
2100
+ )
2101
+ ]);
2102
+ return result;
2103
+ } catch {
2104
+ return { status: "error" };
2105
+ }
2106
+ }
2107
+ function createHealthRoute(opts) {
2108
+ const names = Object.keys(opts.checks);
2109
+ return async function GET() {
2110
+ const probeResults = await Promise.all(
2111
+ names.map(async (name) => {
2112
+ const check = opts.checks[name];
2113
+ const result = await withTimeoutOrError(
2114
+ check.probe,
2115
+ check.timeoutMs ?? DEFAULT_TIMEOUT_MS
2116
+ );
2117
+ return [name, result];
2118
+ })
2119
+ );
2120
+ const services = {};
2121
+ let degraded = false;
2122
+ for (const [name, result] of probeResults) {
2123
+ services[name] = result;
2124
+ const check = opts.checks[name];
2125
+ if (check.gating && result.status === "error") {
2126
+ degraded = true;
2127
+ }
2128
+ }
2129
+ const body = {
2130
+ status: degraded ? "degraded" : "healthy",
2131
+ services
2132
+ };
2133
+ if (opts.extraBody) {
2134
+ try {
2135
+ const extra = await opts.extraBody();
2136
+ Object.assign(body, extra);
2137
+ } catch {
2138
+ }
2139
+ }
2140
+ return new Response(JSON.stringify(body), {
2141
+ status: degraded ? 503 : 200,
2142
+ headers: { "content-type": "application/json" }
2143
+ });
2144
+ };
2145
+ }
2146
+
2147
+ // src/interfaces/ILogger.ts
2148
+ var NoopLogger = class {
2149
+ debug() {
2150
+ }
2151
+ info() {
2152
+ }
2153
+ warn() {
2154
+ }
2155
+ error() {
2156
+ }
2157
+ child() {
2158
+ return this;
2159
+ }
2160
+ };
2161
+
2162
+ // src/auth/cache-helpers.ts
2163
+ var CacheTTL = {
2164
+ /** 5 minutes — query results, dropdown options. */
2165
+ SHORT: 300,
2166
+ /** 1 hour — semi-static reference data, per-user state. */
2167
+ MEDIUM: 3600,
2168
+ /** 6 hours — heavy aggregates, derived state. */
2169
+ LONG: 21600,
2170
+ /** 24 hours — positive AI cache, immutable enrichments. */
2171
+ DAY: 86400,
2172
+ /** 7 days — long-term derived data, hashed content. */
2173
+ WEEK: 604800
2174
+ };
2175
+ function createAppCache(cache, options = {}) {
2176
+ const logger = options.logger ?? new NoopLogger();
2177
+ return {
2178
+ async get(key) {
2179
+ try {
2180
+ return await cache.get(key);
2181
+ } catch (err) {
2182
+ logger.debug("cache.get failed", { key, err: String(err) });
2183
+ return null;
2184
+ }
2185
+ },
2186
+ async set(key, value, ttlSeconds) {
2187
+ try {
2188
+ await cache.set(key, value, ttlSeconds);
2189
+ } catch (err) {
2190
+ logger.debug("cache.set failed", { key, err: String(err) });
2191
+ }
2192
+ },
2193
+ async delete(key) {
2194
+ try {
2195
+ await cache.delete(key);
2196
+ } catch (err) {
2197
+ logger.debug("cache.delete failed", { key, err: String(err) });
2198
+ }
2199
+ },
2200
+ async exists(key) {
2201
+ try {
2202
+ return await cache.exists(key);
2203
+ } catch {
2204
+ return false;
2205
+ }
2206
+ },
2207
+ async getCachedOrFetch(key, fetchFn, ttlSeconds) {
2208
+ try {
2209
+ const cached = await cache.get(key);
2210
+ if (cached !== null) return cached;
2211
+ } catch (err) {
2212
+ logger.debug("getCachedOrFetch read failed; falling through", {
2213
+ key,
2214
+ err: String(err)
2215
+ });
2216
+ }
2217
+ const fresh = await fetchFn();
2218
+ try {
2219
+ await cache.set(key, fresh, ttlSeconds);
2220
+ } catch (err) {
2221
+ logger.debug("getCachedOrFetch write-back failed", {
2222
+ key,
2223
+ err: String(err)
2224
+ });
2225
+ }
2226
+ return fresh;
2227
+ },
2228
+ async invalidate(keys) {
2229
+ const list = Array.isArray(keys) ? keys : [keys];
2230
+ let total = 0;
2231
+ for (const key of list) {
2232
+ try {
2233
+ if (key.includes("*")) {
2234
+ total += await cache.deletePattern(key);
2235
+ } else {
2236
+ await cache.delete(key);
2237
+ total += 1;
2238
+ }
2239
+ } catch (err) {
2240
+ logger.debug("invalidate failed for key", { key, err: String(err) });
2241
+ }
2242
+ }
2243
+ return total;
2244
+ },
2245
+ async warm(key, fetchFn, ttlSeconds) {
2246
+ try {
2247
+ const value = await fetchFn();
2248
+ await cache.set(key, value, ttlSeconds);
2249
+ } catch (err) {
2250
+ logger.debug("warm failed", { key, err: String(err) });
2251
+ }
2252
+ }
2253
+ };
2254
+ }
2255
+
1829
2256
  // src/env.ts
1830
2257
  function getRequiredEnv(key) {
1831
2258
  const value = process.env[key];
@@ -1919,6 +2346,7 @@ function getEnvSummary(keys) {
1919
2346
  export {
1920
2347
  ApiError,
1921
2348
  ApiErrorCode,
2349
+ CacheTTL,
1922
2350
  CommonApiErrors,
1923
2351
  CommonRateLimits,
1924
2352
  DateRangeSchema,
@@ -1953,11 +2381,13 @@ export {
1953
2381
  constantTimeEqual,
1954
2382
  containsHtml,
1955
2383
  containsUrls,
2384
+ createAppCache,
1956
2385
  createAuditActor,
1957
2386
  createAuditLogger,
1958
2387
  createBetaClient,
1959
2388
  createEnsureUser,
1960
2389
  createFeatureFlags,
2390
+ createHealthRoute,
1961
2391
  createLazyRateLimitStore,
1962
2392
  createMemoryRateLimitStore,
1963
2393
  createRedisRateLimitStore,
@@ -1989,6 +2419,7 @@ export {
1989
2419
  hasRole,
1990
2420
  isAllowlisted,
1991
2421
  isApiError,
2422
+ isHoneypotFilled,
1992
2423
  isTokenExpired,
1993
2424
  isValidBearerToken,
1994
2425
  parseKeycloakRoles,
@@ -1997,8 +2428,10 @@ export {
1997
2428
  resetRateLimitForKey,
1998
2429
  resolveIdentifier,
1999
2430
  resolveRateLimitIdentifier,
2431
+ safeRedirect,
2000
2432
  safeValidate,
2001
2433
  sanitizeApiError,
2434
+ signToken,
2002
2435
  storeBetaCode,
2003
2436
  stripHtml,
2004
2437
  stripNullBytes,
@@ -2006,6 +2439,7 @@ export {
2006
2439
  validateBetaCode,
2007
2440
  validateEnvVars,
2008
2441
  verifyCronAuth,
2442
+ verifyToken,
2009
2443
  zodErrorResponse
2010
2444
  };
2011
2445
  //# sourceMappingURL=auth.mjs.map