@opengis/fcore 0.0.1-beta.17 → 0.0.1-beta.19
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/LICENSE +3 -3
- package/README.md +71 -71
- package/dist/config.js +1 -1
- package/dist/context.js +1 -1
- package/dist/errors.js +1 -1
- package/dist/fastify.d.ts.map +1 -1
- package/dist/fastify.js +1 -1
- package/dist/fcore.js +1 -1
- package/dist/migrations/cli.js +1 -1
- package/dist/migrations/runner.js +1 -1
- package/dist/modules/auth/adduser-cli.js +1 -1
- package/dist/modules/auth/passwd-cli.js +1 -1
- package/dist/modules/auth/permission-cli.js +1 -1
- package/dist/modules/auth/route.js +1 -1
- package/dist/modules/auth/schema.js +1 -1
- package/dist/modules/auth/services/change-password.js +1 -1
- package/dist/modules/auth/services/get-current-user.js +1 -1
- package/dist/modules/auth/services/registration.js +1 -1
- package/dist/modules/auth/services/verify-two-factor.js +1 -1
- package/dist/modules/file/mime.js +1 -1
- package/dist/modules/file/route.js +1 -1
- package/dist/modules/file/schema.js +1 -1
- package/dist/modules/file/services/get-file.js +1 -1
- package/dist/modules/file/services/resize-file.js +1 -1
- package/dist/modules/file/services/upload-file.js +1 -1
- package/dist/modules/resource/route.js +1 -1
- package/dist/modules/resource/schema.js +1 -1
- package/dist/modules/resource/services/add-note.js +1 -1
- package/dist/modules/resource/services/add-resource-file.js +1 -1
- package/dist/modules/resource/services/create-resource-relation.js +1 -1
- package/dist/modules/resource/services/create-resource.js +1 -1
- package/dist/modules/resource/services/delete-resource-relation.js +1 -1
- package/dist/modules/resource/services/delete-resource.js +1 -1
- package/dist/modules/resource/services/export-resource.js +1 -1
- package/dist/modules/resource/services/get-resource.js +1 -1
- package/dist/modules/resource/services/list-resource-relation.js +1 -1
- package/dist/modules/resource/services/list-resources.js +1 -1
- package/dist/modules/resource/services/search-resource.js +1 -1
- package/dist/modules/resource/services/suggest-resource.js +1 -1
- package/dist/modules/resource/services/update-resource-relation.js +1 -1
- package/dist/modules/resource/services/update-resource.js +1 -1
- package/dist/modules/resource/services/upload-resource-file.js +1 -1
- package/dist/modules/system/route.js +1 -1
- package/dist/modules/system/schema.d.ts +3 -2
- package/dist/modules/system/schema.d.ts.map +1 -1
- package/dist/modules/system/schema.js +1 -1
- package/dist/modules/system/services/check-system.js +1 -1
- package/dist/modules/system/services/get-access.d.ts +1 -0
- package/dist/modules/system/services/get-access.d.ts.map +1 -1
- package/dist/modules/system/services/get-access.js +1 -1
- package/dist/modules/system/services/get-api-list.js +1 -1
- package/dist/modules/system/services/get-audit-log.js +1 -1
- package/dist/modules/system/services/get-dictionary.js +1 -1
- package/dist/modules/system/services/get-system-log.js +1 -1
- package/dist/modules/system/services/get-system-settings.js +1 -1
- package/dist/modules/system/services/list-dictionaries.js +1 -1
- package/dist/modules/system/services/set-access.d.ts +2 -1
- package/dist/modules/system/services/set-access.d.ts.map +1 -1
- package/dist/modules/system/services/set-access.js +1 -1
- package/dist/modules/system/services/update-dictionary.js +1 -1
- package/dist/modules/system/services/update-system-settings.js +1 -1
- package/dist/modules/utils/require-admin.js +1 -1
- package/dist/modules/utils/safe-user.js +1 -1
- package/dist/modules/utils/unsupported.js +1 -1
- package/dist/plugins/audit/audit.js +1 -1
- package/dist/plugins/audit/audit.types.d.ts +1 -1
- package/dist/plugins/audit/audit.types.d.ts.map +1 -1
- package/dist/plugins/audit/services/write-audit.js +1 -1
- package/dist/plugins/auth/get-user-permissions.js +1 -1
- package/dist/plugins/auth/index.js +1 -1
- package/dist/plugins/auth/verifyUser.js +1 -1
- package/dist/plugins/dictionary.js +1 -1
- package/dist/plugins/file.js +1 -1
- package/dist/plugins/jwt.js +1 -1
- package/dist/plugins/logger/index.js +1 -1
- package/dist/plugins/logger/transport.js +1 -1
- package/dist/plugins/pg.js +1 -1
- package/dist/plugins/redis.js +1 -1
- package/dist/plugins/resource/resource.js +1 -1
- package/dist/plugins/resource/resource.registry.js +1 -1
- package/dist/plugins/resource/resource.types.d.ts +3 -4
- package/dist/plugins/resource/resource.types.d.ts.map +1 -1
- package/dist/plugins/resource/services/add-dictionary-lookup-data.js +1 -1
- package/dist/plugins/resource/services/add-file-token.js +1 -1
- package/dist/plugins/resource/services/add-table-lookup-data.js +1 -1
- package/dist/plugins/resource/services/create-relation.js +1 -1
- package/dist/plugins/resource/services/create.js +1 -1
- package/dist/plugins/resource/services/delete-relation.js +1 -1
- package/dist/plugins/resource/services/delete.d.ts.map +1 -1
- package/dist/plugins/resource/services/delete.js +1 -1
- package/dist/plugins/resource/services/find-one.d.ts.map +1 -1
- package/dist/plugins/resource/services/find-one.js +1 -1
- package/dist/plugins/resource/services/find-relation.d.ts.map +1 -1
- package/dist/plugins/resource/services/find-relation.js +1 -1
- package/dist/plugins/resource/services/find.d.ts.map +1 -1
- package/dist/plugins/resource/services/find.js +1 -1
- package/dist/plugins/resource/services/update-relation.js +1 -1
- package/dist/plugins/resource/services/update.d.ts.map +1 -1
- package/dist/plugins/resource/services/update.js +1 -1
- package/dist/plugins/resource/utils/auto-index.js +1 -1
- package/dist/plugins/resource/utils/fields.js +1 -1
- package/dist/plugins/resource/utils/filters.js +1 -1
- package/dist/plugins/resource/utils/permissions.js +1 -1
- package/dist/plugins/resource/utils/sort.d.ts +1 -1
- package/dist/plugins/resource/utils/sort.d.ts.map +1 -1
- package/dist/plugins/resource/utils/sort.js +1 -1
- package/dist/plugins/resource/utils/sql.js +1 -1
- package/dist/shared/getIP.js +1 -1
- package/migrations/20260903130000_move_notes_files_to_admin.sql +17 -17
- package/migrations/20260903140000_settings_nulls_not_distinct.sql +18 -18
- package/migrations/20260905120000_add_user_foreign_keys.sql +42 -42
- package/package.json +1 -1
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
|
-
import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function
|
|
1
|
+
import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(L){const t=O,E=process.env[L];if(!E)throw new Error(t(0x77)+L);return E;}function Z(){const B=['Missing\x20environment\x20variable:\x20','split','false','parse','strict','none','auth'];Z=function(){return B;};return Z();}function O(L,E){L=L-0x77;const c=Z();let t=c[L];return t;}export function loadConfig(L={}){const e=O,E={'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==='false','max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storagePath':process.env.STORAGE_PATH??'./storage','redactionList':(process.env.REDACTION_LIST||'password')[e(0x78)](','),'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'](c=>c-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!==e(0x79),'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[e(0x7a)](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',e(0x7b),e(0x7c)]['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{...E,...L,'logger':{...E['logger'],...L['logger']},'pg':{...E['pg'],...L['pg']},'redis':{...E['redis'],...L['redis']},'s3':{...E['s3'],...L['s3']},'auth':{...E[e(0x7d)],...L['auth']}};}export{required as requireEnv};
|
package/dist/context.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
let defaultContext;export function setContext(L){defaultContext=L;}function Z(){const t=['Application\x20context\x20is\x20not\x20initialized','redis','end'];Z=function(){return t;};return Z();}export function getContext(){const E=O;if(!defaultContext)throw new Error(E(0x145));return defaultContext;}function O(L,E){L=L-0x145;const c=Z();let t=c[L];return t;}export function createContext(L){return{...L,async 'close'(){const c=O;await Promise['allSettled']([L[c(0x146)]?.['close'](),L['pg']?.[c(0x147)]()]),await L['logger']['close']();}};}
|
package/dist/errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var e=O;function Z(){var X=['details','statusCode','BAD_REQUEST_ERROR','Authentication\x20required','NOT_FOUND'];Z=function(){return X;};return Z();}export class FCoreError extends Error{['code'];['statusCode'];[e(0xdc)];constructor(L,E,c=0x1f4,t){var B=e;super(E),this['code']=L,this[B(0xdd)]=c,this['details']=t,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(L,E){var g=e;super(g(0xde),L,0x190,E);}}export class UnauthorizedError extends FCoreError{constructor(L=e(0xdf)){super('UNAUTHORIZED',L,0x191);}}function O(L,E){L=L-0xdc;var c=Z();var t=c[L];return t;}export class ForbiddenError extends FCoreError{constructor(L='Access\x20denied'){super('FORBIDDEN',L,0x193);}}export class NotFoundError extends FCoreError{constructor(L='Not\x20found'){var r=e;super(r(0xe0),L,0x194);}}export class ConflictError extends FCoreError{constructor(L='Conflict'){super('CONFLICT',L,0x199);}}export class ValidationError extends FCoreError{constructor(L,E){super('VALIDATION_ERROR',L,0x1a6,E);}}export class UnsupportedError extends FCoreError{constructor(L='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',L,0x1f5);}}
|
package/dist/fastify.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../src/fastify.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAY/C,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,UAAU,GAAG,MAAM,GAAG,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../src/fastify.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAY/C,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,UAAU,GAAG,MAAM,GAAG,QAAQ,CAAC;AAYrE,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAG,EAAE,UAAU,EACf,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,GAClC,kBAAkB,CAwIpB"}
|
package/dist/fastify.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import L from'fastify-plugin';import{FCoreError}from'./errors.js';function Z(){const q=['reduce','ctx','method','fcore','public','set','url','addHook','routeOptions','raw','headers','authorization','Bearer\x20','user','auth','access','length','admin','permissions','includes','@fastify/multipart','FST_ERR_VALIDATION','logger','send','code','details','error','debug','test','register','resource','file','rateLimit','disabled','@fastify/rate-limit'];Z=function(){return q;};return Z();}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';function O(L,E){L=L-0x106;const c=Z();let t=c[L];return t;}import{ForbiddenError}from'./errors.js';import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(E,c,t){const f=O,e=decodeURIComponent(c['toString']())['split']('&')[f(0x106)]((B,g)=>{const [r,X]=g['split']('=');return{...B,[r]:X};},{});t(null,e);}export default function fcoreFastify(E,c){return L(async t=>{const A=O;t['decorate'](A(0x107),E);const {config:e}=E,B=new Map();t['addHook']('onRoute',r=>{const G=A,X=r['schema'],j=Array['isArray'](r['method'])?r[G(0x108)]:[r[G(0x108)]];for(const F of j){if(F==='HEAD')continue;const I={'method':F,'endpoint':r['url'],'package':X?.['package']??G(0x109),'tags':X?.['tags']??[],'summary':X?.['summary']??'','description':X?.['description']??'','access':X?.['access']??G(0x10a),'permissions':X?.['permissions']??[]};B[G(0x10b)](F+'\x20'+r[G(0x10c)],I);}}),t[A(0x10d)]('preHandler',async r=>{const x=A;if(r['routeOptions']['url']==='*')return!![];const X=B['get'](r['method']+'\x20'+r[x(0x10e)][x(0x10c)]),j=r[x(0x10f)][x(0x110)]?.[x(0x111)],F=j?.['startsWith'](x(0x112))?j['slice'](0x7):null,I=r[x(0x113)]??(F?await jwtVerifyToken(F):null);!r[x(0x113)]&&F&&process.env.AUTH_JWT_SECRET&&(r['user']=await jwtVerifyToken(F));!r['user']&&process['platform']==='win32'&&E['config']?.[x(0x114)]?.['user']&&(r[x(0x113)]=E['config']['auth']['user']);if(!X?.['access'])throw new Error('Route\x20access\x20not\x20defined');if(X[x(0x115)]==='public')return!![];if(!I)throw new ForbiddenError('User\x20required');if(X['access']==='user'&&!X['permissions']?.[x(0x116)])return!![];if(I['type']==x(0x117))return!![];if(X['access']==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const T of X[x(0x118)]){if(!I['permissions']?.[x(0x119)](T))throw new ForbiddenError('Missing\x20permission:\x20'+T);}return!![];}),await createSessionStore(t,E),await t['register'](import(A(0x11a)),{'limits':{'fileSize':e['maxFileSize']*0x400*0x400}}),t['setErrorHandler']((r,X,j)=>{const W=A;if(r instanceof FCoreError||r['code']===W(0x11b)||r['statusCode']<0x1f4)return r['statusCode']<0x1f4&&E[W(0x11c)]['warn'](r),j['code'](r['statusCode'])[W(0x11d)]({'error':r[W(0x11e)],'message':r['message'],'details':r[W(0x11f)]});return E['logger'][W(0x120)](r),(e[W(0x121)]||process.env.NODE_ENV===W(0x122)||process.env.VITEST)&&console[W(0x120)](r),j['code'](0x1f4)['send']({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const g=r=>!c||c[A(0x119)](r);if(g('auth'))await t[A(0x123)](authRoutes(E));if(g(A(0x124)))await t['register'](resourceRoutes(E));if(g(A(0x125)))await t[A(0x123)](fileRoutes(E));if(g('system'))await t['register'](systemRoutes(E,B));t['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':'buffer'},urlencodedContentParser),!e[A(0x126)]?.[A(0x127)]?t['register'](import(A(0x128)),{'max':e[A(0x126)]?.['max']||0x64,'timeWindow':e[A(0x126)]?.['timeWindow']||0xea60,'hook':'preHandler','global':!![],'keyGenerator':r=>(r['user']?.['id']||r['ip'])+'-'+r[A(0x10f)][A(0x10c)]['split']('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');});}
|
package/dist/fcore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';import{createAudit,createDatabase,createDictionary,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function Z(){const I=['redis','endpoint','accessKey'];Z=function(){return I;};return Z();}function O(L,E){L=L-0xfe;const c=Z();let t=c[L];return t;}export async function createFCore(L={}){const F=O,E=loadConfig(L['config']),c=createRedis(E[F(0xfe)]),t=createLogger(),e=createDatabase(E['pg']),B=createFileS3({'endpoint':E['s3'][F(0xff)],'region':E['s3']['region'],'bucket':E['s3']['bucket'],'accessKey':E['s3'][F(0x100)],'secretKey':E['s3']['secretKey'],'folder':E['s3']['folder'],'forcePathStyle':E['s3']['forcePathStyle'],'tokenSecret':E['s3']['tokenSecret'],'tokenTtl':E['s3']['tokenTtl']}),g=createAudit({'pg':e,'logger':t}),r=createDictionary({'pg':e,'dictionaries':L['dictionaries']}),X=createResource({'pg':e,'logger':t,'audit':g,'dictionary':r,'file':B});L['resources']?.['length']&&X['register'](L['resources']);const j=createContext({'config':E,'logger':t,'redis':c,'pg':e,'file':B,'resource':X,'audit':g,'dictionary':r});return setContext(j),j;}
|
package/dist/migrations/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
2
|
+
function Z(){const F=['--dir','--dir\x20requires\x20a\x20folder\x20path','--fcore','slice','****'];Z=function(){return F;};return Z();}const j=O;import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';import L from'node:path';import{fileURLToPath}from'node:url';function O(L,E){L=L-0x136;const c=Z();let t=c[L];return t;}const packageMigrations=fileURLToPath(new URL('../../migrations',import.meta.url));function migrationDirectory(E){const X=O,c=E['indexOf'](X(0x136));if(c>=0x0){const e=E[c+0x1];if(!e)throw new Error(X(0x137));return L['resolve'](e);}if(E['includes'](X(0x138)))return packageMigrations;const t=E['find'](B=>!B['startsWith']('--'));return L['resolve'](t??'migrations');}try{const config=loadConfig(),dir=migrationDirectory(process['argv'][j(0x139)](0x2));console['log']('Loaded\x20configuration:',{...config['pg'],'user':'****','password':j(0x13a)}),console['log']('Using\x20migration\x20directory:',dir,process['argv']['slice'](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console['log']((r['status']==='run'?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(g){console['error'](g),process['exitCode']=0x1;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import L from'node:fs/promises';function O(L,E){L=L-0x10d;const c=Z();let t=c[L];return t;}import E from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(c={}){const A=O,t=E['resolve'](c['dir']??'migrations'),e=c['database']??databaseFromUrl(c['databaseUrl']??process.env.DATABASE_URL);if(!e)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const B=createDatabase(e);if(!B)throw new Error(A(0x10d));const g=[];try{await B['query'](A(0x10e));const r=await B['query'](A(0x10f)),X=new Set(r[A(0x110)]['map'](F=>F['version'])),j=(await L['readdir'](t))[A(0x111)](F=>F['endsWith']('.sql'))[A(0x112)]();for(const F of j){if(X['has'](F)){g['push']({'file':F,'status':A(0x113)});continue;}const I=await L['readFile'](E['join'](t,F),A(0x114)),T=await B[A(0x115)]();try{await T['query']('BEGIN'),await T['query'](I),await T[A(0x116)]('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[F]),await T['query']('COMMIT');}catch(f){await T['query']('ROLLBACK');throw f;}finally{T[A(0x117)]();}g['push']({'file':F,'status':A(0x118)});}return g;}finally{await B['end']();}}function Z(){const x=['empty\x20pg','\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','SELECT\x20version\x20FROM\x20schema_migrations','rows','filter','sort','skip','utf8','connect','query','release','run','hostname'];Z=function(){return x;};return Z();}function databaseFromUrl(c){const G=O;if(!c)return undefined;const t=new URL(c);return{'host':t[G(0x119)],'port':Number(t['port']||0x1538),'database':t['pathname']['slice'](0x1),'user':decodeURIComponent(t['username']),'password':decodeURIComponent(t['password'])};}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
2
|
+
const c=O;function O(L,E){L=L-0x16a;const c=Z();let t=c[L];return t;}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import L from'./services/registration.js';const [user,password,type]=process['argv']['slice'](0x2);function Z(){const t=['log','Registered\x20user\x20','exitCode','end'];Z=function(){return t;};return Z();}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 L({'user':user,'password':password,'type':type},{'pg':pg});console[c(0x16a)](c(0x16b)+data['id']+'\x20('+data['type']+')');}catch(E){console['error'](E),process[c(0x16c)]=0x1;}finally{await pg[c(0x16d)]();}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
2
|
+
const c=O;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function Z(){const t=['slice','query','rows'];Z=function(){return t;};return Z();}import L from'./services/change-password.js';const [login,password]=process['argv'][c(0x7d)](0x2);function O(L,E){L=L-0x7d;const c=Z();let t=c[L];return t;}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[c(0x7e)]('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result[c(0x7f)][0x0];if(!user)throw new Error('User\x20not\x20found');await L({'userId':user['id'],'password':password},{'pg':pg}),console['log']('Password\x20changed\x20for\x20'+login);}catch(E){console['error'](E),process['exitCode']=0x1;}finally{await pg['end']();}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
const X=O;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=['logs','audit','list','check','access',X(0xa6),X(0xa7)],RESOURCE_ACTIONS=['read',X(0xa8),'create',X(0xa9)],[login,permissionArg]=process[X(0xaa)]['slice'](0x2);function O(L,E){L=L-0xa6;const c=Z();let t=c[L];return t;}function expandPermissions(L){const j=X,E=L['split'](',')[j(0xab)](t=>t['trim']())[j(0xac)](Boolean),c=new Set();for(const t of E){if(t['includes'](':')){c['add'](t);continue;}const e=t==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const B of e){c[j(0xad)](t+':'+B);}}return[...c];}function Z(){const F=['settings','dictionaries','update','delete','argv','map','filter','add','exitCode','Permissions\x20cleared\x20for\x20','get','connect','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','Granted\x20permissions\x20for\x20','join','error','end'];Z=function(){return F;};return Z();}if(!login||!permissionArg)console['error']('Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>'),process[X(0xae)]=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('User\x20not\x20found');if(permissionArg['trim']()==='clear')await pg['query']('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console['log'](X(0xaf)+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource[X(0xb0)](resource)??[];actions['push'](action),byResource['set'](resource,actions);}const client=await pg[X(0xb1)]();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['actions']??[],...actions])];await client['query'](X(0xb2),[merged,user['id'],row['access_id']]);}else await client['query']('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)',[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(g){await client['query']('ROLLBACK');throw g;}finally{client['release']();}console['log'](X(0xb3)+login+':\x20'+permissions[X(0xb4)](',\x20'));}}catch(r){console[X(0xb5)](r),process['exitCode']=0x1;}finally{await pg[X(0xb6)]();}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import L from'./services/get-current-user.js';import E from'./services/registration.js';import c from'./services/change-password.js';function O(L,E){L=L-0xcb;const c=Z();let t=c[L];return t;}function Z(){const x=['body','twofa','twoFactorRedirect','auth','config','sessionTimeout','session','type','fcore','public','credentials','post','Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','Creates\x20a\x20regular\x20user\x20account.','clearCookie','get','Get\x20current\x20user','query','token'];Z=function(){return x;};return Z();}import{authSchemas}from'./schema.js';import t from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(e){return async B=>{const A=O,g=async r=>{const f=O,X=r['method']==='GET'?r['query']:r[f(0xcb)],j=t(r),F=await verifyUser({...X,'ip':j},e);F['permissions']=await getUserPermissions(F['id'],e);const I=F[f(0xcc)]?e['config']['auth'][f(0xcd)]:e['config'][f(0xce)]['redirect'];await r['login'](F);const T=e[f(0xcf)]['auth'][f(0xd0)]*0x3e8*0x3c;return r['session']?.['cookie']&&(r[f(0xd1)]['cookie']['maxAge']=T),await r['session']['save'](),await e['audit']?.['write']?.({'module':'auth','resource':'session','resourceId':r[f(0xd1)]['sessionId'],'action':'login','userId':F['id'],'ipAddress':j}),{'user':{'id':F['id'],'type':F[f(0xd2)],'permissions':F['permissions']},'redirectUrl':I};};B['get']('/api/auth/login',{'schema':{'tags':[A(0xd3),'auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':A(0xd4),'permissions':[],'querystring':authSchemas[A(0xd5)]}},g),B[A(0xd6)]('/api/auth/login',{'schema':{'tags':['fcore',A(0xce)],'summary':'Sign\x20in','description':A(0xd7),'access':'public','permissions':[],'body':authSchemas['credentials']}},g),B[A(0xd6)]('/api/auth/registration',{'schema':{'tags':['fcore','auth'],'summary':'Register','description':A(0xd8),'access':'admin','permissions':['user:create'],'body':authSchemas[A(0xd5)]}},async r=>E(r['body'],e)),B['post']('/api/auth/password',{'schema':{'tags':['fcore','auth'],'summary':'Change\x20password','description':'Changes\x20the\x20password\x20for\x20the\x20current\x20user.','access':'user','permissions':[],'body':authSchemas['password']}},async r=>{if(!r['user'])throw new UnauthorizedError('Not\x20authorized');return await c({'userId':r['user']['id'],...r['body']},e),{'success':!![]};}),B[A(0xd6)]('/api/auth/logout',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':'Terminates\x20the\x20current\x20user\x20session.','access':'user','permissions':[]}},async(r,X)=>{const G=A,j={'redirectUrl':'/'};if(!r['user'])return j;return await e['audit']?.['write']?.({'module':'auth','resource':'session','resourceId':r['session']['sessionId'],'action':'logout','userId':r['user']?.['id']}),await r['session']['destroy'](),X[G(0xd9)](e['config']['auth']['cookieName']),Object['defineProperty'](r,'session',{'value':null,'writable':![],'configurable':![]}),j;}),B[A(0xda)]('/api/auth/user',{'schema':{'tags':['fcore','auth'],'summary':A(0xdb),'description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas[A(0xdc)]}},async r=>L({'user':r['user'],'token':r['query'][A(0xdd)]}));};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const L=O;function Z(){const E=['Object','Optional','String'];Z=function(){return E;};return Z();}function O(L,E){L=L-0x192;const c=Z();let t=c[L];return t;}import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type[L(0x192)]({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type['Object']({'user':Type['String']({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type[L(0x193)](Type[L(0x194)]({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'id':Type[L(0x193)](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type[L(0x192)]({'code':Type['String']({'minLength':0x1})})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hashPassword}from'../../../plugins/auth/index.js';
|
|
1
|
+
function O(L,E){L=L-0xfa;const c=Z();let t=c[L];return t;}import{hashPassword}from'../../../plugins/auth/index.js';function Z(){const g=['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'];Z=function(){return g;};return Z();}export default async function changePassword({id:L,password:E,userId:c},{pg:t}){const B=O,e=await hashPassword(E);await t['query'](B(0xfa),[e,L||c,c]);}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function O(L,E){L=L-0xcc;const c=Z();let t=c[L];return t;}function Z(){const g=['token','../../../plugins/jwt.js','permissions','map'];Z=function(){return g;};return Z();}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(L){const B=O,{user:E}=L;if(!E)return{};if(L[B(0xcc)]){const {jwtSignToken:c}=await import(B(0xcd)),t=await c(E);E['token']=t;}return E['resources']=[...new Set(E?.[B(0xce)][B(0xcf)](e=>e['split'](':')[0x0]))],safeUser(E);}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ConflictError}from'../../../errors.js';
|
|
1
|
+
import{ConflictError}from'../../../errors.js';function Z(){const X=['query','Login\x20is\x20already\x20in\x20use'];Z=function(){return X;};return Z();}function O(L,E){L=L-0x17b;const c=Z();let t=c[L];return t;}import{hashPassword}from'../../../plugins/auth/index.js';export default async function registration({user:L,password:E,type:c},{pg:t}){const r=O,e=await hashPassword(E),B=await t[r(0x17b)]('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',[L,e,c||'regular']),g=B['rows'][0x0];if(!g)throw new ConflictError(r(0x17c));return{'user':g};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(
|
|
1
|
+
import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(L,E){return unsupported('Two-factor\x20provider');}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=O;function O(L,E){L=L-0x93;var c=Z();var t=c[L];return t;}export default new Set(['image/jpeg',L(0x93),L(0x94),'image/webp',L(0x95),L(0x96),'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',L(0x97),'application/vnd.oasis.opendocument.text','application/vnd.oasis.opendocument.spreadsheet',L(0x98),'text/plain',L(0x99),L(0x9a),L(0x9b),'application/xml',L(0x9c),L(0x9d),'application/vnd.google-earth.kml+xml',L(0x9e),'application/zip',L(0x9f),'application/x-7z-compressed',L(0xa0),'application/vnd.rar','application/gzip','application/x-gzip','application/x-tar','audio/mpeg','audio/wav',L(0xa1),L(0xa2),'audio/mp4','video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo','application/octet-stream']);function Z(){var E=['image/png','image/gif','image/bmp','image/tiff','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.presentation','text/csv','text/markdown','application/json','text/xml','application/geo+json','application/vnd.google-earth.kmz','application/x-zip-compressed','application/x-rar-compressed','audio/ogg','audio/webm'];Z=function(){return E;};return Z();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fileTypeFromBuffer}from'file-type';function
|
|
1
|
+
import{fileTypeFromBuffer}from'file-type';function O(L,E){L=L-0xf9;const c=Z();let t=c[L];return t;}import{getFile}from'./services/get-file.js';function Z(){const G=['get','fcore','file','Get\x20file\x20by\x20token','Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','public','fileToken','fileDownloadQuery','query','pop','Cache-Control','post','user','File\x20is\x20required','fields','Returns\x20a\x20resized\x20image\x20file.','params','token','public,\x20max-age=86400,\x20immutable','send'];Z=function(){return G;};return Z();}import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';export function fileRoutes(L){return async E=>{const I=O;E[I(0xf9)]('/api/file/:token',{'schema':{'tags':[I(0xfa),I(0xfb)],'summary':I(0xfc),'description':I(0xfd),'access':I(0xfe),'permissions':[],'params':fileSchemas[I(0xff)],'querystring':fileSchemas[I(0x100)]}},async(c,t)=>{const T=I,e=L[T(0xfb)]['verify'](c['params']['token']),B=await getFile({'pathOrToken':e},L),g=await fileTypeFromBuffer(B),r=g?.['mime']??'application/octet-stream',X=c[T(0x101)]['download']===!![],j=r['startsWith']('image/')||r==='application/pdf',F=e['split']('/')[T(0x102)]()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??T(0xfb);return t['type'](r),t['header']('Content-Disposition',(X||!j?'attachment':'inline')+';\x20filename=\x22'+F+'\x22')['header'](T(0x103),'public,\x20max-age=86400,\x20immutable'),t['send'](B);}),E[I(0x104)]('/api/file/upload',{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':I(0x105),'permissions':['files:create']}},async c=>{const f=I,t=await c['file']();if(!t)throw new Error(f(0x106));return uploadFile({'file':t,'metadata':{'name':t['filename'],'path':t[f(0x107)]['path']?.['value'],'resource':t['fields']['resource']?.['value'],'resourceId':t['fields']['resourceId']?.['value']},'user':c['user']},L);}),E['get']('/api/file/:token/resize',{'schema':{'tags':['fcore','file'],'summary':'Resize\x20file','description':I(0x108),'access':'user','permissions':['files:read'],'params':fileSchemas['fileToken'],'querystring':fileSchemas['resizeQuery']}},async(c,t)=>{const A=I,e=await resizeFile({'pathOrToken':L['file']?.['verify'](c[A(0x109)][A(0x10a)]),...c[A(0x101)]},L),B=await fileTypeFromBuffer(e);return t['type'](B?.['mime']??'image/png'),t['header']('Content-Disposition','inline')['header']('Cache-Control',A(0x10b)),t[A(0x10c)](e);});};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const L=O;import{Type}from'@sinclair/typebox';function O(L,E){L=L-0x144;const c=Z();let t=c[L];return t;}export const fileSchemas={'fileId':Type['Object']({'id':Type['String']({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type[L(0x144)]({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type[L(0x145)]({'download':Type['Optional'](Type[L(0x146)]())}),'filePath':Type[L(0x145)]({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type['Any'](),'metadata':Type['Object']({'name':Type['Optional'](Type[L(0x144)]({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type[L(0x147)](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type[L(0x144)]({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type[L(0x144)]({'minLength':0x1}))}),'resizeQuery':Type[L(0x145)]({'width':Type['Optional'](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type['Optional'](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type[L(0x148)](L(0x149)),Type['Literal']('contain'),Type['Literal']('fill'),Type['Literal'](L(0x14a)),Type[L(0x148)]('outside')]))})};function Z(){const E=['String','Object','Boolean','Optional','Literal','cover','inside'];Z=function(){return E;};return Z();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function O(L,E){L=L-0x115;var c=Z();var t=c[L];return t;}import{NotFoundError}from'../../../errors.js';export async function getFile(L,E){var c=O;if(!E['file'])throw new Error('empty\x20file');if(!await E[c(0x115)]['exists'](L['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+L[c(0x116)]);return E['file']['get'](L['pathOrToken']);}function Z(){var t=['file','pathOrToken'];Z=function(){return t;};return Z();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function Z(){const x=['width','height','sha256','auto','fit','hex','logs','.jpg','code','file','resize','toBuffer','isInteger'];Z=function(){return x;};return Z();}import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';function O(L,E){L=L-0x1cf;const c=Z();let t=c[L];return t;}import{mkdir,readFile,writeFile}from'node:fs/promises';import L from'node:path';import E from'sharp';export async function resizeFile(c,t){const A=O,e=c['pathOrToken']??c['path'];if(!e)throw new ValidationError('File\x20path\x20is\x20required');const B=parseDimension(c['width'],A(0x1cf))??0xc8,g=parseDimension(c[A(0x1d0)],'height'),r=createHash(A(0x1d1))['update'](e+':'+B+':'+(g??A(0x1d2))+':'+(c[A(0x1d3)]??'cover'))['digest'](A(0x1d4)),X=L['resolve'](A(0x1d5),'resize'),j=L['join'](X,r+A(0x1d6));try{return await readFile(j);}catch(f){if(f[A(0x1d7)]!=='ENOENT')throw f;}if(!await t[A(0x1d8)]['exists'](e))throw new NotFoundError('File\x20not\x20found');const F=await t[A(0x1d8)]['get'](e),I=await fileTypeFromBuffer(F);if(!I?.['mime']['startsWith']('image/'))throw new ValidationError('Only\x20image\x20files\x20can\x20be\x20resized');const T=await E(F)[A(0x1d9)]({'width':B,'height':g,'fit':c['fit']??'cover'})[A(0x1da)]();return await mkdir(X,{'recursive':!![]}),await writeFile(j,T),T;}function parseDimension(c,t){const G=O;if(c===undefined||c==='')return undefined;const e=Number(c);if(!Number[G(0x1db)](e)||e<=0x0)throw new ValidationError(t+'\x20must\x20be\x20a\x20positive\x20integer');return e;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function Z(){const f=['replace','getFullYear','padStart','path','metadata','resource','mime','Unsupported\x20file\x20type:\x20','query','resourceId','file','user'];Z=function(){return f;};return Z();}function O(L,E){L=L-0x1c1;const c=Z();let t=c[L];return t;}import{fileTypeFromBuffer}from'file-type';import L from'../mime.js';import{randomUUID}from'node:crypto';export async function uploadFile(E,c){const T=O,t=(E['metadata']['name']??randomUUID())[T(0x1c1)](/[^a-zA-Z0-9._-]/g,'_'),e=new Date(),B=String(e[T(0x1c2)]())['slice'](-0x2),g=String(e['getMonth']()+0x1)['padStart'](0x2,'0'),r=String(e['getDate']())[T(0x1c3)](0x2,'0'),X=E['metadata'][T(0x1c4)]??(E[T(0x1c5)][T(0x1c6)]?E['metadata'][T(0x1c6)]+'/'+(E['metadata']['resourceId']??randomUUID())+'/'+t:null)??'uploads/'+B+'/'+g+'-'+r+'/'+t,j=await E['file']['toBuffer'](),F=await fileTypeFromBuffer(j);if(!L['has'](E['file']['mimetype'])&&(F?.[T(0x1c7)]?!L['has'](F[T(0x1c7)]):!![]))throw new Error(T(0x1c8)+E['file']['mimetype']);await c['file']['put'](X,j);const I=await c['pg'][T(0x1c9)]('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,uploaded_name,file_name,ext,created_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)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[E[T(0x1c5)]['resource']??null,E['metadata'][T(0x1ca)]??null,X,E['file']['mimetype'],E['file'][T(0x1cb)]['bytesRead'],E['metadata']['name'],t,E[T(0x1cb)]['mimetype']['split']('/')['pop']()??null,E[T(0x1cc)]?.['id']??null]);return I['rows'][0x0];}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ForbiddenError}from'../../errors.js';import{listResources}from'./services/list-resources.js';import{getResource}from'./services/get-resource.js';import{createResource}from'./services/create-resource.js';import{updateResource}from'./services/update-resource.js';import{deleteResource}from'./services/delete-resource.js';
|
|
1
|
+
import{ForbiddenError}from'../../errors.js';import{listResources}from'./services/list-resources.js';import{getResource}from'./services/get-resource.js';import{createResource}from'./services/create-resource.js';import{updateResource}from'./services/update-resource.js';import{deleteResource}from'./services/delete-resource.js';function Z(){const X=['get','Search\x20resource','/api/suggest/:resource/:field','fcore','resource','Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','suggestQuery','*:read','exportResourceQuery','query','List\x20resource\x20records','Returns\x20records\x20from\x20a\x20registered\x20resource.','params','Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','body','/api/resource/:resource/:id','resourceId','resourceIncludeQuery','put','Update\x20resource\x20record','Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','user','Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','/api/resource/:resource/:id/upload','uploadResourceFile','type',':update','filename','fields','Create\x20resource\x20relation','resourceIdRelationId','Updates\x20a\x20related\x20resource\x20record.'];Z=function(){return X;};return Z();}import{listResourceRelation}from'./services/list-resource-relation.js';import{createResourceRelation}from'./services/create-resource-relation.js';import{updateResourceRelation}from'./services/update-resource-relation.js';import{deleteResourceRelation}from'./services/delete-resource-relation.js';import{searchResource}from'./services/search-resource.js';import{exportResource}from'./services/export-resource.js';import{suggestResource}from'./services/suggest-resource.js';import{resourceSchemas}from'./schema.js';import{uploadFile}from'../file/services/upload-file.js';const user=L=>L['user'];function O(L,E){L=L-0x122;const c=Z();let t=c[L];return t;}export function resourceRoutes(L){return async E=>{const g=O;E[g(0x122)]('/api/resource/:resource/search',{'schema':{'tags':['fcore','resource'],'summary':g(0x123),'description':'Searches\x20records\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async c=>searchResource({...c['query'],...c['params'],'user':user(c)},L)),E['get'](g(0x124),{'schema':{'tags':[g(0x125),g(0x126)],'summary':'Suggest\x20resource\x20values','description':g(0x127),'access':'user','permissions':[],'params':resourceSchemas['resourceField'],'querystring':resourceSchemas[g(0x128)]}},async c=>suggestResource({...c['query'],...c['params'],'user':user(c)},L)),E['get']('/api/resource/:resource/export',{'schema':{'tags':['fcore','resource'],'summary':'Export\x20resource\x20records','description':'Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[g(0x129)],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas[g(0x12a)]}},async c=>exportResource({...c[g(0x12b)],...c['params'],'user':user(c)},L)),E['get']('/api/resource/:resource',{'schema':{'tags':['fcore','resource'],'summary':g(0x12c),'description':g(0x12d),'access':'user','permissions':[],'params':resourceSchemas['resource']}},async c=>listResources({...c['query'],...c[g(0x12e)],'user':user(c)},L)),E['post']('/api/resource/:resource',{'schema':{'tags':[g(0x125),'resource'],'summary':'Create\x20resource\x20record','description':g(0x12f),'access':'user','permissions':[],'params':resourceSchemas[g(0x126)]}},async c=>createResource({...c['params'],'data':c[g(0x130)],'user':user(c)},L)),E[g(0x122)](g(0x131),{'schema':{'tags':[g(0x125),'resource'],'summary':'Get\x20resource\x20record','description':'Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas[g(0x132)],'querystring':resourceSchemas[g(0x133)]}},async c=>getResource({...c[g(0x12b)],...c['params'],'user':user(c)},L)),E[g(0x134)]('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':g(0x135),'description':g(0x136),'access':g(0x137),'permissions':[],'params':resourceSchemas['resourceId']}},async c=>updateResource({...c[g(0x12e)],'patch':c['body'],'user':user(c)},L)),E['delete']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Delete\x20resource\x20record','description':g(0x138),'access':'user','permissions':[],'params':resourceSchemas[g(0x132)]}},async c=>deleteResource({...c['params'],'user':user(c)},L)),E['post'](g(0x139),{'schema':{'tags':['fcore','resource'],'summary':'Upload\x20resource\x20file','description':'Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','access':g(0x137),'permissions':[],'params':resourceSchemas[g(0x13a)]}},async c=>{const r=g,t=await c['file']();if(!t)throw new Error('File\x20is\x20required');const e=c['params']['resource'],B=c['params']['id'];if(c['user']?.[r(0x13b)]!=='admin'&&!c[r(0x137)]?.['permissions']['includes'](e+r(0x13c)))throw new ForbiddenError('Missing\x20permission:\x20'+e+r(0x13c));return uploadFile({'file':t,'metadata':{'name':t[r(0x13d)],'path':t[r(0x13e)]['path']?.['value'],'resource':e,'resourceId':B},'user':c['user']},L);}),E[g(0x122)]('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore','resource'],'summary':'List\x20resource\x20relations','description':'Returns\x20related\x20records\x20for\x20a\x20resource\x20record.','access':'user','permissions':[],'schema':{'params':resourceSchemas['resourceIdRelation']}}},async c=>listResourceRelation({...c['query'],...c[g(0x12e)],'user':user(c)},L)),E['post']('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore',g(0x126)],'summary':g(0x13f),'description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas['resourceIdRelation']}},async c=>createResourceRelation({...c['params'],'data':c['body'],'user':user(c)},L)),E['delete']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore',g(0x126)],'summary':'Delete\x20resource\x20relation','description':'Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas[g(0x140)]}},async c=>deleteResourceRelation({...c['params'],'user':user(c)},L)),E['put']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore','resource'],'summary':'Update\x20resource\x20relation','description':g(0x141),'access':'user','permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async c=>updateResourceRelation({...c['params'],'data':c['body'],'user':user(c)},L));};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const L=O;function Z(){const E=['Object','String','Optional','Integer','Record'];Z=function(){return E;};return Z();}import{Type}from'@sinclair/typebox';export const identifier=Type['String']({'minLength':0x1,'maxLength':0x80,'pattern':'^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$'});function O(L,E){L=L-0x6f;const c=Z();let t=c[L];return t;}export const resourceSchemas={'dictionaryName':Type[L(0x6f)]({'name':identifier}),'resource':Type['Object']({'resource':identifier}),'exportResource':Type[L(0x6f)]({'resource':identifier}),'resourceField':Type[L(0x6f)]({'resource':identifier,'field':identifier}),'suggestQuery':Type[L(0x6f)]({'q':Type['Optional'](Type[L(0x70)]()),'search':Type[L(0x71)](Type['String']()),'limit':Type['Optional'](Type[L(0x72)]({'minimum':0x1,'maximum':0xc8}))}),'resourceId':Type['Object']({'resource':identifier,'id':identifier}),'resourceIncludeQuery':Type['Object']({'include':Type['Optional'](Type[L(0x70)]({'minLength':0x1}))}),'resourceIdRelation':Type[L(0x6f)]({'resource':identifier,'id':identifier,'relation':identifier}),'resourceIdRelationId':Type['Object']({'resource':identifier,'id':identifier,'relation':identifier,'relationId':identifier}),'uploadResourceFile':Type['Object']({'resource':identifier,'id':identifier}),'uploadResourceFileBody':Type[L(0x6f)]({'file':Type['Any'](),'fileName':Type[L(0x70)]({'minLength':0x1,'maxLength':0xff})}),'exportResourceQuery':Type['Object']({'filter':Type['Optional'](Type[L(0x73)](Type['String'](),Type['Unknown']())),'sort':Type[L(0x71)](Type['Array'](Type['String']({'minLength':0x1}))),'search':Type[L(0x71)](Type[L(0x70)]()),'limit':Type[L(0x71)](Type[L(0x72)]({'minimum':0x1,'maximum':0xc8})),'offset':Type['Optional'](Type[L(0x72)]({'minimum':0x0})),'fields':Type['Optional'](Type['Array'](identifier))})};
|