tempest-express-sdk 0.2.0 → 0.3.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/dist/index.cjs CHANGED
@@ -5,6 +5,7 @@ var zodToOpenapi = require('@asteasolutions/zod-to-openapi');
5
5
  var zod = require('zod');
6
6
  var tempestDbJs = require('tempest-db-js');
7
7
  var crypto = require('crypto');
8
+ var os = require('os');
8
9
  var promises = require('fs/promises');
9
10
  var path = require('path');
10
11
  var express2 = require('express');
@@ -6755,6 +6756,361 @@ var AttemptThrottle = class {
6755
6756
  }
6756
6757
  };
6757
6758
 
6759
+ // src/utils/clientIp.ts
6760
+ var UNKNOWN = "unknown";
6761
+ function getClientIp(req, options = {}) {
6762
+ if (options.trustedHeader) {
6763
+ const value = req.header(options.trustedHeader);
6764
+ if (value) return value.trim();
6765
+ }
6766
+ return req.socket?.remoteAddress ?? req.ip ?? UNKNOWN;
6767
+ }
6768
+ var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
6769
+ function base32Encode(bytes) {
6770
+ let bits = 0;
6771
+ let value = 0;
6772
+ let out = "";
6773
+ for (const byte of bytes) {
6774
+ value = value << 8 | byte;
6775
+ bits += 8;
6776
+ while (bits >= 5) {
6777
+ out += BASE32_ALPHABET[value >>> bits - 5 & 31];
6778
+ bits -= 5;
6779
+ }
6780
+ }
6781
+ if (bits > 0) out += BASE32_ALPHABET[value << 5 - bits & 31];
6782
+ return out;
6783
+ }
6784
+ function base32Decode(secret) {
6785
+ const clean = secret.toUpperCase().replace(/=+$/, "").replace(/\s/g, "");
6786
+ let bits = 0;
6787
+ let value = 0;
6788
+ const out = [];
6789
+ for (const char of clean) {
6790
+ const index = BASE32_ALPHABET.indexOf(char);
6791
+ if (index === -1) continue;
6792
+ value = value << 5 | index;
6793
+ bits += 5;
6794
+ if (bits >= 8) {
6795
+ out.push(value >>> bits - 8 & 255);
6796
+ bits -= 8;
6797
+ }
6798
+ }
6799
+ return Buffer.from(out);
6800
+ }
6801
+ function hotp(secret, counter, digits) {
6802
+ const buffer = Buffer.alloc(8);
6803
+ buffer.writeUInt32BE(Math.floor(counter / 2 ** 32), 0);
6804
+ buffer.writeUInt32BE(counter >>> 0, 4);
6805
+ const digest = crypto.createHmac("sha1", secret).update(buffer).digest();
6806
+ const offset = digest[digest.length - 1] & 15;
6807
+ const binary = (digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255;
6808
+ return (binary % 10 ** digits).toString().padStart(digits, "0");
6809
+ }
6810
+ var TOTPHelper = class {
6811
+ issuer;
6812
+ step;
6813
+ digits;
6814
+ /**
6815
+ * @param options - Issuer label, time step and digit count.
6816
+ */
6817
+ constructor(options) {
6818
+ this.issuer = options.issuer;
6819
+ this.step = options.step ?? 30;
6820
+ this.digits = options.digits ?? 6;
6821
+ }
6822
+ /**
6823
+ * Generate a fresh base32 secret (80 bits).
6824
+ *
6825
+ * @returns A base32-encoded TOTP secret to persist on the user row.
6826
+ */
6827
+ generateSecret() {
6828
+ return base32Encode(crypto.randomBytes(10));
6829
+ }
6830
+ /**
6831
+ * Build the `otpauth://` provisioning URI (render as a QR code).
6832
+ *
6833
+ * @param secret - The base32 secret.
6834
+ * @param accountName - Identifier shown next to the issuer (e.g. the email).
6835
+ * @returns The `otpauth://totp/...` URI.
6836
+ */
6837
+ provisioningUri(secret, accountName) {
6838
+ const label = encodeURIComponent(`${this.issuer}:${accountName}`);
6839
+ const params = new URLSearchParams({
6840
+ secret,
6841
+ issuer: this.issuer,
6842
+ algorithm: "SHA1",
6843
+ digits: String(this.digits),
6844
+ period: String(this.step)
6845
+ });
6846
+ return `otpauth://totp/${label}?${params.toString()}`;
6847
+ }
6848
+ /**
6849
+ * Verify a code against the secret for the current time window.
6850
+ *
6851
+ * @param secret - The base32 secret.
6852
+ * @param code - The submitted code.
6853
+ * @param window - Tolerance in steps (±). Default 1 (previous/current/next).
6854
+ * @returns `true` when the code matches within the window.
6855
+ */
6856
+ verify(secret, code, window = 1) {
6857
+ const cleaned = code.trim().replace(/[\s-]/g, "");
6858
+ if (!/^\d+$/.test(cleaned) || cleaned.length !== this.digits) return false;
6859
+ const key = base32Decode(secret);
6860
+ const counter = Math.floor(Date.now() / 1e3 / this.step);
6861
+ for (let offset = -window; offset <= window; offset++) {
6862
+ if (hotp(key, counter + offset, this.digits) === cleaned) return true;
6863
+ }
6864
+ return false;
6865
+ }
6866
+ };
6867
+
6868
+ // src/utils/httpClient.ts
6869
+ var CircuitOpenError = class extends Error {
6870
+ constructor(host) {
6871
+ super(`Circuit breaker is open for host ${host}`);
6872
+ this.host = host;
6873
+ this.name = "CircuitOpenError";
6874
+ }
6875
+ host;
6876
+ };
6877
+ var RetryPolicy = class {
6878
+ /**
6879
+ * @param maxRetries - Additional attempts after the first. Default 2.
6880
+ * @param baseDelayMs - Base backoff in ms (doubles each attempt). Default 100.
6881
+ * @param retryOn - HTTP status codes that trigger a retry. Default 5xx + 429.
6882
+ */
6883
+ constructor(maxRetries = 2, baseDelayMs = 100, retryOn = [429, 500, 502, 503, 504]) {
6884
+ this.maxRetries = maxRetries;
6885
+ this.baseDelayMs = baseDelayMs;
6886
+ this.retryOn = retryOn;
6887
+ }
6888
+ maxRetries;
6889
+ baseDelayMs;
6890
+ retryOn;
6891
+ /** Backoff delay in ms before `attempt` (0-indexed). */
6892
+ sleepFor(attempt) {
6893
+ return this.baseDelayMs * 2 ** attempt;
6894
+ }
6895
+ };
6896
+ var HTTPClient = class {
6897
+ baseUrl;
6898
+ defaultHeaders;
6899
+ timeoutMs;
6900
+ retryPolicy;
6901
+ breakerThreshold;
6902
+ breakerCooldownMs;
6903
+ breakers = /* @__PURE__ */ new Map();
6904
+ /**
6905
+ * @param options - Base URL, headers, timeout, retry and breaker settings.
6906
+ */
6907
+ constructor(options = {}) {
6908
+ this.baseUrl = options.baseUrl ?? "";
6909
+ this.defaultHeaders = options.defaultHeaders ?? {};
6910
+ this.timeoutMs = options.timeoutMs ?? 3e4;
6911
+ this.retryPolicy = options.retryPolicy ?? new RetryPolicy();
6912
+ this.breakerThreshold = options.breakerThreshold ?? 5;
6913
+ this.breakerCooldownMs = options.breakerCooldownMs ?? 3e4;
6914
+ }
6915
+ resolve(url) {
6916
+ return this.baseUrl && !/^https?:\/\//.test(url) ? `${this.baseUrl}${url}` : url;
6917
+ }
6918
+ hostOf(url) {
6919
+ try {
6920
+ return new URL(url).host;
6921
+ } catch {
6922
+ return url;
6923
+ }
6924
+ }
6925
+ breakerCheck(host) {
6926
+ const state = this.breakers.get(host);
6927
+ if (state && state.openUntil > Date.now()) throw new CircuitOpenError(host);
6928
+ }
6929
+ breakerRecord(host, failed) {
6930
+ const state = this.breakers.get(host) ?? { failures: 0, openUntil: 0 };
6931
+ if (failed) {
6932
+ state.failures += 1;
6933
+ if (state.failures >= this.breakerThreshold) {
6934
+ state.openUntil = Date.now() + this.breakerCooldownMs;
6935
+ state.failures = 0;
6936
+ }
6937
+ } else {
6938
+ state.failures = 0;
6939
+ state.openUntil = 0;
6940
+ }
6941
+ this.breakers.set(host, state);
6942
+ }
6943
+ /**
6944
+ * Perform a request with retries and breaker protection.
6945
+ *
6946
+ * @param method - HTTP method.
6947
+ * @param url - Absolute URL or a path resolved against `baseUrl`.
6948
+ * @param init - Extra `fetch` init (headers, body, …).
6949
+ * @returns The `Response`.
6950
+ * @throws {CircuitOpenError} When the per-host breaker is open.
6951
+ */
6952
+ async request(method, url, init = {}) {
6953
+ const target = this.resolve(url);
6954
+ const host = this.hostOf(target);
6955
+ this.breakerCheck(host);
6956
+ let lastError;
6957
+ for (let attempt = 0; attempt <= this.retryPolicy.maxRetries; attempt++) {
6958
+ const controller = new AbortController();
6959
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
6960
+ try {
6961
+ const response = await fetch(target, {
6962
+ ...init,
6963
+ method,
6964
+ headers: { ...this.defaultHeaders, ...init.headers ?? {} },
6965
+ signal: controller.signal
6966
+ });
6967
+ clearTimeout(timer);
6968
+ if (this.retryPolicy.retryOn.includes(response.status)) {
6969
+ this.breakerRecord(host, true);
6970
+ if (attempt < this.retryPolicy.maxRetries) {
6971
+ await this.sleep(this.retryPolicy.sleepFor(attempt));
6972
+ continue;
6973
+ }
6974
+ return response;
6975
+ }
6976
+ this.breakerRecord(host, false);
6977
+ return response;
6978
+ } catch (error) {
6979
+ clearTimeout(timer);
6980
+ lastError = error;
6981
+ this.breakerRecord(host, true);
6982
+ if (attempt < this.retryPolicy.maxRetries) {
6983
+ await this.sleep(this.retryPolicy.sleepFor(attempt));
6984
+ continue;
6985
+ }
6986
+ }
6987
+ }
6988
+ throw lastError instanceof Error ? lastError : new Error("Request failed");
6989
+ }
6990
+ sleep(ms) {
6991
+ return new Promise((resolve) => setTimeout(resolve, ms));
6992
+ }
6993
+ /** GET request. */
6994
+ get(url, init) {
6995
+ return this.request("GET", url, init);
6996
+ }
6997
+ /** POST request. */
6998
+ post(url, init) {
6999
+ return this.request("POST", url, init);
7000
+ }
7001
+ /** PUT request. */
7002
+ put(url, init) {
7003
+ return this.request("PUT", url, init);
7004
+ }
7005
+ /** PATCH request. */
7006
+ patch(url, init) {
7007
+ return this.request("PATCH", url, init);
7008
+ }
7009
+ /** DELETE request. */
7010
+ delete(url, init) {
7011
+ return this.request("DELETE", url, init);
7012
+ }
7013
+ };
7014
+ function readCpu() {
7015
+ const cores = os.cpus().length;
7016
+ const load1 = os.loadavg()[0] ?? 0;
7017
+ return {
7018
+ cores,
7019
+ load1,
7020
+ loadPercent: cores > 0 ? load1 / cores * 100 : 0
7021
+ };
7022
+ }
7023
+ function readMemory() {
7024
+ const total = os.totalmem();
7025
+ const free = os.freemem();
7026
+ const used = total - free;
7027
+ return {
7028
+ total,
7029
+ free,
7030
+ used,
7031
+ usedPercent: total > 0 ? used / total * 100 : 0,
7032
+ processRss: process.memoryUsage().rss
7033
+ };
7034
+ }
7035
+ function readSystem() {
7036
+ return {
7037
+ cpu: readCpu(),
7038
+ memory: readMemory(),
7039
+ uptimeSeconds: process.uptime()
7040
+ };
7041
+ }
7042
+ function toPrometheus(snapshot = readSystem()) {
7043
+ const lines = [
7044
+ "# HELP process_cpu_load_percent 1-minute load average as percent of cores",
7045
+ "# TYPE process_cpu_load_percent gauge",
7046
+ `process_cpu_load_percent ${snapshot.cpu.loadPercent}`,
7047
+ "# HELP process_memory_used_percent System memory used percent",
7048
+ "# TYPE process_memory_used_percent gauge",
7049
+ `process_memory_used_percent ${snapshot.memory.usedPercent}`,
7050
+ "# HELP process_memory_rss_bytes Resident set size of the process",
7051
+ "# TYPE process_memory_rss_bytes gauge",
7052
+ `process_memory_rss_bytes ${snapshot.memory.processRss}`,
7053
+ "# HELP process_uptime_seconds Process uptime in seconds",
7054
+ "# TYPE process_uptime_seconds counter",
7055
+ `process_uptime_seconds ${snapshot.uptimeSeconds}`
7056
+ ];
7057
+ return `${lines.join("\n")}
7058
+ `;
7059
+ }
7060
+ var MetricsUtils = {
7061
+ cpu: readCpu,
7062
+ memory: readMemory,
7063
+ system: readSystem,
7064
+ toPrometheus
7065
+ };
7066
+
7067
+ // src/utils/email.ts
7068
+ var EmailUtils = class {
7069
+ /**
7070
+ * @param options - SMTP connection and default sender.
7071
+ */
7072
+ constructor(options) {
7073
+ this.options = options;
7074
+ }
7075
+ options;
7076
+ transport = null;
7077
+ async ready() {
7078
+ if (this.transport) return this.transport;
7079
+ let nodemailer;
7080
+ try {
7081
+ const mod = await import('nodemailer');
7082
+ nodemailer = mod.default ?? mod;
7083
+ } catch (cause) {
7084
+ throw new Error(
7085
+ "EmailUtils requires the 'nodemailer' peer dependency. Install with `npm i nodemailer`.",
7086
+ { cause }
7087
+ );
7088
+ }
7089
+ this.transport = nodemailer.createTransport({
7090
+ host: this.options.host,
7091
+ port: this.options.port ?? 587,
7092
+ secure: this.options.secure ?? false,
7093
+ ...this.options.user ? { auth: { user: this.options.user, pass: this.options.password ?? "" } } : {}
7094
+ });
7095
+ return this.transport;
7096
+ }
7097
+ /**
7098
+ * Send an email message.
7099
+ *
7100
+ * @param message - The message (recipients, subject, body).
7101
+ */
7102
+ async send(message) {
7103
+ const transport = await this.ready();
7104
+ await transport.sendMail({
7105
+ from: message.from ?? this.options.from,
7106
+ to: message.to,
7107
+ subject: message.subject,
7108
+ ...message.text !== void 0 ? { text: message.text } : {},
7109
+ ...message.html !== void 0 ? { html: message.html } : {}
7110
+ });
7111
+ }
7112
+ };
7113
+
6758
7114
  // src/cache/manager.ts
6759
7115
  var MemoryCacheManager = class {
6760
7116
  store = /* @__PURE__ */ new Map();
@@ -7595,6 +7951,84 @@ function buildContentDisposition(filename, inline = false) {
7595
7951
  return `${disposition}; filename*=UTF-8''${encoded}`;
7596
7952
  }
7597
7953
 
7954
+ // src/webpush/schemas.ts
7955
+ var webPushKeysSchema = zod.z.object({
7956
+ p256dh: zod.z.string().openapi({ description: "Client public key (base64url)." }),
7957
+ auth: zod.z.string().openapi({ description: "Client auth secret (base64url)." })
7958
+ }).openapi("WebPushKeys");
7959
+ var webPushSubscriptionSchema = zod.z.object({
7960
+ endpoint: zod.z.string().url().openapi({ description: "Push service endpoint URL." }),
7961
+ keys: webPushKeysSchema
7962
+ }).openapi("WebPushSubscription");
7963
+ var webPushPayloadSchema = zod.z.object({
7964
+ title: zod.z.string().openapi({ description: "Notification title." }),
7965
+ body: zod.z.string().optional().openapi({ description: "Notification body." }),
7966
+ url: zod.z.string().optional().openapi({ description: "URL opened on click." }),
7967
+ data: zod.z.record(zod.z.unknown()).optional().openapi({ description: "Extra data." })
7968
+ }).openapi("WebPushPayload");
7969
+
7970
+ // src/webpush/dispatcher.ts
7971
+ var WebPushError = class extends Error {
7972
+ constructor(message, statusCode) {
7973
+ super(message);
7974
+ this.statusCode = statusCode;
7975
+ this.name = "WebPushError";
7976
+ }
7977
+ statusCode;
7978
+ };
7979
+ var WebPushGoneError = class extends WebPushError {
7980
+ constructor(statusCode) {
7981
+ super("Push subscription is gone", statusCode);
7982
+ this.name = "WebPushGoneError";
7983
+ }
7984
+ };
7985
+ var cached4 = null;
7986
+ async function loadWebPush() {
7987
+ if (cached4) return cached4;
7988
+ try {
7989
+ const mod = await import('web-push');
7990
+ cached4 = mod.default ?? mod;
7991
+ } catch (cause) {
7992
+ throw new Error(
7993
+ "WebPushDispatcher requires the 'web-push' peer dependency. Install with `npm i web-push`.",
7994
+ { cause }
7995
+ );
7996
+ }
7997
+ return cached4;
7998
+ }
7999
+ var WebPushDispatcher = class {
8000
+ /**
8001
+ * @param options - VAPID keys and subject.
8002
+ */
8003
+ constructor(options) {
8004
+ this.options = options;
8005
+ }
8006
+ options;
8007
+ /**
8008
+ * Send a payload to a single subscription.
8009
+ *
8010
+ * @param subscription - The browser push subscription.
8011
+ * @param payload - The notification payload.
8012
+ * @throws {WebPushGoneError} When the subscription is expired (410/404).
8013
+ * @throws {WebPushError} On any other delivery failure.
8014
+ */
8015
+ async send(subscription, payload) {
8016
+ const webpush = await loadWebPush();
8017
+ webpush.setVapidDetails(
8018
+ this.options.subject,
8019
+ this.options.publicKey,
8020
+ this.options.privateKey
8021
+ );
8022
+ try {
8023
+ await webpush.sendNotification(subscription, JSON.stringify(payload));
8024
+ } catch (error) {
8025
+ const status = error.statusCode;
8026
+ if (status === 404 || status === 410) throw new WebPushGoneError(status);
8027
+ throw new WebPushError(error.message, status);
8028
+ }
8029
+ }
8030
+ };
8031
+
7598
8032
  // src/auth/schemas.ts
7599
8033
  var signupSchema = zod.z.object({
7600
8034
  email: zod.z.string().email().openapi({ description: "Login identifier (email)." }),
@@ -8107,7 +8541,7 @@ function runServer(app, options = {}) {
8107
8541
  }
8108
8542
 
8109
8543
  // src/version.ts
8110
- var VERSION = "0.2.0";
8544
+ var VERSION = "0.3.0";
8111
8545
 
8112
8546
  Object.defineProperty(exports, "OpenAPIRegistry", {
8113
8547
  enumerable: true,
@@ -8269,14 +8703,17 @@ exports.BaseService = BaseService;
8269
8703
  exports.CEP_PATTERN = CEP_PATTERN;
8270
8704
  exports.CNPJ_PATTERN = CNPJ_PATTERN;
8271
8705
  exports.CPF_PATTERN = CPF_PATTERN;
8706
+ exports.CircuitOpenError = CircuitOpenError;
8272
8707
  exports.CompositeFeatureFlagBackend = CompositeFeatureFlagBackend;
8273
8708
  exports.ConflictException = ConflictException;
8274
8709
  exports.DEFAULT_LOCALE = DEFAULT_LOCALE;
8710
+ exports.EmailUtils = EmailUtils;
8275
8711
  exports.EnvFeatureFlagBackend = EnvFeatureFlagBackend;
8276
8712
  exports.EventStream = EventStream;
8277
8713
  exports.ExpiredTokenException = ExpiredTokenException;
8278
8714
  exports.FeatureFlags = FeatureFlags;
8279
8715
  exports.ForbiddenException = ForbiddenException;
8716
+ exports.HTTPClient = HTTPClient;
8280
8717
  exports.HTTP_500_MARKER = HTTP_500_MARKER;
8281
8718
  exports.InvalidTokenException = InvalidTokenException;
8282
8719
  exports.JSONLogger = JSONLogger;
@@ -8288,6 +8725,7 @@ exports.MemoryFeatureFlagBackend = MemoryFeatureFlagBackend;
8288
8725
  exports.MemorySessionStore = MemorySessionStore;
8289
8726
  exports.MemoryThrottleBackend = MemoryThrottleBackend;
8290
8727
  exports.MessageCatalog = MessageCatalog;
8728
+ exports.MetricsUtils = MetricsUtils;
8291
8729
  exports.NotFoundException = NotFoundException;
8292
8730
  exports.PHONE_BR_PATTERN = PHONE_BR_PATTERN;
8293
8731
  exports.PasswordUtils = PasswordUtils;
@@ -8295,9 +8733,11 @@ exports.REQUEST_ID_HEADER = REQUEST_ID_HEADER;
8295
8733
  exports.RabbitBroker = RabbitBroker;
8296
8734
  exports.RedisCacheManager = RedisCacheManager;
8297
8735
  exports.Region = Region;
8736
+ exports.RetryPolicy = RetryPolicy;
8298
8737
  exports.SSEBroker = SSEBroker;
8299
8738
  exports.ServerSentEvent = ServerSentEvent;
8300
8739
  exports.SessionService = SessionService;
8740
+ exports.TOTPHelper = TOTPHelper;
8301
8741
  exports.TaskManager = TaskManager;
8302
8742
  exports.TooManyRequestsException = TooManyRequestsException;
8303
8743
  exports.UF = UF;
@@ -8305,6 +8745,9 @@ exports.UnauthorizedException = UnauthorizedException;
8305
8745
  exports.UserAuthService = UserAuthService;
8306
8746
  exports.VERSION = VERSION;
8307
8747
  exports.ValidationException = ValidationException;
8748
+ exports.WebPushDispatcher = WebPushDispatcher;
8749
+ exports.WebPushError = WebPushError;
8750
+ exports.WebPushGoneError = WebPushGoneError;
8308
8751
  exports.WebSocketHub = WebSocketHub;
8309
8752
  exports.attachWebSocketHub = attachWebSocketHub;
8310
8753
  exports.authResponseSchema = authResponseSchema;
@@ -8336,6 +8779,7 @@ exports.encodeCursor = encodeCursor;
8336
8779
  exports.generateOpaqueToken = generateOpaqueToken;
8337
8780
  exports.generateOpenApiDocument = generateOpenApiDocument;
8338
8781
  exports.getAuth = getAuth;
8782
+ exports.getClientIp = getClientIp;
8339
8783
  exports.getConditions = getConditions;
8340
8784
  exports.getPaginationConditions = getPaginationConditions;
8341
8785
  exports.getRequestId = getRequestId;
@@ -8397,6 +8841,9 @@ exports.updatedByColumn = updatedByColumn;
8397
8841
  exports.userPublicSchema = userPublicSchema;
8398
8842
  exports.utcnow = utcnow;
8399
8843
  exports.verifyOpaqueToken = verifyOpaqueToken;
8844
+ exports.webPushKeysSchema = webPushKeysSchema;
8845
+ exports.webPushPayloadSchema = webPushPayloadSchema;
8846
+ exports.webPushSubscriptionSchema = webPushSubscriptionSchema;
8400
8847
  exports.wsEnvelopeSchema = wsEnvelopeSchema;
8401
8848
  //# sourceMappingURL=index.cjs.map
8402
8849
  //# sourceMappingURL=index.cjs.map