@navservice/core 1.25.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.
@@ -0,0 +1,347 @@
1
+ import v4 from "zod/v4";
2
+ import { SignJWT, jwtVerify } from "jose";
3
+ import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
4
+ import { promisify } from "node:util";
5
+ const set_response = class {
6
+ static c = class {
7
+ static SUCCESS({ message, results, c }) {
8
+ const payload = {
9
+ status: 200,
10
+ code: "SUCCESS",
11
+ type: "success",
12
+ message: message || "Realizado com sucesso!",
13
+ results: results || []
14
+ };
15
+ if (c) return c.json(payload, {
16
+ status: 200
17
+ });
18
+ return payload;
19
+ }
20
+ static ACTION_REQUIRED({ message, results, c }) {
21
+ const payload = {
22
+ status: 428,
23
+ code: "ACTION_REQUIRED",
24
+ type: "warning",
25
+ message: message || "Ação adicional necessária!",
26
+ results: results || []
27
+ };
28
+ if (c) return c.json(payload, {
29
+ status: 428
30
+ });
31
+ return payload;
32
+ }
33
+ static CREATED({ message, results, c }) {
34
+ const payload = {
35
+ status: 201,
36
+ code: "CREATED",
37
+ type: "success",
38
+ message: message || "Criado com sucesso!",
39
+ results: results || []
40
+ };
41
+ return c ? c.json(payload, {
42
+ status: 201
43
+ }) : payload;
44
+ }
45
+ static WARNING({ message, results, c }) {
46
+ const payload = {
47
+ status: 400,
48
+ code: "WARNING",
49
+ type: "warning",
50
+ message: message || "Aviso!",
51
+ results: results || []
52
+ };
53
+ if (c) c.json(payload, {
54
+ status: 400
55
+ });
56
+ throw payload;
57
+ }
58
+ static AUTHORIZATION_ERROR({ message, results, c }) {
59
+ const payload = {
60
+ status: 405,
61
+ code: "WARNING",
62
+ type: "warning",
63
+ message: message || "Aviso!",
64
+ results: results || []
65
+ };
66
+ if (c) c.json(payload, {
67
+ status: 405
68
+ });
69
+ throw payload;
70
+ }
71
+ static DATABASE_ERROR({ message, results, c }) {
72
+ const payload = {
73
+ status: 500,
74
+ code: "DATABASE_ERROR",
75
+ type: "error",
76
+ message: message || "Erro no banco de dados!",
77
+ results: results || []
78
+ };
79
+ return c ? c.json(payload, {
80
+ status: 500
81
+ }) : payload;
82
+ }
83
+ static SERVER_ERROR({ error, c }) {
84
+ if (error instanceof v4.ZodError) {
85
+ const payload = {
86
+ status: 500,
87
+ code: "SCHEMA_VALIDATION",
88
+ type: "warning",
89
+ message: "Erro ao validar dados!",
90
+ results: v4.treeifyError(error)
91
+ };
92
+ return c.json(payload, {
93
+ status: 500
94
+ });
95
+ }
96
+ const payload = {
97
+ status: error?.status || 500,
98
+ code: error?.code || "SERVER_ERROR",
99
+ type: error?.type || "error",
100
+ message: error?.message || "Erro interno no servidor!",
101
+ results: error?.results || []
102
+ };
103
+ return c.json(payload, {
104
+ status: error?.status || error?.status || 500
105
+ });
106
+ }
107
+ static UNAUTHORIZED({ message, c }) {
108
+ const payload = {
109
+ status: 401,
110
+ code: "UNAUTHORIZED",
111
+ type: "error",
112
+ message: message || "Não autorizado!",
113
+ results: []
114
+ };
115
+ return c ? c.json(payload, {
116
+ status: 401
117
+ }) : payload;
118
+ }
119
+ static INVALID_TOKEN({ message, c }) {
120
+ const payload = {
121
+ status: 401,
122
+ code: "INVALID_TOKEN",
123
+ type: "warning",
124
+ message: message || "Token inválido!",
125
+ results: []
126
+ };
127
+ return c ? c.json(payload, {
128
+ status: 401
129
+ }) : payload;
130
+ }
131
+ static NOT_FOUND({ message, c }) {
132
+ const payload = {
133
+ status: 404,
134
+ code: "NOT_FOUND",
135
+ type: "error",
136
+ message: message || "Recurso não encontrado!",
137
+ results: []
138
+ };
139
+ return c ? c.json(payload, {
140
+ status: 404
141
+ }) : payload;
142
+ }
143
+ static async SUCCESS_FILE({ message, file_buffer, content_type, filename, c }) {
144
+ if (c && content_type) {
145
+ const headers = {
146
+ "Content-Type": content_type,
147
+ "Content-Disposition": filename ? `inline; filename="${filename}"` : "inline"
148
+ };
149
+ return new Response(file_buffer, {
150
+ status: 200,
151
+ headers
152
+ });
153
+ }
154
+ const payload = {
155
+ status: 200,
156
+ code: "SUCCESS_FILE",
157
+ type: "success",
158
+ message: message || "Erro ao retornar arquivo!",
159
+ results: []
160
+ };
161
+ return c ? c.json(payload, {
162
+ status: 200
163
+ }) : payload;
164
+ }
165
+ };
166
+ static error = class {
167
+ static ACTION_REQUIRED({ message, results }) {
168
+ const payload = {
169
+ status: 428,
170
+ code: "ACTION_REQUIRED",
171
+ type: "warning",
172
+ message: message || "Ação adicional necessária!",
173
+ results: results || []
174
+ };
175
+ throw payload;
176
+ }
177
+ static WARNING({ message, results }) {
178
+ const payload = {
179
+ status: 400,
180
+ code: "WARNING",
181
+ type: "warning",
182
+ message: message || "Aviso!",
183
+ results: results || []
184
+ };
185
+ throw payload;
186
+ }
187
+ static AUTHORIZATION_ERROR({ message, results }) {
188
+ const payload = {
189
+ status: 400,
190
+ code: "WARNING",
191
+ type: "warning",
192
+ message: message || "Aviso!",
193
+ results: results || []
194
+ };
195
+ throw payload;
196
+ }
197
+ static DATABASE_ERROR({ message, results }) {
198
+ const payload = {
199
+ status: 405,
200
+ code: "DATABASE_ERROR",
201
+ type: "error",
202
+ message: message || "Erro no banco de dados!",
203
+ results: results || []
204
+ };
205
+ throw payload;
206
+ }
207
+ static SCHEMA_VALIDATION({ results }) {
208
+ const payload = {
209
+ status: 500,
210
+ code: "SCHEMA_VALIDATION",
211
+ type: "error",
212
+ message: "Erro ao validar dados!",
213
+ results: results || []
214
+ };
215
+ throw payload;
216
+ }
217
+ static UNAUTHORIZED({ message }) {
218
+ const payload = {
219
+ status: 401,
220
+ code: "UNAUTHORIZED",
221
+ type: "error",
222
+ message: message || "Não autorizado!"
223
+ };
224
+ throw payload;
225
+ }
226
+ static INVALID_TOKEN({ message }) {
227
+ const payload = {
228
+ status: 401,
229
+ code: "INVALID_TOKEN",
230
+ type: "warning",
231
+ message: message || "Token inválido!",
232
+ results: []
233
+ };
234
+ throw payload;
235
+ }
236
+ static NOT_FOUND({ message }) {
237
+ const payload = {
238
+ status: 404,
239
+ code: "NOT_FOUND",
240
+ type: "error",
241
+ message: message || "Recurso não encontrado!"
242
+ };
243
+ throw payload;
244
+ }
245
+ };
246
+ };
247
+ const _set_response = set_response;
248
+ const scryptAsync = promisify(scrypt);
249
+ class _secret {
250
+ static SALT_LENGTH = 22;
251
+ static KEY_LENGTH = 35;
252
+ static async gerar_hash_senha(password) {
253
+ const salt = randomBytes(this.SALT_LENGTH);
254
+ const derivedKey = await scryptAsync(password, salt, this.KEY_LENGTH);
255
+ return salt.toString('base64') + '.' + derivedKey.toString('base64');
256
+ }
257
+ static async verify({ password, dashed_senha }) {
258
+ try {
259
+ const [saltBase64, hashBase64] = dashed_senha.split('.');
260
+ if (!saltBase64 || !hashBase64) return false;
261
+ const salt = Buffer.from(saltBase64, 'base64');
262
+ const storedHash = Buffer.from(hashBase64, 'base64');
263
+ const derivedKey = await scryptAsync(password, salt, this.KEY_LENGTH);
264
+ return timingSafeEqual(storedHash, derivedKey);
265
+ } catch {
266
+ return false;
267
+ }
268
+ }
269
+ }
270
+ const helpers_secret = _secret;
271
+ class helpers {
272
+ static set_response = _set_response;
273
+ static token = helpers_token;
274
+ static secret = helpers_secret;
275
+ }
276
+ const src_helpers = helpers;
277
+ const _token = class {
278
+ static async verificar_token(c, next) {
279
+ try {
280
+ const authHeader = c.req.header("Authorization");
281
+ if (!authHeader) return src_helpers.set_response.c.INVALID_TOKEN({
282
+ message: 'token não enviado!!!',
283
+ c: c,
284
+ results: []
285
+ });
286
+ const token = authHeader.split(" ")[1];
287
+ if (!token) return src_helpers.set_response.c.INVALID_TOKEN({
288
+ message: 'Acesso negado!!!',
289
+ c: c,
290
+ results: []
291
+ });
292
+ const secret = new TextEncoder().encode(c.env.JSON_WEB_TOKEN_AUTH_USER);
293
+ const { payload } = await jwtVerify(token, secret);
294
+ if (!payload._id || !payload.email) return src_helpers.set_response.c.INVALID_TOKEN({
295
+ message: 'Token inválido!!!!',
296
+ c: c,
297
+ results: []
298
+ });
299
+ const setar_token = {
300
+ _id: payload._id,
301
+ email: payload.email,
302
+ ativo: payload.ativo,
303
+ data_criacao: payload.data_criacao,
304
+ nome: payload.nome,
305
+ app: payload.app,
306
+ usuario_tipo: payload.usuario_tipo
307
+ };
308
+ c.set("usuario_auth", setar_token);
309
+ return await next();
310
+ } catch (error) {
311
+ return src_helpers.set_response.c.INVALID_TOKEN({
312
+ message: 'Token inválido!!!',
313
+ c: c,
314
+ results: []
315
+ });
316
+ }
317
+ }
318
+ static async criar_token_login_usuario({ _id, email, app, usuario_tipo, ativo, data_criacao, nome, c }) {
319
+ if (!c.env.JSON_WEB_TOKEN_AUTH_USER) return src_helpers.set_response.error.WARNING({
320
+ message: "Erro ao gerar token!!",
321
+ results: []
322
+ });
323
+ const token = await new SignJWT({
324
+ _id: _id,
325
+ email: email,
326
+ app: app,
327
+ usuario_tipo: usuario_tipo,
328
+ ativo: ativo,
329
+ data_criacao: data_criacao,
330
+ nome: nome
331
+ }).setProtectedHeader({
332
+ alg: "HS256"
333
+ }).setIssuedAt().sign(new TextEncoder().encode(c.env.JSON_WEB_TOKEN_AUTH_USER)).catch((error)=>src_helpers.set_response.error.WARNING({
334
+ message: "Erro ao gerar token!",
335
+ results: error?.message
336
+ }));
337
+ return token;
338
+ }
339
+ };
340
+ const helpers_token = _token;
341
+ class helpers_helpers {
342
+ static set_response = _set_response;
343
+ static token = helpers_token;
344
+ static secret = helpers_secret;
345
+ }
346
+ const src_helpers_0 = helpers_helpers;
347
+ export { src_helpers_0 as default };
@@ -0,0 +1,3 @@
1
+ export { default as config_env_core } from "./config_env";
2
+ export { default as TypesCore } from "./types";
3
+ export { default as utils } from "./utils";