@opengis/fcore 0.0.1-beta.25 → 0.0.1-beta.26

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 (104) hide show
  1. package/LICENSE +3 -3
  2. package/README.md +71 -71
  3. package/dist/config.js +1 -1
  4. package/dist/context.js +1 -1
  5. package/dist/errors.js +1 -1
  6. package/dist/fastify.js +1 -1
  7. package/dist/fcore.js +1 -1
  8. package/dist/migrations/cli.js +1 -1
  9. package/dist/migrations/runner.js +1 -1
  10. package/dist/modules/auth/adduser-cli.js +1 -1
  11. package/dist/modules/auth/passwd-cli.js +1 -1
  12. package/dist/modules/auth/permission-cli.js +1 -1
  13. package/dist/modules/auth/route.d.ts.map +1 -1
  14. package/dist/modules/auth/route.js +1 -1
  15. package/dist/modules/auth/schema.js +1 -1
  16. package/dist/modules/auth/services/change-password.js +1 -1
  17. package/dist/modules/auth/services/get-current-user.d.ts +2 -0
  18. package/dist/modules/auth/services/get-current-user.d.ts.map +1 -1
  19. package/dist/modules/auth/services/get-current-user.js +1 -1
  20. package/dist/modules/auth/services/registration.js +1 -1
  21. package/dist/modules/auth/services/verify-two-factor.js +1 -1
  22. package/dist/modules/file/mime.js +1 -1
  23. package/dist/modules/file/route.js +1 -1
  24. package/dist/modules/file/schema.js +1 -1
  25. package/dist/modules/file/services/get-file.js +1 -1
  26. package/dist/modules/file/services/resize-file.js +1 -1
  27. package/dist/modules/file/services/upload-file.js +1 -1
  28. package/dist/modules/resource/route.js +1 -1
  29. package/dist/modules/resource/schema.js +1 -1
  30. package/dist/modules/resource/services/add-note.js +1 -1
  31. package/dist/modules/resource/services/add-resource-file.js +1 -1
  32. package/dist/modules/resource/services/create-resource-relation.js +1 -1
  33. package/dist/modules/resource/services/create-resource.js +1 -1
  34. package/dist/modules/resource/services/delete-resource-relation.js +1 -1
  35. package/dist/modules/resource/services/delete-resource.js +1 -1
  36. package/dist/modules/resource/services/export-resource.js +1 -1
  37. package/dist/modules/resource/services/get-resource.js +1 -1
  38. package/dist/modules/resource/services/list-resource-relation.js +1 -1
  39. package/dist/modules/resource/services/list-resources.js +1 -1
  40. package/dist/modules/resource/services/search-resource.js +1 -1
  41. package/dist/modules/resource/services/suggest-resource.js +1 -1
  42. package/dist/modules/resource/services/update-resource-relation.js +1 -1
  43. package/dist/modules/resource/services/update-resource.js +1 -1
  44. package/dist/modules/resource/services/upload-resource-file.js +1 -1
  45. package/dist/modules/system/route.js +1 -1
  46. package/dist/modules/system/schema.js +1 -1
  47. package/dist/modules/system/services/check-system.js +1 -1
  48. package/dist/modules/system/services/get-access.js +1 -1
  49. package/dist/modules/system/services/get-api-list.js +1 -1
  50. package/dist/modules/system/services/get-audit-log.js +1 -1
  51. package/dist/modules/system/services/get-dictionary.js +1 -1
  52. package/dist/modules/system/services/get-system-log.js +1 -1
  53. package/dist/modules/system/services/get-system-settings.js +1 -1
  54. package/dist/modules/system/services/list-dictionaries.js +1 -1
  55. package/dist/modules/system/services/set-access.js +1 -1
  56. package/dist/modules/system/services/update-dictionary.js +1 -1
  57. package/dist/modules/system/services/update-system-settings.js +1 -1
  58. package/dist/modules/utils/require-admin.js +1 -1
  59. package/dist/modules/utils/safe-user.js +1 -1
  60. package/dist/modules/utils/unsupported.js +1 -1
  61. package/dist/plugins/audit/audit.js +1 -1
  62. package/dist/plugins/audit/services/write-audit.js +1 -1
  63. package/dist/plugins/auth/get-user-permissions.js +1 -1
  64. package/dist/plugins/auth/index.js +1 -1
  65. package/dist/plugins/auth/verifyUser.js +1 -1
  66. package/dist/plugins/dictionary.js +1 -1
  67. package/dist/plugins/file.js +1 -1
  68. package/dist/plugins/jwt.js +1 -1
  69. package/dist/plugins/logger/index.js +1 -1
  70. package/dist/plugins/logger/transport.js +1 -1
  71. package/dist/plugins/pg.js +1 -1
  72. package/dist/plugins/redis.js +1 -1
  73. package/dist/plugins/resource/resource.d.ts +1 -1
  74. package/dist/plugins/resource/resource.d.ts.map +1 -1
  75. package/dist/plugins/resource/resource.js +1 -1
  76. package/dist/plugins/resource/resource.registry.d.ts +3 -2
  77. package/dist/plugins/resource/resource.registry.d.ts.map +1 -1
  78. package/dist/plugins/resource/resource.registry.js +1 -1
  79. package/dist/plugins/resource/resource.types.d.ts +5 -4
  80. package/dist/plugins/resource/resource.types.d.ts.map +1 -1
  81. package/dist/plugins/resource/services/add-dictionary-lookup-data.js +1 -1
  82. package/dist/plugins/resource/services/add-file-token.js +1 -1
  83. package/dist/plugins/resource/services/add-table-lookup-data.js +1 -1
  84. package/dist/plugins/resource/services/create-relation.js +1 -1
  85. package/dist/plugins/resource/services/create.js +1 -1
  86. package/dist/plugins/resource/services/delete-relation.js +1 -1
  87. package/dist/plugins/resource/services/delete.js +1 -1
  88. package/dist/plugins/resource/services/find-one.js +1 -1
  89. package/dist/plugins/resource/services/find-relation.js +1 -1
  90. package/dist/plugins/resource/services/find.js +1 -1
  91. package/dist/plugins/resource/services/get-table-columns.js +1 -1
  92. package/dist/plugins/resource/services/update-relation.js +1 -1
  93. package/dist/plugins/resource/services/update.js +1 -1
  94. package/dist/plugins/resource/utils/auto-index.js +1 -1
  95. package/dist/plugins/resource/utils/fields.js +1 -1
  96. package/dist/plugins/resource/utils/filters.js +1 -1
  97. package/dist/plugins/resource/utils/permissions.js +1 -1
  98. package/dist/plugins/resource/utils/sort.js +1 -1
  99. package/dist/plugins/resource/utils/sql.js +1 -1
  100. package/dist/plugins/resource/utils/summary.js +1 -1
  101. package/dist/shared/getIP.js +1 -1
  102. package/migrations/20260903130000_move_notes_files_to_admin.sql +17 -17
  103. package/migrations/20260903140000_settings_nulls_not_distinct.sql +18 -18
  104. package/package.json +93 -93
package/LICENSE CHANGED
@@ -1,3 +1,3 @@
1
- Copyright (c) OpenGIS. All rights reserved.
2
-
3
- Proprietary and confidential.
1
+ Copyright (c) OpenGIS. All rights reserved.
2
+
3
+ Proprietary and confidential.
package/README.md CHANGED
@@ -1,72 +1,72 @@
1
- # @opengis/fcore
2
-
3
- Reusable backend foundation for OpenGIS Node.js applications: config, typed application context, PostgreSQL, Redis, S3 file storage, audit, trusted Resource CRUD, Core modules, Fastify integration and SQL migration runner.
4
-
5
- ## Install
6
-
7
- ```bash
8
- npm install @opengis/fcore
9
- ```
10
-
11
- ## Bootstrap
12
-
13
- ```ts
14
- import { createFCore } from '@opengis/fcore';
15
- import resources from './resources/index.js';
16
-
17
- export const ctx = await createFCore({ resources });
18
- ```
19
-
20
- ```ts
21
- import Fastify from 'fastify';
22
- import fcoreFastify from '@opengis/fcore/fastify';
23
- import { ctx } from './app.js';
24
-
25
- const app = Fastify();
26
- await app.register(fcoreFastify, { ctx });
27
- await app.listen({ port: ctx.config.port });
28
- ```
29
-
30
- ## Resource
31
-
32
- All dynamic table/column identifiers come from registered `ResourceContract` metadata. Values are SQL parameters.
33
-
34
- ## Migrations
35
-
36
- Project SQL files stay in `./migrations`. Build the package/application, then run `fcore-migrate` or import `runMigrations()`.
37
-
38
- ## Module service convention
39
-
40
- Module services are plain async functions with the canonical `service(params, ctx)` signature. `ctx` is passed explicitly from `fastify.ts` to each module `route.ts`; there is no `service.ts` or `createService()` factory.
41
-
42
- ## Structure
43
-
44
- ```bash
45
- @opengis/fcore
46
- ├── src/
47
- │ ├── plugins/
48
- │ │ ├── logger/
49
- │ │ ├── redis/
50
- │ │ ├── pg/
51
- │ │ ├── file/
52
- │ │ ├── audit/
53
- │ │ └── resource/
54
- │ ├── modules/
55
- │ │ ├── auth/
56
- │ │ ├── access/
57
- │ │ ├── resource/
58
- │ │ ├── file/
59
- │ │ ├── template/
60
- │ │ └── system/
61
- │ ├── migrations/
62
- │ ├── config.ts # loadConfig
63
- │ ├── context.ts # createContext, set, get
64
- │ ├── errors.ts # standard Errors
65
- │ ├── fastify.ts # fastify Plugins
66
- │ ├── fcore.ts # createFcore
67
- │ └── index.ts # export type, methods, etc
68
- ├── test/
69
- ├── engineering/
70
- ├── package.json
71
- └── tsconfig.json
1
+ # @opengis/fcore
2
+
3
+ Reusable backend foundation for OpenGIS Node.js applications: config, typed application context, PostgreSQL, Redis, S3 file storage, audit, trusted Resource CRUD, Core modules, Fastify integration and SQL migration runner.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @opengis/fcore
9
+ ```
10
+
11
+ ## Bootstrap
12
+
13
+ ```ts
14
+ import { createFCore } from '@opengis/fcore';
15
+ import resources from './resources/index.js';
16
+
17
+ export const ctx = await createFCore({ resources });
18
+ ```
19
+
20
+ ```ts
21
+ import Fastify from 'fastify';
22
+ import fcoreFastify from '@opengis/fcore/fastify';
23
+ import { ctx } from './app.js';
24
+
25
+ const app = Fastify();
26
+ await app.register(fcoreFastify, { ctx });
27
+ await app.listen({ port: ctx.config.port });
28
+ ```
29
+
30
+ ## Resource
31
+
32
+ All dynamic table/column identifiers come from registered `ResourceContract` metadata. Values are SQL parameters.
33
+
34
+ ## Migrations
35
+
36
+ Project SQL files stay in `./migrations`. Build the package/application, then run `fcore-migrate` or import `runMigrations()`.
37
+
38
+ ## Module service convention
39
+
40
+ Module services are plain async functions with the canonical `service(params, ctx)` signature. `ctx` is passed explicitly from `fastify.ts` to each module `route.ts`; there is no `service.ts` or `createService()` factory.
41
+
42
+ ## Structure
43
+
44
+ ```bash
45
+ @opengis/fcore
46
+ ├── src/
47
+ │ ├── plugins/
48
+ │ │ ├── logger/
49
+ │ │ ├── redis/
50
+ │ │ ├── pg/
51
+ │ │ ├── file/
52
+ │ │ ├── audit/
53
+ │ │ └── resource/
54
+ │ ├── modules/
55
+ │ │ ├── auth/
56
+ │ │ ├── access/
57
+ │ │ ├── resource/
58
+ │ │ ├── file/
59
+ │ │ ├── template/
60
+ │ │ └── system/
61
+ │ ├── migrations/
62
+ │ ├── config.ts # loadConfig
63
+ │ ├── context.ts # createContext, set, get
64
+ │ ├── errors.ts # standard Errors
65
+ │ ├── fastify.ts # fastify Plugins
66
+ │ ├── fcore.ts # createFcore
67
+ │ └── index.ts # export type, methods, etc
68
+ ├── test/
69
+ ├── engineering/
70
+ ├── package.json
71
+ └── tsconfig.json
72
72
  ```
