@opengis/fcore 0.0.1-beta.10 → 0.0.1-beta.11
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.js +1 -1
- package/dist/modules/system/services/check-system.js +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.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/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 +5 -2
- 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.d.ts.map +1 -1
- package/dist/plugins/resource/services/create-relation.js +1 -1
- package/dist/plugins/resource/services/create.d.ts.map +1 -1
- package/dist/plugins/resource/services/create.js +1 -1
- package/dist/plugins/resource/services/delete-relation.d.ts.map +1 -1
- package/dist/plugins/resource/services/delete-relation.js +1 -1
- package/dist/plugins/resource/services/delete.d.ts +5 -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.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.d.ts.map +1 -1
- package/dist/plugins/resource/services/update-relation.js +1 -1
- package/dist/plugins/resource/services/update.d.ts +5 -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.js +1 -1
- package/dist/plugins/resource/utils/sql.js +1 -1
- package/dist/shared/getIP.js +1 -1
- package/migrations/20260903120000_core_schema.sql +5 -2
- package/migrations/20260903130000_move_notes_files_to_admin.sql +17 -17
- package/migrations/20260903130001_add_file_fields.sql +5 -0
- package/migrations/20260903140000_settings_nulls_not_distinct.sql +18 -18
- package/migrations/20260905120000_add_user_foreign_keys.sql +42 -42
- package/package.json +2 -2
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 required(
|
|
1
|
+
import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(R){const t=process.env[R];if(!t)throw new Error('Missing\x20environment\x20variable:\x20'+R);return t;}export function loadConfig(R={}){const g=q,t={'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===g(0x78),'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')['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['split'](',')['map'](X=>X-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??g(0x79),'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!==g(0x78),'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??g(0x7a),'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||g(0x7b)),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&[g(0x7c),'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{...t,...R,'logger':{...t[g(0x7d)],...R[g(0x7d)]},'pg':{...t['pg'],...R['pg']},'redis':{...t[g(0x7e)],...R['redis']},'s3':{...t['s3'],...R['s3']},'auth':{...t[g(0x7f)],...R['auth']}};}export{required as requireEnv};function q(R,t){R=R-0x78;const X=G();let g=X[R];return g;}function G(){const m=['false','us-east-1','session_user_auth','true','lax','logger','redis','auth'];G=function(){return m;};return G();}
|
package/dist/context.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
let defaultContext;function
|
|
1
|
+
let defaultContext;function q(R,t){R=R-0xab;const X=G();let g=X[R];return g;}function G(){const X=['redis','close','end'];G=function(){return X;};return G();}export function setContext(R){defaultContext=R;}export function getContext(){if(!defaultContext)throw new Error('Application\x20context\x20is\x20not\x20initialized');return defaultContext;}export function createContext(R){return{...R,async 'close'(){const t=q;await Promise['allSettled']([R[t(0xab)]?.[t(0xac)](),R['pg']?.[t(0xad)]()]),await R['logger'][t(0xac)]();}};}
|
package/dist/errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export class FCoreError extends Error{['code'];['statusCode'];['details'];constructor(R,t,X=0x1f4,g){var m=q;super(t),this['code']=R,this['statusCode']=X,this['details']=g,this[m(0x162)]=new.target.name;}}export class BadRequestError extends FCoreError{constructor(R,t){super('BAD_REQUEST_ERROR',R,0x190,t);}}export class UnauthorizedError extends FCoreError{constructor(R='Authentication\x20required'){var Z=q;super(Z(0x163),R,0x191);}}export class ForbiddenError extends FCoreError{constructor(R='Access\x20denied'){super('FORBIDDEN',R,0x193);}}export class NotFoundError extends FCoreError{constructor(R='Not\x20found'){super('NOT_FOUND',R,0x194);}}function G(){var l=['name','UNAUTHORIZED','CONFLICT'];G=function(){return l;};return G();}export class ConflictError extends FCoreError{constructor(R='Conflict'){var z=q;super(z(0x164),R,0x199);}}function q(R,t){R=R-0x162;var X=G();var g=X[R];return g;}export class ValidationError extends FCoreError{constructor(R,t){super('VALIDATION_ERROR',R,0x1a6,t);}}export class UnsupportedError extends FCoreError{constructor(R='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',R,0x1f5);}}
|
package/dist/fastify.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../src/fastify.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,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;AAarE,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAG,EAAE,UAAU,EACf,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,GAClC,kBAAkB,
|
|
1
|
+
{"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../src/fastify.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,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;AAarE,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAG,EAAE,UAAU,EACf,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,GAClC,kBAAkB,CAiIpB"}
|
package/dist/fastify.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FCoreError}from'./errors.js';function
|
|
1
|
+
import{FCoreError}from'./errors.js';function q(R,t){R=R-0x1d4;const X=G();let g=X[R];return g;}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';function G(){const e=['ctx','addHook','schema','tags','description','access','url','routeOptions','raw','authorization','startsWith','Bearer\x20','Route\x20access\x20not\x20defined','user','permissions','admin','includes','Missing\x20permission:\x20','statusCode','code','send','INTERNAL_ERROR','register','system','buffer','disabled','split'];G=function(){return e;};return G();}import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(R,t,X){const g=decodeURIComponent(t['toString']())['split']('&')['reduce']((m,Z)=>{const [z,l]=Z['split']('=');return{...m,[z]:l};},{});X(null,g);}export default function fcoreFastify(R,t){return async X=>{const C=q;X['decorate'](C(0x1d4),R);const {config:g}=R,m=new Map();X[C(0x1d5)]('onRoute',z=>{const L=C;if(z['url']['startsWith']('/api/')){const l=z[L(0x1d6)],y=Array['isArray'](z['method'])?z['method']:[z['method']];for(const h of y){if(h==='HEAD')continue;const P={'method':h,'endpoint':z['url'],'package':l?.['package']??'fcore','tags':l?.[L(0x1d7)]??[],'summary':l?.['summary']??'','description':l?.[L(0x1d8)]??'','access':l?.[L(0x1d9)]??'public','permissions':l?.['permissions']??[]};m['set'](h+'\x20'+z[L(0x1da)],P);}}}),X[C(0x1d5)]('preHandler',async z=>{const O=C,l=m['get'](z['method']+'\x20'+z[O(0x1db)]['url']),y=z[O(0x1dc)]['headers']?.[O(0x1dd)],h=y?.[O(0x1de)](O(0x1df))?y['slice'](0x7):null,P=z['user']??(h?await jwtVerifyToken(h):null);!z['user']&&h&&process.env.AUTH_JWT_SECRET&&(z['user']=await jwtVerifyToken(h));if(!l?.['access'])throw new Error(O(0x1e0));if(l[O(0x1d9)]==='public')return!![];if(!P)throw new ForbiddenError('User\x20required');if(l['access']===O(0x1e1)&&!l[O(0x1e2)]?.['length'])return!![];if(P['type']==O(0x1e3))return!![];if(l['access']==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const E of l['permissions']){if(!P['permissions']?.[O(0x1e4)](E))throw new ForbiddenError(O(0x1e5)+E);}return!![];}),await createSessionStore(X,R),await X['register'](import('@fastify/multipart'),{'limits':{'fileSize':g['maxFileSize']*0x400*0x400}}),X['setErrorHandler']((z,l,y)=>{const U=C;if(z instanceof FCoreError||z['code']==='FST_ERR_VALIDATION'||z[U(0x1e6)]<0x1f4)return z['statusCode']<0x1f4&&R['logger']['warn'](z),y[U(0x1e7)](z['statusCode'])[U(0x1e8)]({'error':z['code'],'message':z['message'],'details':z['details']});return R['logger']['error'](z),(g['debug']||process.env.NODE_ENV==='test'||process.env.VITEST)&&console['error'](z),y['code'](0x1f4)['send']({'error':U(0x1e9),'message':'Internal\x20server\x20error'});});const Z=z=>!t||t['includes'](z);if(Z('auth'))await X[C(0x1ea)](authRoutes(R));if(Z('resource'))await X['register'](resourceRoutes(R));if(Z('file'))await X['register'](fileRoutes(R));if(Z(C(0x1eb)))await X['register'](systemRoutes(R,m));X['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':C(0x1ec)},urlencodedContentParser),!g['rateLimit']?.[C(0x1ed)]?X[C(0x1ea)](import('@fastify/rate-limit'),{'max':g['rateLimit']?.['max']||0x64,'timeWindow':g['rateLimit']?.['timeWindow']||0xea60,'hook':'preHandler','global':!![],'keyGenerator':z=>(z['user']?.['id']||z['ip'])+'-'+z['raw']['url'][C(0x1ee)]('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');};};
|
package/dist/fcore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadConfig}from'./config.js';function
|
|
1
|
+
import{loadConfig}from'./config.js';function q(R,t){R=R-0x130;const X=G();let g=X[R];return g;}import{createContext,setContext}from'./context.js';import{createAudit,createDatabase,createDictionary,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function G(){const E=['dictionaries','length'];G=function(){return E;};return G();}export async function createFCore(R={}){const P=q,t=loadConfig(R['config']),X=createRedis(t['redis']),g=createLogger(),m=createDatabase(t['pg']),Z=createFileS3({'endpoint':t['s3']['endpoint'],'region':t['s3']['region'],'bucket':t['s3']['bucket'],'accessKey':t['s3']['accessKey'],'secretKey':t['s3']['secretKey'],'folder':t['s3']['folder'],'forcePathStyle':t['s3']['forcePathStyle'],'tokenSecret':t['s3']['tokenSecret'],'tokenTtl':t['s3']['tokenTtl']}),z=createAudit({'pg':m,'logger':g}),l=createDictionary({'pg':m,'dictionaries':R[P(0x130)]}),y=createResource({'pg':m,'logger':g,'audit':z,'dictionary':l,'file':Z});R['resources']?.[P(0x131)]&&y['register'](R['resources']);const h=createContext({'config':t,'logger':g,'redis':X,'pg':m,'file':Z,'resource':y,'audit':z,'dictionary':l});return setContext(h),h;}
|
package/dist/migrations/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
function
|
|
2
|
+
const t=q;function q(R,t){R=R-0x1cb;const X=G();let g=X[R];return g;}import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';function G(){const X=['status','OK\x20\x20'];G=function(){return X;};return G();}try{const config=loadConfig();console['log']('Loaded\x20configuration:',config['pg']);for(const r of await runMigrations({'database':config['pg']}))console['log']((r[t(0x1cb)]==='run'?t(0x1cc):'SKIP')+'\x20'+r['file']);}catch(R){console['error'](R),process['exitCode']=0x1;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import R from'node:fs/promises';function q(R,t){R=R-0x1eb;const X=G();let g=X[R];return g;}function G(){const e=['resolve','database','databaseUrl','empty\x20pg','query','readdir','filter','endsWith','has','push','COMMIT','slice'];G=function(){return e;};return G();}import t from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(X={}){const O=q,g=t[O(0x1eb)](X['dir']??'migrations'),m=X[O(0x1ec)]??databaseFromUrl(X[O(0x1ed)]??process.env.DATABASE_URL);if(!m)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const Z=createDatabase(m);if(!Z)throw new Error(O(0x1ee));const z=[];try{await Z[O(0x1ef)]('\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 l=await Z['query']('SELECT\x20version\x20FROM\x20schema_migrations'),y=new Set(l['rows']['map'](P=>P['version'])),h=(await R[O(0x1f0)](g))[O(0x1f1)](P=>P[O(0x1f2)]('.sql'))['sort']();for(const P of h){if(y[O(0x1f3)](P)){z[O(0x1f4)]({'file':P,'status':'skip'});continue;}const E=await R['readFile'](t['join'](g,P),'utf8'),C=await Z['connect']();try{await C['query']('BEGIN'),await C['query'](E),await C['query']('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[P]),await C['query'](O(0x1f5));}catch(L){await C['query']('ROLLBACK');throw L;}finally{C['release']();}z[O(0x1f4)]({'file':P,'status':'run'});}return z;}finally{await Z['end']();}}function databaseFromUrl(X){const U=q;if(!X)return undefined;const g=new URL(X);return{'host':g['hostname'],'port':Number(g['port']||0x1538),'database':g['pathname'][U(0x1f6)](0x1),'user':decodeURIComponent(g['username']),'password':decodeURIComponent(g['password'])};}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
function
|
|
2
|
+
const X=q;function q(R,t){R=R-0x143;const X=G();let g=X[R];return g;}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import R from'./services/registration.js';function G(){const g=['argv','Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]','log','type','error','exitCode'];G=function(){return g;};return G();}const [user,password,type]=process[X(0x143)]['slice'](0x2);if(!user||!password)console['error'](X(0x144)),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await R({'user':user,'password':password,'type':type},{'pg':pg});console[X(0x145)]('Registered\x20user\x20'+data['id']+'\x20('+data[X(0x146)]+')');}catch(t){console[X(0x147)](t),process[X(0x148)]=0x1;}finally{await pg['end']();}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import
|
|
2
|
+
const X=q;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function G(){const g=['rows','User\x20not\x20found','Password\x20changed\x20for\x20','end'];G=function(){return g;};return G();}function q(R,t){R=R-0x9b;const X=G();let g=X[R];return g;}import R from'./services/change-password.js';const [login,password]=process['argv']['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['query']('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result[X(0x9b)][0x0];if(!user)throw new Error(X(0x9c));await R({'userId':user['id'],'password':password},{'pg':pg}),console['log'](X(0x9d)+login);}catch(t){console['error'](t),process['exitCode']=0x1;}finally{await pg[X(0x9e)]();}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
2
|
+
function q(R,t){R=R-0xd7;const X=G();let g=X[R];return g;}function G(){const P=['logs','audit','list','check','includes','add','Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>','query','DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL','Permissions\x20cleared\x20for\x20','split','rows','access_id','ROLLBACK','exitCode','end'];G=function(){return P;};return G();}const y=q;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=[y(0xd7),y(0xd8),y(0xd9),y(0xda),'access','settings','dictionaries'],RESOURCE_ACTIONS=['read','update','create','delete'],[login,permissionArg]=process['argv']['slice'](0x2);function expandPermissions(R){const h=y,t=R['split'](',')['map'](g=>g['trim']())['filter'](Boolean),X=new Set();for(const g of t){if(g[h(0xdb)](':')){X['add'](g);continue;}const m=g==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const Z of m){X[h(0xdc)](g+':'+Z);}}return[...X];}if(!login||!permissionArg)console['error'](y(0xdd)),process['exitCode']=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[y(0xde)](y(0xdf),[user['id']]),console['log'](y(0xe0)+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission[y(0xe1)](':'),actions=byResource['get'](resource)??[];actions['push'](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[y(0xe2)][0x0];if(row){const merged=[...new Set([...row['actions']??[],...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[y(0xe3)]]);}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[y(0xde)]('COMMIT');}catch(z){await client['query'](y(0xe4));throw z;}finally{client['release']();}console['log']('Granted\x20permissions\x20for\x20'+login+':\x20'+permissions['join'](',\x20'));}}catch(l){console['error'](l),process[y(0xe5)]=0x1;}finally{await pg[y(0xe6)]();}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';
|
|
1
|
+
import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';function G(){const e=['method','GET','config','auth','twoFactorRedirect','login','cookie','session','fcore','Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','credentials','post','/api/auth/login','Register','admin','body','/api/auth/logout','Terminates\x20the\x20current\x20user\x20session.','write','destroy','get','Get\x20current\x20user','query','token'];G=function(){return e;};return G();}import R from'./services/get-current-user.js';function q(R,t){R=R-0x124;const X=G();let g=X[R];return g;}import t from'./services/registration.js';import X from'./services/change-password.js';import{authSchemas}from'./schema.js';import g from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(m){return async Z=>{const O=q,z=async l=>{const L=q,y=l[L(0x124)]===L(0x125)?l['query']:l['body'],h=g(l),P=await verifyUser({...y,'ip':h},m);P['permissions']=await getUserPermissions(P['id'],m);const E=P['twofa']?m[L(0x126)][L(0x127)][L(0x128)]:m[L(0x126)]['auth']['redirect'];await l[L(0x129)](P);const C=m['config'][L(0x127)]['sessionTimeout']*0x3e8*0x3c;return l['session']?.[L(0x12a)]&&(l['session']['cookie']['maxAge']=C),await l['session']['save'](),await m['audit']?.['write']?.({'module':L(0x127),'resource':'session','resourceId':l[L(0x12b)]['sessionId'],'action':L(0x129),'userId':P['id'],'ipAddress':h}),{'user':{'id':P['id'],'type':P['type'],'permissions':P['permissions']},'redirectUrl':E};};Z['get']('/api/auth/login',{'schema':{'tags':[O(0x12c),'auth'],'summary':'Sign\x20in','description':O(0x12d),'access':'public','permissions':[],'querystring':authSchemas[O(0x12e)]}},z),Z[O(0x12f)](O(0x130),{'schema':{'tags':['fcore',O(0x127)],'summary':'Sign\x20in','description':O(0x12d),'access':'public','permissions':[],'body':authSchemas['credentials']}},z),Z[O(0x12f)]('/api/auth/registration',{'schema':{'tags':[O(0x12c),'auth'],'summary':O(0x131),'description':'Creates\x20a\x20regular\x20user\x20account.','access':O(0x132),'permissions':['user:create'],'body':authSchemas['credentials']}},async l=>t(l[O(0x133)],m)),Z['post']('/api/auth/password',{'schema':{'tags':[O(0x12c),'auth'],'summary':'Change\x20password','description':'Changes\x20the\x20password\x20for\x20the\x20current\x20user.','access':'user','permissions':[],'body':authSchemas['password']}},async l=>{if(!l['user'])throw new UnauthorizedError('Not\x20authorized');return await X({'userId':l['user']['id'],...l['body']},m),{'success':!![]};}),Z[O(0x12f)](O(0x134),{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':O(0x135),'access':'user','permissions':[]}},async(l,y)=>{const U=O,h={'redirectUrl':'/'};if(!l['user'])return h;return await m['audit']?.[U(0x136)]?.({'module':'auth','resource':'session','resourceId':l['session']['sessionId'],'action':'logout','userId':l['user']?.['id']}),await l[U(0x12b)][U(0x137)](),y['clearCookie'](m[U(0x126)]['auth']['cookieName']),Object['defineProperty'](l,'session',{'value':null,'writable':![],'configurable':![]}),h;}),Z[O(0x138)]('/api/auth/user',{'schema':{'tags':[O(0x12c),O(0x127)],'summary':O(0x139),'description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas['query']}},async l=>R({'user':l['user'],'token':l[O(0x13a)][O(0x13b)]}));};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const R=q;function q(R,t){R=R-0x1e4;const X=G();let g=X[R];return g;}import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type['Object']({'token':Type[R(0x1e4)](Type['Boolean']())}),'credentials':Type[R(0x1e5)]({'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['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type[R(0x1e5)]({'code':Type['String']({'minLength':0x1})})};function G(){const t=['Optional','Object'];G=function(){return t;};return G();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:
|
|
1
|
+
function q(R,t){R=R-0x69;const X=G();let g=X[R];return g;}import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:R,password:t,userId:X},{pg:g}){const Z=q,m=await hashPassword(t);await g['query'](Z(0x69),[m,R||X,X]);}function G(){const z=['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'];G=function(){return z;};return G();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function q(R,t){R=R-0x75;const X=G();let g=X[R];return g;}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(R){const Z=q,{user:t}=R;if(!t)return{};if(R['token']){const {jwtSignToken:X}=await import(Z(0x75)),g=await X(t);t['token']=g;}return t[Z(0x76)]=[...new Set(t?.['permissions']['map'](m=>m['split'](':')[0x0]))],safeUser(t);}function G(){const z=['../../../plugins/jwt.js','resources'];G=function(){return z;};return G();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function G(){const y=['query','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','rows'];G=function(){return y;};return G();}import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';function q(R,t){R=R-0x176;const X=G();let g=X[R];return g;}export default async function registration({user:R,password:t,type:X},{pg:g}){const l=q,m=await hashPassword(t),Z=await g[l(0x176)](l(0x177),[R,m,X||'regular']),z=Z[l(0x178)][0x0];if(!z)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':z};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(
|
|
1
|
+
function G(){var g=['Two-factor\x20provider'];G=function(){return g;};return G();}import{unsupported}from'../../utils/unsupported.js';function q(R,t){R=R-0xd7;var X=G();var g=X[R];return g;}export default async function verifyTwoFactor(R,t){var X=q;return unsupported(X(0xd7));}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var R=q;function q(R,t){R=R-0xaf;var X=G();var g=X[R];return g;}export default new Set(['image/jpeg',R(0xaf),'image/gif','image/webp','image/bmp','image/tiff',R(0xb0),'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',R(0xb1),R(0xb2),'text/csv','text/markdown',R(0xb3),R(0xb4),'text/xml','application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip','application/x-zip-compressed','application/x-7z-compressed','application/x-rar-compressed',R(0xb5),R(0xb6),'application/x-gzip',R(0xb7),'audio/mpeg','audio/wav','audio/ogg','audio/webm',R(0xb8),'video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo',R(0xb9)]);function G(){var t=['image/png','image/svg+xml','application/vnd.oasis.opendocument.presentation','text/plain','application/json','application/xml','application/vnd.rar','application/gzip','application/x-tar','audio/mp4','application/octet-stream'];G=function(){return t;};return G();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';function q(R,t){R=R-0x154;const X=G();let g=X[R];return g;}import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';function G(){const U=['get','file','public','token','application/octet-stream','image/','application/pdf','Content-Disposition','inline','header','public,\x20max-age=86400,\x20immutable','post','/api/file/upload','fcore','filename','resource','fields','user','query'];G=function(){return U;};return G();}export function fileRoutes(R){return async t=>{const E=q;t[E(0x154)]('/api/file/:token',{'schema':{'tags':['fcore',E(0x155)],'summary':'Get\x20file\x20by\x20token','description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':E(0x156),'permissions':[],'params':fileSchemas['fileToken'],'querystring':fileSchemas['fileDownloadQuery']}},async(X,g)=>{const C=E,m=R[C(0x155)]['verify'](X['params'][C(0x157)]),Z=await getFile({'pathOrToken':m},R),z=await fileTypeFromBuffer(Z),l=z?.['mime']??C(0x158),y=X['query']['download']===!![],h=l['startsWith'](C(0x159))||l===C(0x15a),P=m['split']('/')['pop']()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??C(0x155);return g['type'](l),g['header'](C(0x15b),(y||!h?'attachment':C(0x15c))+';\x20filename=\x22'+P+'\x22')[C(0x15d)]('Cache-Control',C(0x15e)),g['send'](Z);}),t[E(0x15f)](E(0x160),{'schema':{'tags':[E(0x161),'file'],'summary':'Upload\x20file','description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':['files:create']}},async X=>{const L=E,g=await X['file']();if(!g)throw new Error('File\x20is\x20required');return uploadFile({'file':g,'metadata':{'name':g[L(0x162)],'path':g['fields']['path']?.['value'],'resource':g['fields'][L(0x163)]?.['value'],'resourceId':g[L(0x164)]['resourceId']?.['value']},'user':X[L(0x165)]},R);}),t['get']('/api/file/:token/resize',{'schema':{'tags':['fcore','file'],'summary':'Resize\x20file','description':'Returns\x20a\x20resized\x20image\x20file.','access':'user','permissions':['files:read'],'params':fileSchemas['fileToken'],'querystring':fileSchemas['resizeQuery']}},async(X,g)=>{const O=E,m=await resizeFile({'pathOrToken':R['file']?.['verify'](X['params'][O(0x157)]),...X[O(0x166)]},R),Z=await fileTypeFromBuffer(m);return g['type'](Z?.['mime']??'image/png'),g['header']('Content-Disposition','inline')[O(0x15d)]('Cache-Control',O(0x15e)),g['send'](m);});};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
function G(){const t=['Object','String','Optional','Union','cover','contain','fill'];G=function(){return t;};return G();}function q(R,t){R=R-0x197;const X=G();let g=X[R];return g;}const R=q;import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type[R(0x197)]({'id':Type['String']({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type[R(0x197)]({'download':Type['Optional'](Type['Boolean']())}),'filePath':Type['Object']({'*':Type[R(0x198)]({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type['Any'](),'metadata':Type[R(0x197)]({'name':Type['Optional'](Type['String']({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type[R(0x199)](Type[R(0x198)]({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type[R(0x199)](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))}),'resizeQuery':Type[R(0x197)]({'width':Type['Optional'](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type['Optional'](Type['Integer']({'minimum':0x1})),'fit':Type[R(0x199)](Type[R(0x19a)]([Type['Literal'](R(0x19b)),Type['Literal'](R(0x19c)),Type['Literal'](R(0x19d)),Type['Literal']('inside'),Type['Literal']('outside')]))})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{NotFoundError}from'../../../errors.js';export async function getFile(R,t){var X=q;if(!t[X(0xb6)])throw new Error(X(0xb7));if(!await t[X(0xb6)]['exists'](R['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+R[X(0xb8)]);return t['file']['get'](R[X(0xb8)]);}function q(R,t){R=R-0xb6;var X=G();var g=X[R];return g;}function G(){var g=['file','empty\x20file','pathOrToken'];G=function(){return g;};return G();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NotFoundError,ValidationError}from'../../../errors.js';
|
|
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 R from'node:path';import t from'sharp';function q(R,t){R=R-0xce;const X=G();let g=X[R];return g;}function G(){const e=['pathOrToken','fit','hex','logs','resize','code','ENOENT','file','mime','startsWith','cover','toBuffer','\x20must\x20be\x20a\x20positive\x20integer'];G=function(){return e;};return G();}export async function resizeFile(X,g){const O=q,m=X[O(0xce)]??X['path'];if(!m)throw new ValidationError('File\x20path\x20is\x20required');const Z=parseDimension(X['width'],'width')??0xc8,z=parseDimension(X['height'],'height'),l=createHash('sha256')['update'](m+':'+Z+':'+(z??'auto')+':'+(X[O(0xcf)]??'cover'))['digest'](O(0xd0)),y=R['resolve'](O(0xd1),O(0xd2)),h=R['join'](y,l+'.jpg');try{return await readFile(h);}catch(L){if(L[O(0xd3)]!==O(0xd4))throw L;}if(!await g['file']['exists'](m))throw new NotFoundError('File\x20not\x20found');const P=await g[O(0xd5)]['get'](m),E=await fileTypeFromBuffer(P);if(!E?.[O(0xd6)][O(0xd7)]('image/'))throw new ValidationError('Only\x20image\x20files\x20can\x20be\x20resized');const C=await t(P)['resize']({'width':Z,'height':z,'fit':X[O(0xcf)]??O(0xd8)})[O(0xd9)]();return await mkdir(y,{'recursive':!![]}),await writeFile(h,C),C;}function parseDimension(X,g){const U=q;if(X===undefined||X==='')return undefined;const m=Number(X);if(!Number['isInteger'](m)||m<=0x0)throw new ValidationError(g+U(0xda));return m;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{fileTypeFromBuffer}from'file-type';import R from'../mime.js';import{randomUUID}from'node:crypto';function q(R,t){R=R-0x147;const X=G();let g=X[R];return g;}function G(){const L=['padStart','metadata','has','mime','resource','name','file','rows'];G=function(){return L;};return G();}export async function uploadFile(t,X){const C=q,g=(t['metadata']['name']??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),m=new Date(),Z=String(m['getFullYear']())['slice'](-0x2),z=String(m['getMonth']()+0x1)[C(0x147)](0x2,'0'),l=String(m['getDate']())['padStart'](0x2,'0'),y=t['metadata']['path']??(t[C(0x148)]['resource']?t['metadata']['resource']+'/'+(t['metadata']['resourceId']??randomUUID())+'/'+g:null)??'uploads/'+Z+'/'+z+'-'+l+'/'+g,h=await t['file']['toBuffer'](),P=await fileTypeFromBuffer(h);if(!R['has'](t['file']['mimetype'])&&(P?.['mime']?!R[C(0x149)](P[C(0x14a)]):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+t['file']['mimetype']);await X['file']['put'](y,h);const E=await X['pg']['query']('\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',[t['metadata'][C(0x14b)]??null,t['metadata']['resourceId']??null,y,t['file']['mimetype'],t['file']['file']['bytesRead'],t['metadata'][C(0x14c)],g,t[C(0x14d)]['mimetype']['split']('/')['pop']()??null,t['user']?.['id']??null]);return E[C(0x14e)][0x0];}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ForbiddenError}from'../../errors.js';import{listResources}from'./services/list-resources.js';import{getResource}from'./services/get-resource.js';
|
|
1
|
+
import{ForbiddenError}from'../../errors.js';import{listResources}from'./services/list-resources.js';import{getResource}from'./services/get-resource.js';function G(){const y=['fcore','resource','params','resourceField','suggestQuery','get','/api/resource/:resource/export','query','/api/resource/:resource','user','body','/api/resource/:resource/:id','Update\x20resource\x20record','post','Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','file','type','permissions','fields','List\x20resource\x20relations','Delete\x20resource\x20relation'];G=function(){return y;};return G();}import{createResource}from'./services/create-resource.js';import{updateResource}from'./services/update-resource.js';import{deleteResource}from'./services/delete-resource.js';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';function q(R,t){R=R-0x141;const X=G();let g=X[R];return g;}const user=R=>R['user'];export function resourceRoutes(R){return async t=>{const z=q;t['get']('/api/resource/:resource/search',{'schema':{'tags':[z(0x141),z(0x142)],'summary':'Search\x20resource','description':'Searches\x20records\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async X=>searchResource({...X['query'],...X[z(0x143)],'user':user(X)},R)),t['get']('/api/suggest/:resource/:field',{'schema':{'tags':['fcore','resource'],'summary':'Suggest\x20resource\x20values','description':'Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','access':'user','permissions':[],'params':resourceSchemas[z(0x144)],'querystring':resourceSchemas[z(0x145)]}},async X=>suggestResource({...X['query'],...X[z(0x143)],'user':user(X)},R)),t[z(0x146)](z(0x147),{'schema':{'tags':['fcore',z(0x142)],'summary':'Export\x20resource\x20records','description':'Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':['*:read'],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas['exportResourceQuery']}},async X=>exportResource({...X[z(0x148)],...X[z(0x143)],'user':user(X)},R)),t['get'](z(0x149),{'schema':{'tags':[z(0x141),z(0x142)],'summary':'List\x20resource\x20records','description':'Returns\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async X=>listResources({...X['query'],...X['params'],'user':user(X)},R)),t['post']('/api/resource/:resource',{'schema':{'tags':['fcore','resource'],'summary':'Create\x20resource\x20record','description':'Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':z(0x14a),'permissions':[],'params':resourceSchemas[z(0x142)]}},async X=>createResource({...X[z(0x143)],'data':X[z(0x14b)],'user':user(X)},R)),t[z(0x146)](z(0x14c),{'schema':{'tags':['fcore','resource'],'summary':'Get\x20resource\x20record','description':'Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','access':z(0x14a),'permissions':[],'params':resourceSchemas['resourceId'],'querystring':resourceSchemas['resourceIncludeQuery']}},async X=>getResource({...X['query'],...X['params'],'user':user(X)},R)),t['put'](z(0x14c),{'schema':{'tags':['fcore','resource'],'summary':z(0x14d),'description':'Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resourceId']}},async X=>updateResource({...X['params'],'patch':X['body'],'user':user(X)},R)),t['delete']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Delete\x20resource\x20record','description':'Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resourceId']}},async X=>deleteResource({...X[z(0x143)],'user':user(X)},R)),t[z(0x14e)]('/api/resource/:resource/:id/upload',{'schema':{'tags':['fcore','resource'],'summary':'Upload\x20resource\x20file','description':z(0x14f),'access':z(0x14a),'permissions':[],'params':resourceSchemas['uploadResourceFile']}},async X=>{const l=z,g=await X[l(0x150)]();if(!g)throw new Error('File\x20is\x20required');const m=X['params']['resource'],Z=X['params']['id'];if(X['user']?.[l(0x151)]!=='admin'&&!X['user']?.[l(0x152)]['includes'](m+':update'))throw new ForbiddenError('Missing\x20permission:\x20'+m+':update');return uploadFile({'file':g,'metadata':{'name':g['filename'],'path':g[l(0x153)]['path']?.['value'],'resource':m,'resourceId':Z},'user':X[l(0x14a)]},R);}),t['get']('/api/resource/:resource/:id/:relation',{'schema':{'tags':[z(0x141),z(0x142)],'summary':z(0x154),'description':'Returns\x20related\x20records\x20for\x20a\x20resource\x20record.','access':z(0x14a),'permissions':[],'schema':{'params':resourceSchemas['resourceIdRelation']}}},async X=>listResourceRelation({...X['query'],...X[z(0x143)],'user':user(X)},R)),t[z(0x14e)]('/api/resource/:resource/:id/:relation',{'schema':{'tags':[z(0x141),z(0x142)],'summary':'Create\x20resource\x20relation','description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas['resourceIdRelation']}},async X=>createResourceRelation({...X['params'],'data':X['body'],'user':user(X)},R)),t['delete']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore','resource'],'summary':z(0x155),'description':'Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async X=>deleteResourceRelation({...X['params'],'user':user(X)},R)),t['put']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore',z(0x142)],'summary':'Update\x20resource\x20relation','description':'Updates\x20a\x20related\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async X=>updateResourceRelation({...X['params'],'data':X['body'],'user':user(X)},R));};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
function G(){const t=['String','^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$','Object','Optional','Record'];G=function(){return t;};return G();}const R=q;function q(R,t){R=R-0x97;const X=G();let g=X[R];return g;}import{Type}from'@sinclair/typebox';export const identifier=Type[R(0x97)]({'minLength':0x1,'maxLength':0x80,'pattern':R(0x98)});export const resourceSchemas={'dictionaryName':Type['Object']({'name':identifier}),'resource':Type['Object']({'resource':identifier}),'exportResource':Type['Object']({'resource':identifier}),'resourceField':Type['Object']({'resource':identifier,'field':identifier}),'suggestQuery':Type[R(0x99)]({'q':Type['Optional'](Type[R(0x97)]()),'search':Type[R(0x9a)](Type['String']()),'limit':Type['Optional'](Type['Integer']({'minimum':0x1,'maximum':0xc8}))}),'resourceId':Type['Object']({'resource':identifier,'id':identifier}),'resourceIncludeQuery':Type['Object']({'include':Type[R(0x9a)](Type['String']({'minLength':0x1}))}),'resourceIdRelation':Type['Object']({'resource':identifier,'id':identifier,'relation':identifier}),'resourceIdRelationId':Type[R(0x99)]({'resource':identifier,'id':identifier,'relation':identifier,'relationId':identifier}),'uploadResourceFile':Type['Object']({'resource':identifier,'id':identifier}),'uploadResourceFileBody':Type['Object']({'file':Type['Any'](),'fileName':Type[R(0x97)]({'minLength':0x1,'maxLength':0xff})}),'exportResourceQuery':Type['Object']({'filter':Type['Optional'](Type[R(0x9b)](Type['String'](),Type['Unknown']())),'sort':Type['Optional'](Type['Array'](Type['String']({'minLength':0x1}))),'search':Type['Optional'](Type[R(0x97)]()),'limit':Type[R(0x9a)](Type['Integer']({'minimum':0x1,'maximum':0xc8})),'offset':Type[R(0x9a)](Type['Integer']({'minimum':0x0})),'fields':Type['Optional'](Type['Array'](identifier))})};
|