@develit-io/backend-sdk 5.39.0 → 5.39.2

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.d.mts CHANGED
@@ -66,6 +66,8 @@ declare const idempotency: <T extends {
66
66
 
67
67
  declare const jwt: <TAuthService, TJwtPayload>() => MiddlewareHandler;
68
68
 
69
+ declare const ip: <TOrganizationService, TJwtPayload>() => MiddlewareHandler;
70
+
69
71
  declare const logger: () => MiddlewareHandler;
70
72
 
71
73
  declare const ENVIRONMENT: string[];
@@ -523,5 +525,5 @@ interface WithRetryCounterOptions {
523
525
  type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
524
526
  declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
525
527
 
526
- export { DatabaseTransaction, ENVIRONMENT, RPCResponse, USER_ROLES, action, bankAccount, bankAccountMetadataSchema, base, bicSchema, calculateExponentialBackoff, cloudflareQueue, composeWranglerBase, createAuditLogWriter, createInternalError, defineCommand, derivePortFromId, develitWorker, durableObjectNamespaceIdFromName, first, firstOrError, getD1Credentials, getD1DatabaseIdFromWrangler, getDrizzleD1Config, getSecret, handleAction, handleActionResponse, ibanSchema, idempotency, isInternalError, jwt, logger, paginationQuerySchema, paginationSchema, service, useFetch, useResult, useResultSync, uuidv4 };
528
+ export { DatabaseTransaction, ENVIRONMENT, RPCResponse, USER_ROLES, action, bankAccount, bankAccountMetadataSchema, base, bicSchema, calculateExponentialBackoff, cloudflareQueue, composeWranglerBase, createAuditLogWriter, createInternalError, defineCommand, derivePortFromId, develitWorker, durableObjectNamespaceIdFromName, first, firstOrError, getD1Credentials, getD1DatabaseIdFromWrangler, getDrizzleD1Config, getSecret, handleAction, handleActionResponse, ibanSchema, idempotency, ip, isInternalError, jwt, logger, paginationQuerySchema, paginationSchema, service, useFetch, useResult, useResultSync, uuidv4 };
527
529
  export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, AuthUser, BankAccountMetadata, BaseEvent, Command, CommandLogPayload, DevelitWorkerMethods, Environment, GatewayResponse, IRPCResponse, IdempotencyVariables, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, Project, UserRole, UserVariables, ValidatedInput };
package/dist/index.d.ts CHANGED
@@ -66,6 +66,8 @@ declare const idempotency: <T extends {
66
66
 
67
67
  declare const jwt: <TAuthService, TJwtPayload>() => MiddlewareHandler;
68
68
 
69
+ declare const ip: <TOrganizationService, TJwtPayload>() => MiddlewareHandler;
70
+
69
71
  declare const logger: () => MiddlewareHandler;
70
72
 
71
73
  declare const ENVIRONMENT: string[];
@@ -523,5 +525,5 @@ interface WithRetryCounterOptions {
523
525
  type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
524
526
  declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
525
527
 
526
- export { DatabaseTransaction, ENVIRONMENT, RPCResponse, USER_ROLES, action, bankAccount, bankAccountMetadataSchema, base, bicSchema, calculateExponentialBackoff, cloudflareQueue, composeWranglerBase, createAuditLogWriter, createInternalError, defineCommand, derivePortFromId, develitWorker, durableObjectNamespaceIdFromName, first, firstOrError, getD1Credentials, getD1DatabaseIdFromWrangler, getDrizzleD1Config, getSecret, handleAction, handleActionResponse, ibanSchema, idempotency, isInternalError, jwt, logger, paginationQuerySchema, paginationSchema, service, useFetch, useResult, useResultSync, uuidv4 };
528
+ export { DatabaseTransaction, ENVIRONMENT, RPCResponse, USER_ROLES, action, bankAccount, bankAccountMetadataSchema, base, bicSchema, calculateExponentialBackoff, cloudflareQueue, composeWranglerBase, createAuditLogWriter, createInternalError, defineCommand, derivePortFromId, develitWorker, durableObjectNamespaceIdFromName, first, firstOrError, getD1Credentials, getD1DatabaseIdFromWrangler, getDrizzleD1Config, getSecret, handleAction, handleActionResponse, ibanSchema, idempotency, ip, isInternalError, jwt, logger, paginationQuerySchema, paginationSchema, service, useFetch, useResult, useResultSync, uuidv4 };
527
529
  export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, AuthUser, BankAccountMetadata, BaseEvent, Command, CommandLogPayload, DevelitWorkerMethods, Environment, GatewayResponse, IRPCResponse, IdempotencyVariables, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, Project, UserRole, UserVariables, ValidatedInput };
package/dist/index.mjs CHANGED
@@ -2,6 +2,7 @@ import { sql } from 'drizzle-orm';
2
2
  import { integer, text } from 'drizzle-orm/sqlite-core';
3
3
  import { COUNTRY_CODES_2, CURRENCY_CODES, BANK_CODES } from '@develit-io/general-codes';
4
4
  import { createMiddleware } from 'hono/factory';
5
+ import { HTTPException } from 'hono/http-exception';
5
6
  import { createError } from 'h3';
6
7
  import { z as z$1 } from 'zod';
7
8
  import 'cloudflare';
@@ -70,21 +71,16 @@ const idempotency = () => {
70
71
  return createMiddleware(async (context, next) => {
71
72
  const idempotencyKeyHeader = context.req.header("X-Idempotency-Key");
72
73
  if (!idempotencyKeyHeader) {
73
- return context.json(
74
- {
75
- message: `The 'X-Idempotency-Key' header must exist and must have a value.`
76
- },
77
- 401
78
- );
74
+ throw new HTTPException(401, {
75
+ message: `The 'X-Idempotency-Key' header must exist and must have a value.`
76
+ });
79
77
  }
80
78
  const existingIdempotencyRecord = await context.env.IDEMPOTENCY_KV.get(idempotencyKeyHeader);
81
- if (existingIdempotencyRecord)
82
- return context.json(
83
- {
84
- message: "The identical request has already been processed. The idempotency key is not unique."
85
- },
86
- 409
87
- );
79
+ if (existingIdempotencyRecord) {
80
+ throw new HTTPException(409, {
81
+ message: "The identical request has already been processed. The idempotency key is not unique."
82
+ });
83
+ }
88
84
  await context.env.IDEMPOTENCY_KV.put(
89
85
  idempotencyKeyHeader,
90
86
  idempotencyKeyHeader,
@@ -497,52 +493,37 @@ const jwt = () => {
497
493
  return createMiddleware(async (context, next) => {
498
494
  const authorizationHeader = context.req.header("Authorization");
499
495
  if (!authorizationHeader) {
500
- return context.json(
501
- {
502
- message: `The 'Authorization' header must exist and must have a value.`
503
- },
504
- 401
505
- );
496
+ throw new HTTPException(401, {
497
+ message: `The 'Authorization' header must exist and must have a value.`
498
+ });
506
499
  }
507
500
  if (!validateBearerScheme(authorizationHeader)) {
508
- return context.json(
509
- {
510
- message: `The 'Authorization' header value must use the Bearer scheme.`
511
- },
512
- 401
513
- );
501
+ throw new HTTPException(401, {
502
+ message: `The 'Authorization' header value must use the Bearer scheme.`
503
+ });
514
504
  }
515
505
  const bearerToken = extractBearerToken(authorizationHeader);
516
506
  if (!validateBearerToken(bearerToken)) {
517
- return context.json(
518
- {
519
- message: `The Bearer token in the 'Authorization' header value must be a JWT.`
520
- },
521
- 401
522
- );
507
+ throw new HTTPException(401, {
508
+ message: `The Bearer token in the 'Authorization' header value must be a JWT.`
509
+ });
523
510
  }
524
511
  const authService = context.env.AUTH_SERVICE;
525
512
  const { data, error } = await authService.verifyAccessToken({
526
513
  accessToken: bearerToken
527
514
  });
528
515
  if (!data || error) {
529
- return context.json(
530
- {
531
- message: "The JWT must contain valid user information."
532
- },
533
- 401
534
- );
516
+ throw new HTTPException(401, {
517
+ message: "The JWT must contain valid user information."
518
+ });
535
519
  }
536
520
  const rawUserMetaDataString = data.payload.user.rawUserMetaData;
537
521
  const rawUserMetaData = rawUserMetaDataString ? JSON.parse(rawUserMetaDataString) : null;
538
522
  const organizationId = rawUserMetaData?.organizationId ?? null;
539
523
  if (!organizationId) {
540
- return context.json(
541
- {
542
- message: "User data integrity check failed."
543
- },
544
- 422
545
- );
524
+ throw new HTTPException(422, {
525
+ message: "User data integrity check failed."
526
+ });
546
527
  }
547
528
  context.set("user", {
548
529
  email: data.payload.user.email,
@@ -554,6 +535,41 @@ const jwt = () => {
554
535
  });
555
536
  };
556
537
 
538
+ const ip = () => {
539
+ return createMiddleware(async (context, next) => {
540
+ const requestIp = context.req.header("cf-connecting-ip") || context.req.header("x-forwarded-for");
541
+ if (!requestIp) {
542
+ throw new HTTPException(401, {
543
+ message: "Failed to retrieve request IP address."
544
+ });
545
+ }
546
+ const user = context.get("user");
547
+ if (!user.organizationId) {
548
+ throw new HTTPException(401, {
549
+ message: "Failed to retrieve request organization ID."
550
+ });
551
+ }
552
+ const organizationService = context.env.ORGANIZATION_SERVICE;
553
+ const { data: organization, error } = await organizationService.getOrganization({
554
+ organizationId: user.organizationId
555
+ });
556
+ if (!organization || error) {
557
+ throw new HTTPException(404, {
558
+ message: "Failed to retrieve organization."
559
+ });
560
+ }
561
+ console.log(context.env.ENVIRONMENT);
562
+ if (organization.payload.organization.ipAuthorization && context.env.ENVIRONMENT !== "localhost") {
563
+ if (!organization.payload.organization.authorizedIps.map((ip2) => ip2.ip).includes(requestIp)) {
564
+ throw new HTTPException(404, {
565
+ message: "Forbidden"
566
+ });
567
+ }
568
+ }
569
+ await next();
570
+ });
571
+ };
572
+
557
573
  const composeRequestLog = async (request) => {
558
574
  return {
559
575
  method: request.method,
@@ -831,4 +847,4 @@ function develitWorker(Worker) {
831
847
  return DevelitWorker;
832
848
  }
833
849
 
834
- export { DatabaseTransaction, ENVIRONMENT, RPCResponse, USER_ROLES, action, bankAccount, bankAccountMetadataSchema, base, bicSchema, calculateExponentialBackoff, cloudflareQueue, composeWranglerBase, createAuditLogWriter, createInternalError, defineCommand, derivePortFromId, develitWorker, durableObjectNamespaceIdFromName, first, firstOrError, getD1Credentials, getD1DatabaseIdFromWrangler, getDrizzleD1Config, getSecret, handleAction, handleActionResponse, ibanSchema, idempotency, isInternalError, jwt, logger, paginationQuerySchema, paginationSchema, service, useFetch, useResult, useResultSync, uuidv4 };
850
+ export { DatabaseTransaction, ENVIRONMENT, RPCResponse, USER_ROLES, action, bankAccount, bankAccountMetadataSchema, base, bicSchema, calculateExponentialBackoff, cloudflareQueue, composeWranglerBase, createAuditLogWriter, createInternalError, defineCommand, derivePortFromId, develitWorker, durableObjectNamespaceIdFromName, first, firstOrError, getD1Credentials, getD1DatabaseIdFromWrangler, getDrizzleD1Config, getSecret, handleAction, handleActionResponse, ibanSchema, idempotency, ip, isInternalError, jwt, logger, paginationQuerySchema, paginationSchema, service, useFetch, useResult, useResultSync, uuidv4 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@develit-io/backend-sdk",
3
- "version": "5.39.0",
3
+ "version": "5.39.2",
4
4
  "description": "Develit Backend SDK",
5
5
  "author": "Develit.io",
6
6
  "license": "ISC",