package/dist/config.js CHANGED
@@ -1 +1 @@
1
- function f(){const H=['Missing\x20environment\x20variable:\x20','true','local','split','parse','logger','redis','auth'];f=function(){return H;};return f();}import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(w){const Z=Y,y=process.env[w];if(!y)throw new Error(Z(0xb8)+w);return y;}function Y(w,y){w=w-0xb8;const d=f();let Z=d[w];return Z;}export function loadConfig(w={}){const M=Y,y={'env':process.env.NODE_ENV??'development','debug':process.env.DEBUG===M(0xb9),'port':Number(process.env.PORT??0xbb8),'maxFileSize':+(process.env.MAX_FILE_SIZE||0x200),'rateLimit':{'disabled':process.env.RATE_LIMIT==='false','max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storageType':(process.env.STORAGE_TYPE??'s3')['toLowerCase']()===M(0xba)||!process.env.S3_ENDPOINT?M(0xba):'s3','storagePath':process.env.STORAGE_PATH??'./storage','redactionList':(process.env.REDACTION_LIST||'password')['split'](','),'logger':{'level':process.env.LOG_LEVEL??'info','responses':process.env.LOG_RESPONSES==='true'?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES[M(0xbb)](',')['map'](d=>d-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process['cwd']()+'/log'},'pg':{'host':process.env.PG_HOST??'localhost','port':Number(process.env.PG_PORT??0x1538),'database':process.env.PG_DATABASE??'','user':process.env.PG_USER??'','password':process.env.PG_PASSWORD??''},'redis':{'host':process.env.REDIS_HOST??'','port':Number(process.env.REDIS_PORT??0x18eb),'password':process.env.REDIS_PASSWORD,'lazyConnect':!![],'db':process.env.REDIS_DB?Number(process.env.REDIS_DB):undefined},'s3':{'endpoint':process.env.S3_ENDPOINT,'region':process.env.S3_REGION??'us-east-1','bucket':process.env.S3_BUCKET??'','accessKey':process.env.S3_ACCESS_KEY,'secretKey':process.env.S3_SECRET_KEY,'folder':process.env.S3_FOLDER,'forcePathStyle':process.env.S3_FORCE_PATH_STYLE!=='false','tokenSecret':process.env.FILE_TOKEN_SECRET,'tokenTtl':Number(process.env.FILE_TOKEN_TTL??0xe10)},'auth':{'accessToken':process.env.AUTH_ACCESS_TOKEN||'Ch7QR4e73Jg0wx0xOjm','user':process.env.AUTH_USER?JSON[M(0xbc)](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??'x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','cookieName':process.env.AUTH_COOKIE_NAME??'session_user_auth','jwtSecret':process.env.AUTH_JWT_SECRET??'0ua4b1Tz21m47z13U3EO0uN9e0WE7hqRFbcZ72cbdWqZBzemf9cAU865xan1s81TdNpUKKfF','redirect':process.env.AUTH_REDIRECT??'/','twoFactorRedirect':process.env.AUTH_TWOFACTOR_REDIRECT??'/','cookieOptions':process.env.AUTH_COOKIE_OPTIONS_DOMAIN?{'domain':process.env.AUTH_COOKIE_OPTIONS_DOMAIN,'path':process.env.AUTH_COOKIE_OPTIONS_PATH||'/','httpOnly':Boolean(process.env.AUTH_COOKIE_OPTIONS_HTTP_ONLY||'true'),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&['lax','strict','none']['includes'](process.env.AUTH_COOKIE_OPTIONS_SAME_SITE)?process.env.AUTH_COOKIE_OPTIONS_SAME_SITE:Boolean(process.env.AUTH_COOKIE_OPTIONS_SAME_SITE||'true')}:{'path':'/','httpOnly':!![],'secure':![],'sameSite':!![]}}};return{...y,...w,'logger':{...y[M(0xbd)],...w[M(0xbd)]},'pg':{...y['pg'],...w['pg']},'redis':{...y['redis'],...w[M(0xbe)]},'s3':{...y['s3'],...w['s3']},'auth':{...y['auth'],...w[M(0xbf)]}};}export{required as requireEnv};
1
+ import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(w){const h=process.env[w];if(!h)throw new Error('Missing\x20environment\x20variable:\x20'+w);return h;}function z(){const Y=['false','./storage','split','includes','true','auth'];z=function(){return Y;};return z();}function G(w,h){w=w-0xe9;const S=z();let X=S[w];return X;}export function loadConfig(w={}){const X=G,h={'env':process.env.NODE_ENV??'development','debug':process.env.DEBUG==='true','port':Number(process.env.PORT??0xbb8),'maxFileSize':+(process.env.MAX_FILE_SIZE||0x200),'rateLimit':{'disabled':process.env.RATE_LIMIT===X(0xe9),'max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storageType':(process.env.STORAGE_TYPE??'s3')['toLowerCase']()==='local'||!process.env.S3_ENDPOINT?'local':'s3','storagePath':process.env.STORAGE_PATH??X(0xea),'redactionList':(process.env.REDACTION_LIST||'password')[X(0xeb)](','),'logger':{'level':process.env.LOG_LEVEL??'info','responses':process.env.LOG_RESPONSES==='true'?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES['split'](',')['map'](S=>S-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process['cwd']()+'/log'},'pg':{'host':process.env.PG_HOST??'localhost','port':Number(process.env.PG_PORT??0x1538),'database':process.env.PG_DATABASE??'','user':process.env.PG_USER??'','password':process.env.PG_PASSWORD??''},'redis':{'host':process.env.REDIS_HOST??'','port':Number(process.env.REDIS_PORT??0x18eb),'password':process.env.REDIS_PASSWORD,'lazyConnect':!![],'db':process.env.REDIS_DB?Number(process.env.REDIS_DB):undefined},'s3':{'endpoint':process.env.S3_ENDPOINT,'region':process.env.S3_REGION??'us-east-1','bucket':process.env.S3_BUCKET??'','accessKey':process.env.S3_ACCESS_KEY,'secretKey':process.env.S3_SECRET_KEY,'folder':process.env.S3_FOLDER,'forcePathStyle':process.env.S3_FORCE_PATH_STYLE!=='false','tokenSecret':process.env.FILE_TOKEN_SECRET,'tokenTtl':Number(process.env.FILE_TOKEN_TTL??0xe10)},'auth':{'accessToken':process.env.AUTH_ACCESS_TOKEN||'Ch7QR4e73Jg0wx0xOjm','user':process.env.AUTH_USER?JSON['parse'](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??'x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','cookieName':process.env.AUTH_COOKIE_NAME??'session_user_auth','jwtSecret':process.env.AUTH_JWT_SECRET??'0ua4b1Tz21m47z13U3EO0uN9e0WE7hqRFbcZ72cbdWqZBzemf9cAU865xan1s81TdNpUKKfF','redirect':process.env.AUTH_REDIRECT??'/','twoFactorRedirect':process.env.AUTH_TWOFACTOR_REDIRECT??'/','cookieOptions':process.env.AUTH_COOKIE_OPTIONS_DOMAIN?{'domain':process.env.AUTH_COOKIE_OPTIONS_DOMAIN,'path':process.env.AUTH_COOKIE_OPTIONS_PATH||'/','httpOnly':Boolean(process.env.AUTH_COOKIE_OPTIONS_HTTP_ONLY||'true'),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&['lax','strict','none'][X(0xec)](process.env.AUTH_COOKIE_OPTIONS_SAME_SITE)?process.env.AUTH_COOKIE_OPTIONS_SAME_SITE:Boolean(process.env.AUTH_COOKIE_OPTIONS_SAME_SITE||X(0xed))}:{'path':'/','httpOnly':!![],'secure':![],'sameSite':!![]}}};return{...h,...w,'logger':{...h['logger'],...w['logger']},'pg':{...h['pg'],...w['pg']},'redis':{...h['redis'],...w['redis']},'s3':{...h['s3'],...w['s3']},'auth':{...h['auth'],...w[X(0xee)]}};}export{required as requireEnv};
package/dist/context.js CHANGED
@@ -1 +1 @@
1
- function f(){const Z=['Application\x20context\x20is\x20not\x20initialized','allSettled','end'];f=function(){return Z;};return f();}let defaultContext;function Y(w,y){w=w-0x1a4;const d=f();let Z=d[w];return Z;}export function setContext(w){defaultContext=w;}export function getContext(){const y=Y;if(!defaultContext)throw new Error(y(0x1a4));return defaultContext;}export function createContext(w){return{...w,async 'close'(){const d=Y;await Promise[d(0x1a5)]([w['redis']?.['close'](),w['pg']?.[d(0x1a6)]()]),await w['logger']['close']();}};}
1
+ let defaultContext;function G(w,h){w=w-0xf2;const S=z();let X=S[w];return X;}function z(){const X=['Application\x20context\x20is\x20not\x20initialized','close'];z=function(){return X;};return z();}export function setContext(w){defaultContext=w;}export function getContext(){const h=G;if(!defaultContext)throw new Error(h(0xf2));return defaultContext;}export function createContext(w){return{...w,async 'close'(){const S=G;await Promise['allSettled']([w['redis']?.[S(0xf3)](),w['pg']?.['end']()]),await w['logger']['close']();}};}
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- function Y(w,y){w=w-0x189;var d=f();var Z=d[w];return Z;}var M=Y;export class FCoreError extends Error{['code'];['statusCode'];['details'];constructor(w,y,d=0x1f4,Z){super(y),this['code']=w,this['statusCode']=d,this['details']=Z,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(w,y){super('BAD_REQUEST_ERROR',w,0x190,y);}}export class UnauthorizedError extends FCoreError{constructor(w=M(0x189)){super('UNAUTHORIZED',w,0x191);}}export class ForbiddenError extends FCoreError{constructor(w='Access\x20denied'){super('FORBIDDEN',w,0x193);}}export class NotFoundError extends FCoreError{constructor(w='Not\x20found'){var H=M;super(H(0x18a),w,0x194);}}export class ConflictError extends FCoreError{constructor(w=M(0x18b)){super('CONFLICT',w,0x199);}}export class ValidationError extends FCoreError{constructor(w,y){super('VALIDATION_ERROR',w,0x1a6,y);}}export class UnsupportedError extends FCoreError{constructor(w='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',w,0x1f5);}}function f(){var Q=['Authentication\x20required','NOT_FOUND','Conflict'];f=function(){return Q;};return f();}
1
+ function G(w,h){w=w-0x112;var S=z();var X=S[w];return X;}var Y=G;export class FCoreError extends Error{['code'];['statusCode'];[Y(0x112)];constructor(w,h,S=0x1f4,X){var v=Y;super(h),this[v(0x113)]=w,this[v(0x114)]=S,this['details']=X,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(w,h){super('BAD_REQUEST_ERROR',w,0x190,h);}}export class UnauthorizedError extends FCoreError{constructor(w='Authentication\x20required'){super('UNAUTHORIZED',w,0x191);}}export class ForbiddenError extends FCoreError{constructor(w='Access\x20denied'){var D=Y;super(D(0x115),w,0x193);}}export class NotFoundError extends FCoreError{constructor(w='Not\x20found'){super('NOT_FOUND',w,0x194);}}export class ConflictError extends FCoreError{constructor(w='Conflict'){var o=Y;super(o(0x116),w,0x199);}}export class ValidationError extends FCoreError{constructor(w,h){super('VALIDATION_ERROR',w,0x1a6,h);}}export class UnsupportedError extends FCoreError{constructor(w='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',w,0x1f5);}}function z(){var q=['details','code','statusCode','FORBIDDEN','CONFLICT'];z=function(){return q;};return z();}
package/dist/fastify.js CHANGED
@@ -1 +1 @@
1
- import w from'fastify-plugin';import{FCoreError}from'./errors.js';import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';import{resourceRoutes}from'./modules/resource/route.js';function Y(w,y){w=w-0xd7;const d=f();let Z=d[w];return Z;}import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';import{ForbiddenError}from'./errors.js';function f(){const A=['split','decorate','method','fcore','tags','description','set','get','routeOptions','user','startsWith','public','User\x20required','type','Admin\x20access\x20required','replace','$resource','Missing\x20permission:\x20','setErrorHandler','statusCode','code','test','INTERNAL_ERROR','includes','auth','file','system','application/x-www-form-urlencoded','register','@fastify/rate-limit','max','preHandler','log'];f=function(){return A;};return f();}import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(y,d,Z){const G=Y,M=decodeURIComponent(d['toString']())[G(0xd7)]('&')['reduce']((H,Q)=>{const [s,j]=Q['split']('=');return{...H,[s]:j};},{});Z(null,M);}export default function fcoreFastify(y,d){return w(async Z=>{const U=Y;Z[U(0xd8)]('ctx',y);const {config:M}=y,H=new Map();Z['addHook']('onRoute',s=>{const E=U,j=s['schema'],n=Array['isArray'](s[E(0xd9)])?s['method']:[s['method']];for(const t of n){if(t==='HEAD')continue;const K={'method':t,'endpoint':s['url'],'package':j?.['package']??E(0xda),'tags':j?.[E(0xdb)]??[],'summary':j?.['summary']??'','description':j?.[E(0xdc)]??'','access':j?.['access']??'public','permissions':j?.['permissions']??[]};H[E(0xdd)](t+'\x20'+s['url'],K);}}),Z['addHook']('preHandler',async s=>{const e=U;if(s['routeOptions']['url']==='*')return!![];const j=H[e(0xde)](s['method']+'\x20'+s[e(0xdf)]['url']),n=!s['user']&&process['platform']==='win32'&&y['config']?.['auth']?.['user']?y['config']?.['auth']?.[e(0xe0)]:null,t=s['raw']['headers']?.['authorization'],K=t?.[e(0xe1)]('Bearer\x20')?t['slice'](0x7):null,T=s['user']??(K?await jwtVerifyToken(K):n);!s['user']&&K&&process.env.AUTH_JWT_SECRET&&(s[e(0xe0)]=await jwtVerifyToken(K));if(!j?.['access'])throw new ForbiddenError('Route\x20access\x20not\x20defined');if(j['access']===e(0xe2))return!![];if(!T)throw new ForbiddenError(e(0xe3));if(j['access']==='user'&&!j['permissions']?.['length'])return!![];if(T[e(0xe4)]=='admin')return!![];if(j['access']==='admin')throw new ForbiddenError(e(0xe5));for(const h of j['permissions']){const i=h?.[e(0xe6)](e(0xe7),s['params']['resource']??'');if(!T['permissions']?.['includes'](i))throw new ForbiddenError(e(0xe8)+i);}return!![];}),await createSessionStore(Z,y),await Z['register'](import('@fastify/multipart'),{'limits':{'fileSize':M['maxFileSize']*0x400*0x400}}),Z[U(0xe9)]((s,j,n)=>{const l=U;if(s instanceof FCoreError||s['code']==='FST_ERR_VALIDATION'||s[l(0xea)]<0x1f4)return s[l(0xea)]<0x1f4&&y['logger']['warn'](s),n[l(0xeb)](s['statusCode'])['send']({'error':s[l(0xeb)],'message':s['message'],'details':s['details']});return y['logger']['error'](s),(M['debug']||process.env.NODE_ENV===l(0xec)||process.env.VITEST)&&console['error'](s),n['code'](0x1f4)['send']({'error':l(0xed),'message':'Internal\x20server\x20error'});});const Q=s=>!d||d[U(0xee)](s);if(Q(U(0xef)))await Z['register'](authRoutes(y));if(Q('resource'))await Z['register'](resourceRoutes(y));if(Q(U(0xf0)))await Z['register'](fileRoutes(y));if(Q(U(0xf1)))await Z['register'](systemRoutes(y,H));Z['addContentTypeParser'](U(0xf2),{'parseAs':'buffer'},urlencodedContentParser),!M['rateLimit']?.['disabled']?Z[U(0xf3)](import(U(0xf4)),{'max':M['rateLimit']?.[U(0xf5)]||0x64,'timeWindow':M['rateLimit']?.['timeWindow']||0xea60,'hook':U(0xf6),'global':!![],'keyGenerator':s=>(s['user']?.['id']||s['ip'])+'-'+s['raw']['url']['split']('?')[0x0]}):console[U(0xf7)]('⚠️\x20rate\x20limit\x20is\x20disabled');});}
1
+ import w from'fastify-plugin';import{FCoreError}from'./errors.js';import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';import{resourceRoutes}from'./modules/resource/route.js';import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';import{ForbiddenError}from'./errors.js';import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(h,S,X){const H=G,Y=decodeURIComponent(S[H(0x12a)]())['split']('&')['reduce']((v,D)=>{const R=H,[o,q]=D[R(0x12b)]('=');return{...v,[o]:q};},{});X(null,Y);}function G(w,h){w=w-0x12a;const S=z();let X=S[w];return X;}function z(){const d=['toString','split','method','url','get','config','auth','headers','authorization','startsWith','user','access','permissions','type','admin','params','maxFileSize','setErrorHandler','FST_ERR_VALIDATION','statusCode','code','send','resource','system','addContentTypeParser','max'];z=function(){return d;};return z();}export default function fcoreFastify(h,S){return w(async X=>{const x=G;X['decorate']('ctx',h);const {config:Y}=h,v=new Map();X['addHook']('onRoute',o=>{const Q=G,q=o['schema'],e=Array['isArray'](o['method'])?o[Q(0x12c)]:[o['method']];for(const Z of e){if(Z==='HEAD')continue;const K={'method':Z,'endpoint':o['url'],'package':q?.['package']??'fcore','tags':q?.['tags']??[],'summary':q?.['summary']??'','description':q?.['description']??'','access':q?.['access']??'public','permissions':q?.['permissions']??[]};v['set'](Z+'\x20'+o['url'],K);}}),X['addHook']('preHandler',async o=>{const P=G;if(o['routeOptions'][P(0x12d)]==='*')return!![];const q=v[P(0x12e)](o[P(0x12c)]+'\x20'+o['routeOptions']['url']),e=!o['user']&&process['platform']==='win32'&&h[P(0x12f)]?.['auth']?.['user']?h['config']?.[P(0x130)]?.['user']:null,Z=o['raw'][P(0x131)]?.[P(0x132)],K=Z?.[P(0x133)]('Bearer\x20')?Z['slice'](0x7):null,y=o['user']??(K?await jwtVerifyToken(K):e);!o['user']&&K&&process.env.AUTH_JWT_SECRET&&(o[P(0x134)]=await jwtVerifyToken(K));if(!q?.['access'])throw new ForbiddenError('Route\x20access\x20not\x20defined');if(q['access']==='public')return!![];if(!y)throw new ForbiddenError('User\x20required');if(q[P(0x135)]==='user'&&!q[P(0x136)]?.['length'])return!![];if(y[P(0x137)]==P(0x138))return!![];if(q['access']===P(0x138))throw new ForbiddenError('Admin\x20access\x20required');for(const V of q[P(0x136)]){const O=V?.['replace']('$resource',o[P(0x139)]['resource']??'');if(!y[P(0x136)]?.['includes'](O))throw new ForbiddenError('Missing\x20permission:\x20'+O);}return!![];}),await createSessionStore(X,h),await X['register'](import('@fastify/multipart'),{'limits':{'fileSize':Y[x(0x13a)]*0x400*0x400}}),X[x(0x13b)]((o,q,e)=>{const c=x;if(o instanceof FCoreError||o['code']===c(0x13c)||o[c(0x13d)]<0x1f4)return o['statusCode']<0x1f4&&h['logger']['warn'](o),e[c(0x13e)](o['statusCode'])[c(0x13f)]({'error':o['code'],'message':o['message'],'details':o['details']});return h['logger']['error'](o),(Y['debug']||process.env.NODE_ENV==='test'||process.env.VITEST)&&console['error'](o),e[c(0x13e)](0x1f4)['send']({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const D=o=>!S||S['includes'](o);if(D('auth'))await X['register'](authRoutes(h));if(D(x(0x140)))await X['register'](resourceRoutes(h));if(D('file'))await X['register'](fileRoutes(h));if(D(x(0x141)))await X['register'](systemRoutes(h,v));X[x(0x142)]('application/x-www-form-urlencoded',{'parseAs':'buffer'},urlencodedContentParser),!Y['rateLimit']?.['disabled']?X['register'](import('@fastify/rate-limit'),{'max':Y['rateLimit']?.[x(0x143)]||0x64,'timeWindow':Y['rateLimit']?.['timeWindow']||0xea60,'hook':'preHandler','global':!![],'keyGenerator':o=>(o['user']?.['id']||o['ip'])+'-'+o['raw'][x(0x12d)][x(0x12b)]('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');});}
package/dist/fcore.js CHANGED
@@ -1 +1 @@
1
- import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';import{createAudit,createDatabase,createDictionary,createFileLocal,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function Y(w,y){w=w-0x93;const d=f();let Z=d[w];return Z;}function f(){const K=['local','storagePath','tokenSecret','region','bucket','secretKey','folder'];f=function(){return K;};return f();}export async function createFCore(w={}){const t=Y,y=loadConfig(w['config']),d=createRedis(y['redis']),Z=createLogger(),M=createDatabase(y['pg']),H=y['storageType']===t(0x93)?createFileLocal({'storagePath':y[t(0x94)],'folder':y['s3']['folder'],'tokenSecret':y['s3'][t(0x95)],'tokenTtl':y['s3']['tokenTtl']}):createFileS3({'endpoint':y['s3']['endpoint'],'region':y['s3'][t(0x96)],'bucket':y['s3'][t(0x97)],'accessKey':y['s3']['accessKey'],'secretKey':y['s3'][t(0x98)],'folder':y['s3'][t(0x99)],'forcePathStyle':y['s3']['forcePathStyle'],'tokenSecret':y['s3']['tokenSecret'],'tokenTtl':y['s3']['tokenTtl']}),Q=createAudit({'pg':M,'logger':Z}),s=createDictionary({'pg':M,'dictionaries':w['dictionaries']}),j=createResource({'pg':M,'logger':Z,'audit':Q,'dictionary':s,'file':H});w['resources']?.['length']&&j['register'](w['resources']);const n=createContext({'config':y,'logger':Z,'redis':d,'pg':M,'file':H,'resource':j,'audit':Q,'dictionary':s});return setContext(n),n;}
1
+ import{loadConfig}from'./config.js';function z(){const K=['local','tokenSecret','tokenTtl','endpoint','region','dictionaries','resources'];z=function(){return K;};return z();}import{createContext,setContext}from'./context.js';import{createAudit,createDatabase,createDictionary,createFileLocal,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function G(w,h){w=w-0x97;const S=z();let X=S[w];return X;}export async function createFCore(w={}){const Z=G,h=loadConfig(w['config']),S=createRedis(h['redis']),X=createLogger(),Y=createDatabase(h['pg']),v=h['storageType']===Z(0x97)?createFileLocal({'storagePath':h['storagePath'],'folder':h['s3']['folder'],'tokenSecret':h['s3'][Z(0x98)],'tokenTtl':h['s3'][Z(0x99)]}):createFileS3({'endpoint':h['s3'][Z(0x9a)],'region':h['s3'][Z(0x9b)],'bucket':h['s3']['bucket'],'accessKey':h['s3']['accessKey'],'secretKey':h['s3']['secretKey'],'folder':h['s3']['folder'],'forcePathStyle':h['s3']['forcePathStyle'],'tokenSecret':h['s3']['tokenSecret'],'tokenTtl':h['s3']['tokenTtl']}),D=createAudit({'pg':Y,'logger':X}),o=createDictionary({'pg':Y,'dictionaries':w[Z(0x9c)]}),q=createResource({'pg':Y,'logger':X,'audit':D,'dictionary':o,'file':v});w[Z(0x9d)]?.['length']&&q['register'](w[Z(0x9d)]);const e=createContext({'config':h,'logger':X,'redis':S,'pg':Y,'file':v,'resource':q,'audit':D,'dictionary':o});return setContext(e),e;}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- function Y(w,y){w=w-0x19e;const d=f();let Z=d[w];return Z;}const j=Y;import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';import w from'node:path';import{fileURLToPath}from'node:url';const packageMigrations=fileURLToPath(new URL('../../migrations',import.meta.url));function migrationDirectory(y){const s=Y,d=y['indexOf']('--dir');if(d>=0x0){const M=y[d+0x1];if(!M)throw new Error(s(0x19e));return w[s(0x19f)](M);}if(y['includes']('--fcore'))return packageMigrations;const Z=y[s(0x1a0)](H=>!H['startsWith']('--'));return w['resolve'](Z??s(0x1a1));}function f(){const n=['--dir\x20requires\x20a\x20folder\x20path','resolve','find','migrations','slice','****','log','run','exitCode'];f=function(){return n;};return f();}try{const config=loadConfig(),dir=migrationDirectory(process['argv'][j(0x1a2)](0x2));console['log']('Loaded\x20configuration:',{...config['pg'],'user':'****','password':j(0x1a3)}),console[j(0x1a4)]('Using\x20migration\x20directory:',dir,process['argv']['slice'](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console['log']((r['status']===j(0x1a5)?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(Q){console['error'](Q),process[j(0x1a6)]=0x1;}
2
+ const q=G;import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';import w from'node:path';import{fileURLToPath}from'node:url';function G(w,h){w=w-0x116;const S=z();let X=S[w];return X;}const packageMigrations=fileURLToPath(new URL('../../migrations',import.meta.url));function migrationDirectory(h){const o=G,S=h['indexOf']('--dir');if(S>=0x0){const Y=h[S+0x1];if(!Y)throw new Error('--dir\x20requires\x20a\x20folder\x20path');return w['resolve'](Y);}if(h['includes']('--fcore'))return packageMigrations;const X=h[o(0x116)](v=>!v[o(0x117)]('--'));return w['resolve'](X??'migrations');}try{const config=loadConfig(),dir=migrationDirectory(process[q(0x118)]['slice'](0x2));console[q(0x119)]('Loaded\x20configuration:',{...config['pg'],'user':'****','password':'****'}),console[q(0x119)](q(0x11a),dir,process['argv'][q(0x11b)](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console['log']((r[q(0x11c)]==='run'?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(D){console['error'](D),process[q(0x11d)]=0x1;}function z(){const e=['find','startsWith','argv','log','Using\x20migration\x20directory:','slice','status','exitCode'];z=function(){return e;};return z();}
@@ -1 +1 @@
1
- import w from'node:fs/promises';import y from'node:path';function f(){const U=['dir','databaseUrl','query','filter','endsWith','push','skip','readFile','INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)','password'];f=function(){return U;};return f();}function Y(w,y){w=w-0xd2;const d=f();let Z=d[w];return Z;}import{createDatabase}from'../plugins/pg.js';export async function runMigrations(d={}){const i=Y,Z=y['resolve'](d[i(0xd2)]??'migrations'),M=d['database']??databaseFromUrl(d[i(0xd3)]??process.env.DATABASE_URL);if(!M)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const H=createDatabase(M);if(!H)throw new Error('empty\x20pg');const Q=[];try{await H[i(0xd4)]('\x0a\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20IF\x20NOT\x20EXISTS\x20schema_migrations\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20version\x20varchar(255)\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20applied_at\x20timestamptz\x20NOT\x20NULL\x20DEFAULT\x20now()\x0a\x20\x20\x20\x20\x20\x20)\x0a\x20\x20\x20\x20');const s=await H['query']('SELECT\x20version\x20FROM\x20schema_migrations'),j=new Set(s['rows']['map'](t=>t['version'])),n=(await w['readdir'](Z))[i(0xd5)](t=>t[i(0xd6)]('.sql'))['sort']();for(const t of n){if(j['has'](t)){Q[i(0xd7)]({'file':t,'status':i(0xd8)});continue;}const K=await w[i(0xd9)](y['join'](Z,t),'utf8'),T=await H['connect']();try{await T['query']('BEGIN'),await T[i(0xd4)](K),await T['query'](i(0xda),[t]),await T[i(0xd4)]('COMMIT');}catch(h){await T['query']('ROLLBACK');throw h;}finally{T['release']();}Q[i(0xd7)]({'file':t,'status':'run'});}return Q;}finally{await H['end']();}}function databaseFromUrl(d){const G=Y;if(!d)return undefined;const Z=new URL(d);return{'host':Z['hostname'],'port':Number(Z['port']||0x1538),'database':Z['pathname']['slice'](0x1),'user':decodeURIComponent(Z['username']),'password':decodeURIComponent(Z[G(0xdb)])};}
1
+ import w from'node:fs/promises';import h from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(S={}){const O=G,X=h['resolve'](S['dir']??O(0x1a0)),Y=S[O(0x1a1)]??databaseFromUrl(S[O(0x1a2)]??process.env.DATABASE_URL);if(!Y)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const v=createDatabase(Y);if(!v)throw new Error('empty\x20pg');const D=[];try{await v[O(0x1a3)]('\x0a\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20IF\x20NOT\x20EXISTS\x20schema_migrations\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20version\x20varchar(255)\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20applied_at\x20timestamptz\x20NOT\x20NULL\x20DEFAULT\x20now()\x0a\x20\x20\x20\x20\x20\x20)\x0a\x20\x20\x20\x20');const o=await v['query']('SELECT\x20version\x20FROM\x20schema_migrations'),q=new Set(o[O(0x1a4)][O(0x1a5)](Z=>Z[O(0x1a6)])),e=(await w['readdir'](X))[O(0x1a7)](Z=>Z['endsWith']('.sql'))['sort']();for(const Z of e){if(q['has'](Z)){D['push']({'file':Z,'status':O(0x1a8)});continue;}const K=await w['readFile'](h['join'](X,Z),'utf8'),y=await v[O(0x1a9)]();try{await y['query']('BEGIN'),await y['query'](K),await y[O(0x1a3)](O(0x1aa),[Z]),await y['query']('COMMIT');}catch(V){await y[O(0x1a3)]('ROLLBACK');throw V;}finally{y['release']();}D['push']({'file':Z,'status':'run'});}return D;}finally{await v[O(0x1ab)]();}}function G(w,h){w=w-0x1a0;const S=z();let X=S[w];return X;}function z(){const H=['migrations','database','databaseUrl','query','rows','map','version','filter','skip','connect','INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)','end'];z=function(){return H;};return z();}function databaseFromUrl(S){if(!S)return undefined;const X=new URL(S);return{'host':X['hostname'],'port':Number(X['port']||0x1538),'database':X['pathname']['slice'](0x1),'user':decodeURIComponent(X['username']),'password':decodeURIComponent(X['password'])};}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const d=Y;import{loadConfig}from'../../config.js';function Y(w,y){w=w-0xa2;const d=f();let Z=d[w];return Z;}import{createDatabase}from'../../plugins/pg.js';function f(){const Z=['argv','Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]','exitCode','Registered\x20user\x20','end'];f=function(){return Z;};return f();}import w from'./services/registration.js';const [user,password,type]=process[d(0xa2)]['slice'](0x2);if(!user||!password)console['error'](d(0xa3)),process[d(0xa4)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await w({'user':user,'password':password,'type':type},{'pg':pg});console['log'](d(0xa5)+data['id']+'\x20('+data['type']+')');}catch(y){console['error'](y),process['exitCode']=0x1;}finally{await pg[d(0xa6)]();}}
2
+ function G(w,h){w=w-0x100;const S=z();let X=S[w];return X;}function z(){const X=['argv','error'];z=function(){return X;};return z();}const S=G;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import w from'./services/registration.js';const [user,password,type]=process[S(0x100)]['slice'](0x2);if(!user||!password)console['error']('Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await w({'user':user,'password':password,'type':type},{'pg':pg});console['log']('Registered\x20user\x20'+data['id']+'\x20('+data['type']+')');}catch(h){console[S(0x101)](h),process['exitCode']=0x1;}finally{await pg['end']();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- function Y(w,y){w=w-0x19c;const d=f();let Z=d[w];return Z;}const d=Y;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import w from'./services/change-password.js';function f(){const Z=['argv','error','query','User\x20not\x20found','Password\x20changed\x20for\x20'];f=function(){return Z;};return f();}const [login,password]=process[d(0x19c)]['slice'](0x2);if(!login||!password)console[d(0x19d)]('Usage:\x20fcore-password\x20<login>\x20<password>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg[d(0x19e)]('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result['rows'][0x0];if(!user)throw new Error(d(0x19f));await w({'userId':user['id'],'password':password},{'pg':pg}),console['log'](d(0x1a0)+login);}catch(y){console['error'](y),process['exitCode']=0x1;}finally{await pg['end']();}}
2
+ function G(w,h){w=w-0x1b7;const S=z();let X=S[w];return X;}function z(){const X=['argv','query','SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201','User\x20not\x20found','Password\x20changed\x20for\x20','error','end'];z=function(){return X;};return z();}const S=G;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import w from'./services/change-password.js';const [login,password]=process[S(0x1b7)]['slice'](0x2);if(!login||!password)console['error']('Usage:\x20fcore-password\x20<login>\x20<password>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg[S(0x1b8)](S(0x1b9),[login]),user=result['rows'][0x0];if(!user)throw new Error(S(0x1ba));await w({'userId':user['id'],'password':password},{'pg':pg}),console['log'](S(0x1bb)+login);}catch(h){console[S(0x1bc)](h),process['exitCode']=0x1;}finally{await pg[S(0x1bd)]();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const j=Y;import{loadConfig}from'../../config.js';function Y(w,y){w=w-0xf8;const d=f();let Z=d[w];return Z;}import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=[j(0xf8),'audit',j(0xf9),'check','access','settings',j(0xfa)],RESOURCE_ACTIONS=[j(0xfb),j(0xfc),j(0xfd),'delete'],[login,permissionArg]=process['argv']['slice'](0x2);function f(){const t=['logs','list','dictionaries','read','update','create','split','map','filter','system','error','Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>','exitCode','User\x20not\x20found','DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL','log','Permissions\x20cleared\x20for\x20','get','connect','BEGIN','SELECT\x20access_id,\x20actions\x20FROM\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL\x20AND\x20resource\x20=\x20$2','actions','INSERT\x20INTO\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(\x20resource,\x20actions,\x20user_uid,\x20created_by,\x20updated_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$4)','ROLLBACK'];f=function(){return t;};return f();}function expandPermissions(w){const n=j,y=w[n(0xfe)](',')[n(0xff)](Z=>Z['trim']())[n(0x100)](Boolean),d=new Set();for(const Z of y){if(Z['includes'](':')){d['add'](Z);continue;}const M=Z===n(0x101)?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const H of M){d['add'](Z+':'+H);}}return[...d];}if(!login||!permissionArg)console[j(0x102)](j(0x103)),process[j(0x104)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg['query']('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result['rows'][0x0];if(!user)throw new Error(j(0x105));if(permissionArg['trim']()==='clear')await pg['query'](j(0x106),[user['id']]),console[j(0x107)](j(0x108)+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource[j(0x109)](resource)??[];actions['push'](action),byResource['set'](resource,actions);}const client=await pg[j(0x10a)]();try{await client['query'](j(0x10b));for(const [resource,actions]of byResource){const existing=await client['query'](j(0x10c),[user['id'],resource]),row=existing['rows'][0x0];if(row){const merged=[...new Set([...row[j(0x10d)]??[],...actions])];await client['query']('UPDATE\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20actions\x20=\x20$1,\x20updated_by\x20=\x20$2,\x20updated_at\x20=\x20now()\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20access_id\x20=\x20$3',[merged,user['id'],row['access_id']]);}else await client['query'](j(0x10e),[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(Q){await client['query'](j(0x10f));throw Q;}finally{client['release']();}console['log']('Granted\x20permissions\x20for\x20'+login+':\x20'+permissions['join'](',\x20'));}}catch(s){console['error'](s),process[j(0x104)]=0x1;}finally{await pg['end']();}}
2
+ const q=G;import{loadConfig}from'../../config.js';function G(w,h){w=w-0x1b6;const S=z();let X=S[w];return X;}function z(){const Z=['logs','create','argv','split','map','SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201','User\x20not\x20found','trim','log','push','actions','UPDATE\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20actions\x20=\x20$1,\x20updated_by\x20=\x20$2,\x20updated_at\x20=\x20now()\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20access_id\x20=\x20$3','access_id','INSERT\x20INTO\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(\x20resource,\x20actions,\x20user_uid,\x20created_by,\x20updated_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$4)','query','release','Granted\x20permissions\x20for\x20'];z=function(){return Z;};return z();}import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=[q(0x1b6),'audit','list','check','access','settings','dictionaries'],RESOURCE_ACTIONS=['read','update',q(0x1b7),'delete'],[login,permissionArg]=process[q(0x1b8)]['slice'](0x2);function expandPermissions(w){const e=q,h=w[e(0x1b9)](',')[e(0x1ba)](X=>X['trim']())['filter'](Boolean),S=new Set();for(const X of h){if(X['includes'](':')){S['add'](X);continue;}const Y=X==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const v of Y){S['add'](X+':'+v);}}return[...S];}if(!login||!permissionArg)console['error']('Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg['query'](q(0x1bb),[login]),user=result['rows'][0x0];if(!user)throw new Error(q(0x1bc));if(permissionArg[q(0x1bd)]()==='clear')await pg['query']('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console[q(0x1be)]('Permissions\x20cleared\x20for\x20'+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource['get'](resource)??[];actions[q(0x1bf)](action),byResource['set'](resource,actions);}const client=await pg['connect']();try{await client['query']('BEGIN');for(const [resource,actions]of byResource){const existing=await client['query']('SELECT\x20access_id,\x20actions\x20FROM\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL\x20AND\x20resource\x20=\x20$2',[user['id'],resource]),row=existing['rows'][0x0];if(row){const merged=[...new Set([...row[q(0x1c0)]??[],...actions])];await client['query'](q(0x1c1),[merged,user['id'],row[q(0x1c2)]]);}else await client['query'](q(0x1c3),[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(D){await client[q(0x1c4)]('ROLLBACK');throw D;}finally{client[q(0x1c5)]();}console['log'](q(0x1c6)+login+':\x20'+permissions['join'](',\x20'));}}catch(o){console['error'](o),process['exitCode']=0x1;}finally{await pg['end']();}}
@@ -1 +1 @@
1
- {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../src/modules/auth/route.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAkB,MAAM,SAAS,CAAC;AAClE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAYnD,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,kBAAkB,CAoK9D"}
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../src/modules/auth/route.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAkB,MAAM,SAAS,CAAC;AAClE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAYnD,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,kBAAkB,CA0K9D"}
@@ -1 +1 @@
1
- function Y(w,y){w=w-0x176;const d=f();let Z=d[w];return Z;}import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import w from'./services/get-current-user.js';import y from'./services/registration.js';import d from'./services/change-password.js';function f(){const E=['GET','permissions','redirect','login','config','session','maxAge','save','audit','auth','fcore','Sign\x20in','Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','public','Creates\x20a\x20regular\x20user\x20account.','admin','post','Change\x20password','user','body','destroy','cookieName','Get\x20current\x20user'];f=function(){return E;};return f();}import{authSchemas}from'./schema.js';import Z from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(M){return async H=>{const i=Y,Q=async s=>{const h=Y,j=s['method']===h(0x176)?s['query']:s['body'],n=Z(s),t=await verifyUser({...j,'ip':n},M);t[h(0x177)]=await getUserPermissions(t['id'],M);const K=t['twofa']?M['config']['auth']['twoFactorRedirect']:M['config']['auth'][h(0x178)];await s[h(0x179)](t);const T=M[h(0x17a)]['auth']['sessionTimeout']*0x3e8*0x3c;return s['session']?.['cookie']&&(s[h(0x17b)]['cookie'][h(0x17c)]=T),await s['session'][h(0x17d)](),await M[h(0x17e)]?.['write']?.({'module':h(0x17f),'resource':'session','resourceId':s['session']['sessionId'],'action':h(0x179),'userId':t['id'],'ipAddress':n}),{'user':{'id':t['id'],'type':t['type'],'permissions':t['permissions']},'redirectUrl':K};};H['get']('/api/auth/login',{'schema':{'tags':[i(0x180),'auth'],'summary':i(0x181),'description':i(0x182),'access':i(0x183),'permissions':[],'querystring':authSchemas['credentials']}},Q),H['post']('/api/auth/login',{'schema':{'tags':[i(0x180),'auth'],'summary':'Sign\x20in','description':i(0x182),'access':'public','permissions':[],'body':authSchemas['credentials']}},Q),H['post']('/api/auth/registration',{'schema':{'tags':['fcore','auth'],'summary':'Register','description':i(0x184),'access':i(0x185),'permissions':['user:create'],'body':authSchemas['credentials']}},async s=>y(s['body'],M)),H[i(0x186)]('/api/auth/password',{'schema':{'tags':[i(0x180),i(0x17f)],'summary':i(0x187),'description':'Changes\x20the\x20password\x20for\x20the\x20current\x20user.','access':i(0x188),'permissions':[],'body':authSchemas['password']}},async s=>{const G=i;if(!s[G(0x188)])throw new UnauthorizedError('Not\x20authorized');return await d({'userId':s[G(0x188)]['id'],...s[G(0x189)]},M),{'success':!![]};}),H['post']('/api/auth/logout',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':'Terminates\x20the\x20current\x20user\x20session.','access':i(0x188),'permissions':[]}},async(s,j)=>{const U=i,n={'redirectUrl':'/'};if(!s[U(0x188)])return n;return await M['audit']?.['write']?.({'module':U(0x17f),'resource':'session','resourceId':s[U(0x17b)]['sessionId'],'action':'logout','userId':s['user']?.['id']}),await s['session'][U(0x18a)](),j['clearCookie'](M['config']['auth'][U(0x18b)]),Object['defineProperty'](s,'session',{'value':null,'writable':![],'configurable':![]}),n;}),H['get']('/api/auth/user',{'schema':{'tags':['fcore',i(0x17f)],'summary':i(0x18c),'description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas['query']}},async s=>w({'user':s[i(0x188)],'token':s['query']['token']}));};}
1
+ import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import w from'./services/get-current-user.js';import h from'./services/registration.js';import S from'./services/change-password.js';import{authSchemas}from'./schema.js';import X from'../../shared/getIP.js';function z(){const P=['GET','twofa','twoFactorRedirect','sessionTimeout','cookie','maxAge','audit','session','sessionId','login','Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','public','/api/auth/login','auth','credentials','admin','user:create','Change\x20password','Changes\x20the\x20password\x20for\x20the\x20current\x20user.','user','Terminates\x20the\x20current\x20user\x20session.','destroy','config','Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','query'];z=function(){return P;};return z();}import{UnauthorizedError}from'../../errors.js';function G(w,h){w=w-0xb8;const S=z();let X=S[w];return X;}export function authRoutes(Y){return async v=>{const O=G,D=async o=>{const V=G,q=o['method']===V(0xb8)?o['query']:o['body'],e=X(o),Z=await verifyUser({...q,'ip':e},Y);Z['permissions']=await getUserPermissions(Z['id'],Y);const K=Z[V(0xb9)]?Y['config']['auth'][V(0xba)]:Y['config']['auth']['redirect'];await o['login'](Z);const y=Y['config']['auth'][V(0xbb)]*0x3e8*0x3c;return o['session']?.[V(0xbc)]&&(o['session']['cookie'][V(0xbd)]=y),await o['session']['save'](),await Y[V(0xbe)]?.['write']?.({'module':'auth','resource':V(0xbf),'resourceId':o[V(0xbf)][V(0xc0)],'action':V(0xc1),'userId':Z['id'],'ipAddress':e}),{'user':{'id':Z['id'],'type':Z['type'],'permissions':Z['permissions']},'redirectUrl':K};};v['get']('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':O(0xc2),'access':O(0xc3),'permissions':[],'querystring':authSchemas['credentials']}},D),v['post'](O(0xc4),{'schema':{'tags':['fcore',O(0xc5)],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'body':authSchemas[O(0xc6)]}},D),v['post']('/api/auth/registration',{'schema':{'tags':['fcore','auth'],'summary':'Register','description':'Creates\x20a\x20regular\x20user\x20account.','access':O(0xc7),'permissions':[O(0xc8)],'body':authSchemas[O(0xc6)]}},async o=>h(o['body'],Y)),v['post']('/api/auth/password',{'schema':{'tags':['fcore','auth'],'summary':O(0xc9),'description':O(0xca),'access':'user','permissions':[],'body':authSchemas['password']}},async o=>{const H=O;if(!o['user'])throw new UnauthorizedError('Not\x20authorized');return await S({'userId':o[H(0xcb)]['id'],...o['body']},Y),{'success':!![]};}),v['post']('/api/auth/logout',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':O(0xcc),'access':O(0xcb),'permissions':[]}},async(o,q)=>{const R=O,e={'redirectUrl':'/'};if(!o['user'])return e;return await Y[R(0xbe)]?.['write']?.({'module':R(0xc5),'resource':R(0xbf),'resourceId':o['session'][R(0xc0)],'action':'logout','userId':o['user']?.['id']}),await o['session'][R(0xcd)](),q['clearCookie'](Y[R(0xce)]['auth']['cookieName']),Object['defineProperty'](o,'session',{'value':null,'writable':![],'configurable':![]}),e;}),v['get']('/api/auth/user',{'schema':{'tags':['fcore','auth'],'summary':'Get\x20current\x20user','description':O(0xcf),'access':'user','permissions':[],'querystring':authSchemas['query']}},async o=>{const Q=O;return w({'user':o['user'],'token':o[Q(0xd0)]['token'],'maxAge':o['session']?.['cookie']?.['maxAge'],'originalExpires':o['session']?.['cookie']?.['originalExpires']?.['toISOString']?.()});});};}
@@ -1 +1 @@
1
- function f(){const y=['Optional','String'];f=function(){return y;};return f();}function Y(w,y){w=w-0x1c5;const d=f();let Z=d[w];return Z;}const w=Y;import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type['Object']({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type['Object']({'user':Type['String']({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'id':Type[w(0x1c5)](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type['Object']({'code':Type[w(0x1c6)]({'minLength':0x1})})};
1
+ function z(){const h=['Optional','Object','String'];z=function(){return h;};return z();}const w=G;function G(w,h){w=w-0x1b1;const S=z();let X=S[w];return X;}import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type['Object']({'token':Type[w(0x1b1)](Type['Boolean']())}),'credentials':Type[w(0x1b2)]({'user':Type[w(0x1b3)]({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type[w(0x1b3)]({'minLength':0x1,'maxLength':0x64}),'id':Type['Optional'](Type[w(0x1b3)]({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type['Object']({'code':Type['String']({'minLength':0x1})})};
@@ -1 +1 @@
1
- function Y(w,y){w=w-0x1bd;const d=f();let Z=d[w];return Z;}function f(){const Q=['query','UPDATE\x20admin.users\x0a\x20\x20\x20\x20\x20SET\x20password_hash\x20=\x20$1,\x20updated_at\x20=\x20now(),\x20updated_by\x20=\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20uid\x20=\x20$2'];f=function(){return Q;};return f();}import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:w,password:y,userId:d},{pg:Z}){const H=Y,M=await hashPassword(y);await Z[H(0x1bd)](H(0x1be),[M,w||d,d]);}
1
+ import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:w,password:h,userId:S},{pg:X}){const Y=await hashPassword(h);await X['query']('UPDATE\x20admin.users\x0a\x20\x20\x20\x20\x20SET\x20password_hash\x20=\x20$1,\x20updated_at\x20=\x20now(),\x20updated_by\x20=\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20uid\x20=\x20$2',[Y,w||S,S]);}
@@ -5,5 +5,7 @@ import type { User } from "../../../context.js";
5
5
  export default function getCurrentUser(params: {
6
6
  user: User | undefined;
7
7
  token: boolean | undefined;
8
+ maxAge: number | undefined;
9
+ originalExpires: string | undefined;
8
10
  }): Promise<Record<string, unknown>>;
9
11
  //# sourceMappingURL=get-current-user.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"get-current-user.d.ts","sourceRoot":"","sources":["../../../../src/modules/auth/services/get-current-user.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAEhD,wBAA8B,cAAc,CAAC,MAAM,EAAE;IACnD,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;IACvB,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC;CAC5B,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAenC"}
1
+ {"version":3,"file":"get-current-user.d.ts","sourceRoot":"","sources":["../../../../src/modules/auth/services/get-current-user.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAEhD,wBAA8B,cAAc,CAAC,MAAM,EAAE;IACnD,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;IACvB,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC;IAC3B,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAkBnC"}
@@ -1 +1 @@
1
- function Y(w,y){w=w-0xa9;const d=f();let Z=d[w];return Z;}function f(){const Q=['token','map'];f=function(){return Q;};return f();}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(w){const H=Y,{user:y}=w;if(!y)return{};if(w[H(0xa9)]){const {jwtSignToken:d}=await import('../../../plugins/jwt.js'),Z=await d(y);y['token']=Z;}return y['resources']=[...new Set(y?.['permissions'][H(0xaa)](M=>M['split'](':')[0x0]))],safeUser(y);}
1
+ function z(){const D=['token','permissions','maxAge'];z=function(){return D;};return z();}function G(w,h){w=w-0x1bb;const S=z();let X=S[w];return X;}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(w){const v=G,{user:h}=w;if(!h)return{};if(w[v(0x1bb)]){const {jwtSignToken:S}=await import('../../../plugins/jwt.js'),X=await S(h);h['token']=X;}return h['resources']=[...new Set(h?.[v(0x1bc)]['map'](Y=>Y['split'](':')[0x0]))],{...safeUser(h),'session':{'maxAge':w['maxAge'],'originalExpires':w[v(0x1bd)]}};}
@@ -1 +1 @@
1
- function Y(w,y){w=w-0x164;const d=f();let Z=d[w];return Z;}import{ConflictError}from'../../../errors.js';function f(){const j=['INSERT\x20INTO\x20admin.users\x20(login,\x20password_hash,\x20user_type)\x0a\x20\x20\x20\x20\x20SELECT\x20$1,\x20$2,\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20NOT\x20EXISTS\x20(SELECT\x201\x20FROM\x20admin.users\x20WHERE\x20login\x20=\x20$1)\x0a\x20\x20\x20\x20\x20RETURNING\x20uid\x20AS\x20id,\x20user_type\x20AS\x20type'];f=function(){return j;};return f();}import{hashPassword}from'../../../plugins/auth/index.js';export default async function registration({user:w,password:y,type:d},{pg:Z}){const s=Y,M=await hashPassword(y),H=await Z['query'](s(0x164),[w,M,d||'regular']),Q=H['rows'][0x0];if(!Q)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':Q};}
1
+ import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';function z(){const q=['query','regular'];z=function(){return q;};return z();}function G(w,h){w=w-0x181;const S=z();let X=S[w];return X;}export default async function registration({user:w,password:h,type:S},{pg:X}){const o=G,Y=await hashPassword(h),v=await X[o(0x181)]('INSERT\x20INTO\x20admin.users\x20(login,\x20password_hash,\x20user_type)\x0a\x20\x20\x20\x20\x20SELECT\x20$1,\x20$2,\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20NOT\x20EXISTS\x20(SELECT\x201\x20FROM\x20admin.users\x20WHERE\x20login\x20=\x20$1)\x0a\x20\x20\x20\x20\x20RETURNING\x20uid\x20AS\x20id,\x20user_type\x20AS\x20type',[w,Y,S||o(0x182)]),D=v['rows'][0x0];if(!D)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':D};}
@@ -1 +1 @@
1
- function Y(w,y){w=w-0x7a;var d=f();var Z=d[w];return Z;}import{unsupported}from'../../utils/unsupported.js';function f(){var Z=['Two-factor\x20provider'];f=function(){return Z;};return f();}export default async function verifyTwoFactor(w,y){var d=Y;return unsupported(d(0x7a));}
1
+ function z(){var X=['Two-factor\x20provider'];z=function(){return X;};return z();}function G(w,h){w=w-0xf0;var S=z();var X=S[w];return X;}import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(w,h){var S=G;return unsupported(S(0xf0));}
@@ -1 +1 @@
1
- var w=Y;function Y(w,y){w=w-0xfc;var d=f();var Z=d[w];return Z;}function f(){var y=['image/webp','application/json','application/xml','application/zip','application/x-tar','audio/ogg','audio/webm','video/webm'];f=function(){return y;};return f();}export default new Set(['image/jpeg','image/png','image/gif',w(0xfc),'image/bmp','image/tiff','image/svg+xml','image/x-icon','image/avif','application/pdf','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-powerpoint','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.text','application/vnd.oasis.opendocument.spreadsheet','application/vnd.oasis.opendocument.presentation','text/plain','text/csv','text/markdown',w(0xfd),w(0xfe),'text/xml','application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz',w(0xff),'application/x-zip-compressed','application/x-7z-compressed','application/x-rar-compressed','application/vnd.rar','application/gzip','application/x-gzip',w(0x100),'audio/mpeg','audio/wav',w(0x101),w(0x102),'audio/mp4','video/mp4','video/mpeg',w(0x103),'video/quicktime','video/x-msvideo','application/octet-stream']);
1
+ var w=G;function G(w,h){w=w-0x1f3;var S=z();var X=S[w];return X;}function z(){var h=['image/bmp','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/x-zip-compressed','application/x-rar-compressed','audio/webm','audio/mp4'];z=function(){return h;};return z();}export default new Set(['image/jpeg','image/png','image/gif','image/webp',w(0x1f3),'image/tiff','image/svg+xml','image/x-icon','image/avif','application/pdf','application/msword',w(0x1f4),'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-powerpoint','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.text','application/vnd.oasis.opendocument.spreadsheet','application/vnd.oasis.opendocument.presentation','text/plain','text/csv','text/markdown','application/json','application/xml','text/xml','application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip',w(0x1f5),'application/x-7z-compressed',w(0x1f6),'application/vnd.rar','application/gzip','application/x-gzip','application/x-tar','audio/mpeg','audio/wav','audio/ogg',w(0x1f7),w(0x1f8),'video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo','application/octet-stream']);
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';function f(){const G=['file','public','fileDownloadQuery','token','application/octet-stream','image/','split','pop','header','attachment','inline','public,\x20max-age=86400,\x20immutable','post','File\x20is\x20required','fields','value','get','/api/file/:token/resize','user','fileToken','params','query','Content-Disposition'];f=function(){return G;};return f();}import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';function Y(w,y){w=w-0x169;const d=f();let Z=d[w];return Z;}import{fileSchemas}from'./schema.js';export function fileRoutes(w){return async y=>{const K=Y;y['get']('/api/file/:token',{'schema':{'tags':['fcore',K(0x169)],'summary':'Get\x20file\x20by\x20token','description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':K(0x16a),'permissions':[],'params':fileSchemas['fileToken'],'querystring':fileSchemas[K(0x16b)]}},async(d,Z)=>{const T=K,M=w[T(0x169)]['verify'](d['params'][T(0x16c)]),H=await getFile({'pathOrToken':M},w),Q=await fileTypeFromBuffer(H),s=Q?.['mime']??T(0x16d),j=d['query']['download']===!![],n=s['startsWith'](T(0x16e))||s==='application/pdf',t=M[T(0x16f)]('/')[T(0x170)]()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??'file';return Z['type'](s),Z[T(0x171)]('Content-Disposition',(j||!n?T(0x172):T(0x173))+';\x20filename=\x22'+t+'\x22')[T(0x171)]('Cache-Control',T(0x174)),Z['send'](H);}),y[K(0x175)]('/api/file/upload',{'schema':{'tags':['fcore',K(0x169)],'summary':'Upload\x20file','description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':['files:create']}},async d=>{const h=K,Z=await d['file']();if(!Z)throw new Error(h(0x176));return uploadFile({'file':Z,'metadata':{'name':Z['filename'],'path':Z[h(0x177)]['path']?.['value'],'resource':Z['fields']['resource']?.[h(0x178)],'resourceId':Z[h(0x177)]['resourceId']?.[h(0x178)]},'user':d['user']},w);}),y[K(0x179)](K(0x17a),{'schema':{'tags':['fcore','file'],'summary':'Resize\x20file','description':'Returns\x20a\x20resized\x20image\x20file.','access':K(0x17b),'permissions':['files:read'],'params':fileSchemas[K(0x17c)],'querystring':fileSchemas['resizeQuery']}},async(d,Z)=>{const i=K,M=await resizeFile({'pathOrToken':w[i(0x169)]?.['verify'](d[i(0x17d)]['token']),...d[i(0x17e)]},w),H=await fileTypeFromBuffer(M);return Z['type'](H?.['mime']??'image/png'),Z[i(0x171)](i(0x17f),'inline')[i(0x171)]('Cache-Control','public,\x20max-age=86400,\x20immutable'),Z['send'](M);});};}
1
+ import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';function G(w,h){w=w-0x6a;const S=z();let X=S[w];return X;}import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';function z(){const H=['fcore','Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','fileToken','params','mime','download','startsWith','header','post','Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','fields','file','resizeQuery','Cache-Control'];z=function(){return H;};return z();}export function fileRoutes(w){return async h=>{const K=G;h['get']('/api/file/:token',{'schema':{'tags':[K(0x6a),'file'],'summary':'Get\x20file\x20by\x20token','description':K(0x6b),'access':'public','permissions':[],'params':fileSchemas[K(0x6c)],'querystring':fileSchemas['fileDownloadQuery']}},async(S,X)=>{const y=K,Y=w['file']['verify'](S[y(0x6d)]['token']),v=await getFile({'pathOrToken':Y},w),D=await fileTypeFromBuffer(v),o=D?.[y(0x6e)]??'application/octet-stream',q=S['query'][y(0x6f)]===!![],e=o[y(0x70)]('image/')||o==='application/pdf',Z=Y['split']('/')['pop']()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??'file';return X['type'](o),X['header']('Content-Disposition',(q||!e?'attachment':'inline')+';\x20filename=\x22'+Z+'\x22')[y(0x71)]('Cache-Control','public,\x20max-age=86400,\x20immutable'),X['send'](v);}),h[K(0x72)]('/api/file/upload',{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':K(0x73),'access':'user','permissions':['files:create']}},async S=>{const V=K,X=await S['file']();if(!X)throw new Error('File\x20is\x20required');return uploadFile({'file':X,'metadata':{'name':X['filename'],'path':X['fields']['path']?.['value'],'resource':X['fields']['resource']?.['value'],'resourceId':X[V(0x74)]['resourceId']?.['value']},'user':S['user']},w);}),h['get']('/api/file/:token/resize',{'schema':{'tags':[K(0x6a),K(0x75)],'summary':'Resize\x20file','description':'Returns\x20a\x20resized\x20image\x20file.','access':'user','permissions':['files:read'],'params':fileSchemas[K(0x6c)],'querystring':fileSchemas[K(0x76)]}},async(S,X)=>{const O=K,Y=await resizeFile({'pathOrToken':w['file']?.['verify'](S['params']['token']),...S['query']},w),v=await fileTypeFromBuffer(Y);return X['type'](v?.['mime']??'image/png'),X['header']('Content-Disposition','inline')['header'](O(0x77),'public,\x20max-age=86400,\x20immutable'),X['send'](Y);});};}
@@ -1 +1 @@
1
- function Y(w,y){w=w-0x16b;const d=f();let Z=d[w];return Z;}function f(){const y=['Optional','Boolean','Object','String','contain','fill','Literal'];f=function(){return y;};return f();}const w=Y;import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type['Object']({'id':Type['String']({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type['Object']({'download':Type[w(0x16b)](Type[w(0x16c)]())}),'filePath':Type['Object']({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type[w(0x16d)]({'file':Type['Any'](),'metadata':Type['Object']({'name':Type['Optional'](Type['String']({'minLength':0x1})),'path':Type[w(0x16b)](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type['Optional'](Type[w(0x16e)]({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))}),'resizeQuery':Type['Object']({'width':Type['Optional'](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type['Optional'](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type['Literal']('cover'),Type['Literal'](w(0x16f)),Type['Literal'](w(0x170)),Type[w(0x171)]('inside'),Type['Literal']('outside')]))})};
1
+ const w=G;function G(w,h){w=w-0x14c;const S=z();let X=S[w];return X;}function z(){const h=['String','Object','Optional','Integer','cover','contain','Literal','outside'];z=function(){return h;};return z();}import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type['Object']({'id':Type[w(0x14c)]({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type[w(0x14d)]({'download':Type['Optional'](Type['Boolean']())}),'filePath':Type[w(0x14d)]({'*':Type[w(0x14c)]({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type['Any'](),'metadata':Type['Object']({'name':Type[w(0x14e)](Type['String']({'minLength':0x1})),'path':Type[w(0x14e)](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type[w(0x14c)]({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))}),'resizeQuery':Type[w(0x14d)]({'width':Type['Optional'](Type[w(0x14f)]({'minimum':0x1,'default':0xc8})),'height':Type[w(0x14e)](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type['Literal'](w(0x150)),Type['Literal'](w(0x151)),Type['Literal']('fill'),Type[w(0x152)]('inside'),Type['Literal'](w(0x153))]))})};
@@ -1 +1 @@
1
- import{NotFoundError}from'../../../errors.js';function Y(w,y){w=w-0x191;var d=f();var Z=d[w];return Z;}function f(){var Z=['file'];f=function(){return Z;};return f();}export async function getFile(w,y){var d=Y;if(!y[d(0x191)])throw new Error('empty\x20file');if(!await y['file']['exists'](w['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+w['pathOrToken']);return y['file']['get'](w['pathOrToken']);}
1
+ function z(){var X=['pathOrToken','file','get'];z=function(){return X;};return z();}function G(w,h){w=w-0x10b;var S=z();var X=S[w];return X;}import{NotFoundError}from'../../../errors.js';export async function getFile(w,h){var S=G;if(!h['file'])throw new Error('empty\x20file');if(!await h['file']['exists'](w['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+w[S(0x10b)]);return h[S(0x10c)][S(0x10d)](w['pathOrToken']);}
@@ -1 +1 @@
1
- import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import w from'node:path';import y from'sharp';export async function resizeFile(d,Z){const i=Y,M=d['pathOrToken']??d[i(0x1b8)];if(!M)throw new ValidationError(i(0x1b9));const H=parseDimension(d['width'],'width')??0xc8,Q=parseDimension(d[i(0x1ba)],'height'),s=createHash('sha256')['update'](M+':'+H+':'+(Q??i(0x1bb))+':'+(d['fit']??i(0x1bc)))[i(0x1bd)]('hex'),j=w[i(0x1be)]('logs','resize'),n=w['join'](j,s+i(0x1bf));try{return await readFile(n);}catch(h){if(h['code']!=='ENOENT')throw h;}if(!await Z['file'][i(0x1c0)](M))throw new NotFoundError('File\x20not\x20found');const t=await Z['file']['get'](M),K=await fileTypeFromBuffer(t);if(!K?.['mime']['startsWith']('image/'))throw new ValidationError('Only\x20image\x20files\x20can\x20be\x20resized');const T=await y(t)['resize']({'width':H,'height':Q,'fit':d['fit']??'cover'})[i(0x1c1)]();return await mkdir(j,{'recursive':!![]}),await writeFile(n,T),T;}function Y(w,y){w=w-0x1b8;const d=f();let Z=d[w];return Z;}function parseDimension(d,Z){const G=Y;if(d===undefined||d==='')return undefined;const M=Number(d);if(!Number['isInteger'](M)||M<=0x0)throw new ValidationError(Z+G(0x1c2));return M;}function f(){const U=['path','File\x20path\x20is\x20required','height','auto','cover','digest','resolve','.jpg','exists','toBuffer','\x20must\x20be\x20a\x20positive\x20integer'];f=function(){return U;};return f();}
1
+ import{NotFoundError,ValidationError}from'../../../errors.js';function G(w,h){w=w-0x18e;const S=z();let X=S[w];return X;}import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import w from'node:path';import h from'sharp';function z(){const H=['pathOrToken','path','File\x20path\x20is\x20required','width','update','auto','fit','resolve','code','startsWith','Only\x20image\x20files\x20can\x20be\x20resized','resize'];z=function(){return H;};return z();}export async function resizeFile(S,X){const O=G,Y=S[O(0x18e)]??S[O(0x18f)];if(!Y)throw new ValidationError(O(0x190));const v=parseDimension(S[O(0x191)],O(0x191))??0xc8,D=parseDimension(S['height'],'height'),o=createHash('sha256')[O(0x192)](Y+':'+v+':'+(D??O(0x193))+':'+(S[O(0x194)]??'cover'))['digest']('hex'),q=w[O(0x195)]('logs','resize'),e=w['join'](q,o+'.jpg');try{return await readFile(e);}catch(V){if(V[O(0x196)]!=='ENOENT')throw V;}if(!await X['file']['exists'](Y))throw new NotFoundError('File\x20not\x20found');const Z=await X['file']['get'](Y),K=await fileTypeFromBuffer(Z);if(!K?.['mime'][O(0x197)]('image/'))throw new ValidationError(O(0x198));const y=await h(Z)[O(0x199)]({'width':v,'height':D,'fit':S['fit']??'cover'})['toBuffer']();return await mkdir(q,{'recursive':!![]}),await writeFile(e,y),y;}function parseDimension(S,X){if(S===undefined||S==='')return undefined;const Y=Number(S);if(!Number['isInteger'](Y)||Y<=0x0)throw new ValidationError(X+'\x20must\x20be\x20a\x20positive\x20integer');return Y;}
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';import w from'../mime.js';import{randomUUID}from'node:crypto';import{ValidationError}from'../../../errors.js';function Y(w,y){w=w-0x89;const d=f();let Z=d[w];return Z;}export async function uploadFile(y,d){const i=Y,Z=(y['metadata']['name']??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),M=new Date(),H=String(M['getFullYear']())['slice'](-0x2),Q=String(M[i(0x89)]()+0x1)[i(0x8a)](0x2,'0'),s=String(M[i(0x8b)]())['padStart'](0x2,'0'),j=y['metadata']['path']??(y['metadata']['resource']?y[i(0x8c)]['resource']+'/'+(y['metadata']['resourceId']??randomUUID())+'/'+Z:null)??i(0x8d)+H+'/'+Q+'-'+s+'/'+Z,n=await y['file'][i(0x8e)](),t=await fileTypeFromBuffer(n);if(!w['has'](y['file'][i(0x8f)])&&(t?.['mime']?!w['has'](t['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+y['file']['mimetype']);const K=Boolean(y['metadata']['resource']&&y['metadata'][i(0x90)]);if(K){const h=await d['pg']['query']('SELECT\x20file_id\x20FROM\x20admin.files\x0a\x20\x20\x20\x20\x20\x20\x20WHERE\x20resource\x20=\x20$1\x20AND\x20resource_id\x20=\x20$2\x20AND\x20file_name\x20=\x20$3\x0a\x20\x20\x20\x20\x20\x20\x20LIMIT\x201',[y['metadata']['resource'],String(y['metadata'][i(0x90)]),Z]);if((h['rowCount']??0x0)>0x0)throw new ValidationError('File\x20with\x20name\x20\x22'+Z+i(0x91)+y[i(0x8c)][i(0x92)]+'\x22\x20and\x20id\x20\x22'+y[i(0x8c)][i(0x90)]+'\x22');}await d['file'][i(0x93)](j,n);const T=await d['pg'][i(0x94)]('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,\x20uploaded_name,\x20file_name,\x20ext,\x20status,\x20created_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$5,\x20$6,\x20$7,\x20$8,\x20$9,\x20$10)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[y[i(0x8c)]['resource']??null,y[i(0x8c)]['resourceId']??null,j,y['file'][i(0x8f)],y['file'][i(0x95)][i(0x96)],y['metadata']['name'],Z,y[i(0x95)]['mimetype'][i(0x97)]('/')['pop']()??null,K?'attached':'pending',y['user']?.['id']??null]);return{...T[i(0x98)][0x0],'token':d['file']['create'](j)};}function f(){const G=['getMonth','padStart','getDate','metadata','uploads/','toBuffer','mimetype','resourceId','\x22\x20already\x20exists\x20for\x20resource\x20\x22','resource','put','query','file','bytesRead','split','rows'];f=function(){return G;};return f();}
1
+ import{fileTypeFromBuffer}from'file-type';function G(w,h){w=w-0x1da;const S=z();let X=S[w];return X;}import w from'../mime.js';import{randomUUID}from'node:crypto';function z(){const H=['getFullYear','metadata','resourceId','has','put','mimetype','pop','user'];z=function(){return H;};return z();}import{ValidationError}from'../../../errors.js';export async function uploadFile(h,S){const O=G,X=(h['metadata']['name']??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),Y=new Date(),v=String(Y[O(0x1da)]())['slice'](-0x2),D=String(Y['getMonth']()+0x1)['padStart'](0x2,'0'),o=String(Y['getDate']())['padStart'](0x2,'0'),q=h['metadata']['path']??(h[O(0x1db)]['resource']?h['metadata']['resource']+'/'+(h['metadata'][O(0x1dc)]??randomUUID())+'/'+X:null)??'uploads/'+v+'/'+D+'-'+o+'/'+X,e=await h['file']['toBuffer'](),Z=await fileTypeFromBuffer(e);if(!w[O(0x1dd)](h['file']['mimetype'])&&(Z?.['mime']?!w['has'](Z['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+h['file']['mimetype']);const K=Boolean(h['metadata']['resource']&&h['metadata']['resourceId']);if(K){const V=await S['pg']['query']('SELECT\x20file_id\x20FROM\x20admin.files\x0a\x20\x20\x20\x20\x20\x20\x20WHERE\x20resource\x20=\x20$1\x20AND\x20resource_id\x20=\x20$2\x20AND\x20file_name\x20=\x20$3\x0a\x20\x20\x20\x20\x20\x20\x20LIMIT\x201',[h[O(0x1db)]['resource'],String(h[O(0x1db)]['resourceId']),X]);if((V['rowCount']??0x0)>0x0)throw new ValidationError('File\x20with\x20name\x20\x22'+X+'\x22\x20already\x20exists\x20for\x20resource\x20\x22'+h['metadata']['resource']+'\x22\x20and\x20id\x20\x22'+h['metadata']['resourceId']+'\x22');}await S['file'][O(0x1de)](q,e);const y=await S['pg']['query']('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,\x20uploaded_name,\x20file_name,\x20ext,\x20status,\x20created_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$5,\x20$6,\x20$7,\x20$8,\x20$9,\x20$10)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[h[O(0x1db)]['resource']??null,h[O(0x1db)]['resourceId']??null,q,h['file']['mimetype'],h['file']['file']['bytesRead'],h[O(0x1db)]['name'],X,h['file'][O(0x1df)]['split']('/')[O(0x1e0)]()??null,K?'attached':'pending',h[O(0x1e1)]?.['id']??null]);return{...y['rows'][0x0],'token':S['file']['create'](q)};}