@opengis/fcore 0.0.1-beta.22 → 0.0.1-beta.24
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.d.ts +1 -0
- package/dist/modules/resource/schema.d.ts.map +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.d.ts.map +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 +22 -0
- 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 +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.js +1 -1
- package/dist/plugins/resource/services/delete-relation.d.ts +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.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/get-table-columns.d.ts +8 -0
- package/dist/plugins/resource/services/get-table-columns.d.ts.map +1 -0
- package/dist/plugins/resource/services/get-table-columns.js +1 -0
- package/dist/plugins/resource/services/update-relation.js +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.d.ts +2 -1
- package/dist/plugins/resource/utils/filters.d.ts.map +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/plugins/resource/utils/summary.d.ts +3 -0
- package/dist/plugins/resource/utils/summary.d.ts.map +1 -0
- package/dist/plugins/resource/utils/summary.js +1 -0
- package/dist/shared/getIP.js +1 -1
- package/migrations/20260903120000_core_schema.sql +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/migrations/20260910170000_core_schema.sql +22 -0
- 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
|
-
function
|
|
1
|
+
function W(){const S=['Missing\x20environment\x20variable:\x20','true','./storage','password','map','false','x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','session_user_auth','lax','includes','logger','redis'];W=function(){return S;};return W();}import'dotenv/config';function n(s,J){s=s-0x124;const N=W();let O=N[s];return O;}const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(s){const O=n,J=process.env[s];if(!J)throw new Error(O(0x124)+s);return J;}export function loadConfig(s={}){const E=n,J={'env':process.env.NODE_ENV??'development','debug':process.env.DEBUG===E(0x125),'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??E(0x126),'redactionList':(process.env.REDACTION_LIST||E(0x127))['split'](','),'logger':{'level':process.env.LOG_LEVEL??'info','responses':process.env.LOG_RESPONSES===E(0x125)?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES['split'](',')[E(0x128)](N=>N-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(0x129),'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??E(0x12a),'cookieName':process.env.AUTH_COOKIE_NAME??E(0x12b),'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&&[E(0x12c),'strict','none'][E(0x12d)](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{...J,...s,'logger':{...J['logger'],...s[E(0x12e)]},'pg':{...J['pg'],...s['pg']},'redis':{...J['redis'],...s[E(0x12f)]},'s3':{...J['s3'],...s['s3']},'auth':{...J['auth'],...s['auth']}};}export{required as requireEnv};
|
package/dist/context.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function n(s,J){s=s-0x16d;const N=W();let O=N[s];return O;}let defaultContext;function W(){const N=['allSettled','redis'];W=function(){return N;};return W();}export function setContext(s){defaultContext=s;}export function getContext(){if(!defaultContext)throw new Error('Application\x20context\x20is\x20not\x20initialized');return defaultContext;}export function createContext(s){return{...s,async 'close'(){const J=n;await Promise[J(0x16d)]([s[J(0x16e)]?.['close'](),s['pg']?.['end']()]),await s['logger']['close']();}};}
|
package/dist/errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var E=n;function n(s,J){s=s-0x148;var N=W();var O=N[s];return O;}function W(){var a=['code','statusCode','details','Not\x20found','NOT_FOUND','UNSUPPORTED'];W=function(){return a;};return W();}export class FCoreError extends Error{[E(0x148)];[E(0x149)];['details'];constructor(s,J,N=0x1f4,O){var S=E;super(J),this['code']=s,this['statusCode']=N,this[S(0x14a)]=O,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(s,J){super('BAD_REQUEST_ERROR',s,0x190,J);}}export class UnauthorizedError extends FCoreError{constructor(s='Authentication\x20required'){super('UNAUTHORIZED',s,0x191);}}export class ForbiddenError extends FCoreError{constructor(s='Access\x20denied'){super('FORBIDDEN',s,0x193);}}export class NotFoundError extends FCoreError{constructor(s=E(0x14b)){var T=E;super(T(0x14c),s,0x194);}}export class ConflictError extends FCoreError{constructor(s='Conflict'){super('CONFLICT',s,0x199);}}export class ValidationError extends FCoreError{constructor(s,J){super('VALIDATION_ERROR',s,0x1a6,J);}}export class UnsupportedError extends FCoreError{constructor(s='Operation\x20is\x20not\x20configured'){var f=E;super(f(0x14d),s,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;AAYrE,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":"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,CAgJpB"}
|
package/dist/fastify.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import s from'fastify-plugin';import{FCoreError}from'./errors.js';import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';import{resourceRoutes}from'./modules/resource/route.js';function W(){const x=['method','HEAD','fcore','tags','description','permissions','set','get','url','platform','auth','authorization','access','public','User\x20required','user','length','admin','Admin\x20access\x20required','$resource','params','includes','register','setErrorHandler','FST_ERR_VALIDATION','logger','error','code','Internal\x20server\x20error','system','addContentTypeParser','application/x-www-form-urlencoded','buffer','log','⚠️\x20rate\x20limit\x20is\x20disabled'];W=function(){return x;};return W();}import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';function n(s,J){s=s-0x1b2;const N=W();let O=N[s];return O;}import{ForbiddenError}from'./errors.js';import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(J,N,O){const E=decodeURIComponent(N['toString']())['split']('&')['reduce']((S,T)=>{const [f,a]=T['split']('=');return{...S,[f]:a};},{});O(null,E);}export default function fcoreFastify(J,N){return s(async O=>{const u=n;O['decorate']('ctx',J);const {config:E}=J,S=new Map();O['addHook']('onRoute',f=>{const i=n,a=f['schema'],g=Array['isArray'](f['method'])?f[i(0x1b2)]:[f['method']];for(const p of g){if(p===i(0x1b3))continue;const D={'method':p,'endpoint':f['url'],'package':a?.['package']??i(0x1b4),'tags':a?.[i(0x1b5)]??[],'summary':a?.['summary']??'','description':a?.[i(0x1b6)]??'','access':a?.['access']??'public','permissions':a?.[i(0x1b7)]??[]};S[i(0x1b8)](p+'\x20'+f['url'],D);}}),O['addHook']('preHandler',async f=>{const Q=n;if(f['routeOptions']['url']==='*')return!![];const a=S[Q(0x1b9)](f['method']+'\x20'+f['routeOptions'][Q(0x1ba)]),g=!f['user']&&process[Q(0x1bb)]==='win32'&&J['config']?.[Q(0x1bc)]?.['user']?J['config']?.[Q(0x1bc)]?.['user']:null,p=f['raw']['headers']?.[Q(0x1bd)],D=p?.['startsWith']('Bearer\x20')?p['slice'](0x7):null,R=f['user']??(D?await jwtVerifyToken(D):g);!f['user']&&D&&process.env.AUTH_JWT_SECRET&&(f['user']=await jwtVerifyToken(D));if(!a?.[Q(0x1be)])throw new ForbiddenError('Route\x20access\x20not\x20defined');if(a['access']===Q(0x1bf))return!![];if(!R)throw new ForbiddenError(Q(0x1c0));if(a['access']===Q(0x1c1)&&!a[Q(0x1b7)]?.[Q(0x1c2)])return!![];if(R['type']=='admin')return!![];if(a['access']===Q(0x1c3))throw new ForbiddenError(Q(0x1c4));for(const v of a['permissions']){const o=v?.['replace'](Q(0x1c5),f[Q(0x1c6)]['resource']??'');if(!R['permissions']?.[Q(0x1c7)](o))throw new ForbiddenError('Missing\x20permission:\x20'+o);}return!![];}),await createSessionStore(O,J),await O[u(0x1c8)](import('@fastify/multipart'),{'limits':{'fileSize':E['maxFileSize']*0x400*0x400}}),O[u(0x1c9)]((f,a,g)=>{const e=u;if(f instanceof FCoreError||f['code']===e(0x1ca)||f['statusCode']<0x1f4)return f['statusCode']<0x1f4&&J[e(0x1cb)]['warn'](f),g['code'](f['statusCode'])['send']({'error':f['code'],'message':f['message'],'details':f['details']});return J['logger'][e(0x1cc)](f),(E['debug']||process.env.NODE_ENV==='test'||process.env.VITEST)&&console['error'](f),g[e(0x1cd)](0x1f4)['send']({'error':'INTERNAL_ERROR','message':e(0x1ce)});});const T=f=>!N||N['includes'](f);if(T('auth'))await O[u(0x1c8)](authRoutes(J));if(T('resource'))await O['register'](resourceRoutes(J));if(T('file'))await O['register'](fileRoutes(J));if(T(u(0x1cf)))await O['register'](systemRoutes(J,S));O[u(0x1d0)](u(0x1d1),{'parseAs':u(0x1d2)},urlencodedContentParser),!E['rateLimit']?.['disabled']?O[u(0x1c8)](import('@fastify/rate-limit'),{'max':E['rateLimit']?.['max']||0x64,'timeWindow':E['rateLimit']?.['timeWindow']||0xea60,'hook':'preHandler','global':!![],'keyGenerator':f=>(f['user']?.['id']||f['ip'])+'-'+f['raw']['url']['split']('?')[0x0]}):console[u(0x1d3)](u(0x1d4));});}
|
package/dist/fcore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';function
|
|
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 W(){const D=['region','bucket','accessKey','folder','forcePathStyle','resources','length'];W=function(){return D;};return W();}function n(s,J){s=s-0x1aa;const N=W();let O=N[s];return O;}export async function createFCore(s={}){const p=n,J=loadConfig(s['config']),N=createRedis(J['redis']),O=createLogger(),E=createDatabase(J['pg']),S=createFileS3({'endpoint':J['s3']['endpoint'],'region':J['s3'][p(0x1aa)],'bucket':J['s3'][p(0x1ab)],'accessKey':J['s3'][p(0x1ac)],'secretKey':J['s3']['secretKey'],'folder':J['s3'][p(0x1ad)],'forcePathStyle':J['s3'][p(0x1ae)],'tokenSecret':J['s3']['tokenSecret'],'tokenTtl':J['s3']['tokenTtl']}),T=createAudit({'pg':E,'logger':O}),f=createDictionary({'pg':E,'dictionaries':s['dictionaries']}),a=createResource({'pg':E,'logger':O,'audit':T,'dictionary':f,'file':S});s[p(0x1af)]?.[p(0x1b0)]&&a['register'](s[p(0x1af)]);const g=createContext({'config':J,'logger':O,'redis':N,'pg':E,'file':S,'resource':a,'audit':T,'dictionary':f});return setContext(g),g;}
|
package/dist/migrations/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
2
|
+
const a=n;import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';import s from'node:path';function n(s,J){s=s-0x154;const N=W();let O=N[s];return O;}import{fileURLToPath}from'node:url';function W(){const g=['--dir','--fcore','argv','slice','log','status','run','OK\x20\x20','SKIP','file','exitCode'];W=function(){return g;};return W();}const packageMigrations=fileURLToPath(new URL('../../migrations',import.meta.url));function migrationDirectory(J){const f=n,N=J['indexOf'](f(0x154));if(N>=0x0){const E=J[N+0x1];if(!E)throw new Error('--dir\x20requires\x20a\x20folder\x20path');return s['resolve'](E);}if(J['includes'](f(0x155)))return packageMigrations;const O=J['find'](S=>!S['startsWith']('--'));return s['resolve'](O??'migrations');}try{const config=loadConfig(),dir=migrationDirectory(process[a(0x156)]['slice'](0x2));console['log']('Loaded\x20configuration:',{...config['pg'],'user':'****','password':'****'}),console['log']('Using\x20migration\x20directory:',dir,process['argv'][a(0x157)](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console[a(0x158)]((r[a(0x159)]===a(0x15a)?a(0x15b):a(0x15c))+'\x20'+r[a(0x15d)]);}catch(T){console['error'](T),process[a(0x15e)]=0x1;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import s from'node:fs/promises';import J from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(N={}){const o=n,O=J[o(0x8d)](N['dir']??'migrations'),E=N['database']??databaseFromUrl(N[o(0x8e)]??process.env.DATABASE_URL);if(!E)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const S=createDatabase(E);if(!S)throw new Error('empty\x20pg');const T=[];try{await S['query']('\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 f=await S['query'](o(0x8f)),a=new Set(f['rows']['map'](p=>p['version'])),g=(await s['readdir'](O))['filter'](p=>p['endsWith']('.sql'))['sort']();for(const p of g){if(a['has'](p)){T[o(0x90)]({'file':p,'status':'skip'});continue;}const D=await s['readFile'](J['join'](O,p),'utf8'),R=await S['connect']();try{await R['query']('BEGIN'),await R['query'](D),await R['query'](o(0x91),[p]),await R['query'](o(0x92));}catch(v){await R[o(0x93)](o(0x94));throw v;}finally{R['release']();}T['push']({'file':p,'status':'run'});}return T;}finally{await S['end']();}}function n(s,J){s=s-0x8d;const N=W();let O=N[s];return O;}function databaseFromUrl(N){const i=n;if(!N)return undefined;const O=new URL(N);return{'host':O['hostname'],'port':Number(O['port']||0x1538),'database':O[i(0x95)]['slice'](0x1),'user':decodeURIComponent(O['username']),'password':decodeURIComponent(O['password'])};}function W(){const Q=['resolve','databaseUrl','SELECT\x20version\x20FROM\x20schema_migrations','push','INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)','COMMIT','query','ROLLBACK','pathname'];W=function(){return Q;};return W();}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
2
|
+
const N=n;function n(s,J){s=s-0x97;const N=W();let O=N[s];return O;}import{loadConfig}from'../../config.js';function W(){const O=['argv','log','end'];W=function(){return O;};return W();}import{createDatabase}from'../../plugins/pg.js';import s from'./services/registration.js';const [user,password,type]=process[N(0x97)]['slice'](0x2);if(!user||!password)console['error']('Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await s({'user':user,'password':password,'type':type},{'pg':pg});console[N(0x98)]('Registered\x20user\x20'+data['id']+'\x20('+data['type']+')');}catch(J){console['error'](J),process['exitCode']=0x1;}finally{await pg[N(0x99)]();}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
const N=n;function n(s,J){s=s-0x182;const N=W();let O=N[s];return O;}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function W(){const O=['slice','exitCode','log','Password\x20changed\x20for\x20'];W=function(){return O;};return W();}import s from'./services/change-password.js';const [login,password]=process['argv'][N(0x182)](0x2);if(!login||!password)console['error']('Usage:\x20fcore-password\x20<login>\x20<password>'),process[N(0x183)]=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');await s({'userId':user['id'],'password':password},{'pg':pg}),console[N(0x184)](N(0x185)+login);}catch(J){console['error'](J),process['exitCode']=0x1;}finally{await pg['end']();}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
2
|
+
const a=n;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=['logs','audit',a(0x77),'check','access','settings','dictionaries'],RESOURCE_ACTIONS=['read','update','create','delete'],[login,permissionArg]=process[a(0x78)]['slice'](0x2);function n(s,J){s=s-0x77;const N=W();let O=N[s];return O;}function expandPermissions(s){const g=a,J=s['split'](',')['map'](O=>O['trim']())['filter'](Boolean),N=new Set();for(const O of J){if(O[g(0x79)](':')){N[g(0x7a)](O);continue;}const E=O==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const S of E){N['add'](O+':'+S);}}return[...N];}if(!login||!permissionArg)console[a(0x7b)](a(0x7c)),process[a(0x7d)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg[a(0x7e)]('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[a(0x7e)]('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console['log'](a(0x7f)+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission[a(0x80)](':'),actions=byResource[a(0x81)](resource)??[];actions['push'](action),byResource[a(0x82)](resource,actions);}const client=await pg[a(0x83)]();try{await client[a(0x7e)](a(0x84));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[a(0x7e)](a(0x85),[merged,user['id'],row[a(0x86)]]);}else await client['query'](a(0x87),[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(T){await client['query']('ROLLBACK');throw T;}finally{client['release']();}console['log'](a(0x88)+login+':\x20'+permissions['join'](',\x20'));}}catch(f){console[a(0x7b)](f),process['exitCode']=0x1;}finally{await pg['end']();}}function W(){const p=['list','argv','includes','add','error','Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>','exitCode','query','Permissions\x20cleared\x20for\x20','split','get','set','connect','BEGIN','UPDATE\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20actions\x20=\x20$1,\x20updated_by\x20=\x20$2,\x20updated_at\x20=\x20now()\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20access_id\x20=\x20$3','access_id','INSERT\x20INTO\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(\x20resource,\x20actions,\x20user_uid,\x20created_by,\x20updated_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$4)','Granted\x20permissions\x20for\x20'];W=function(){return p;};return W();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import
|
|
1
|
+
import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import s from'./services/get-current-user.js';function W(){const Q=['method','config','twoFactorRedirect','auth','sessionTimeout','session','maxAge','write','permissions','get','credentials','Register','user:create','body','post','/api/auth/password','Changes\x20the\x20password\x20for\x20the\x20current\x20user.','user','/api/auth/logout','fcore','Sign\x20out','audit','sessionId','logout','cookieName','/api/auth/user','query'];W=function(){return Q;};return W();}import J from'./services/registration.js';import N from'./services/change-password.js';import{authSchemas}from'./schema.js';import O from'../../shared/getIP.js';function n(s,J){s=s-0x13e;const N=W();let O=N[s];return O;}import{UnauthorizedError}from'../../errors.js';export function authRoutes(E){return async S=>{const o=n,T=async f=>{const v=n,a=f[v(0x13e)]==='GET'?f['query']:f['body'],g=O(f),p=await verifyUser({...a,'ip':g},E);p['permissions']=await getUserPermissions(p['id'],E);const D=p['twofa']?E[v(0x13f)]['auth'][v(0x140)]:E['config'][v(0x141)]['redirect'];await f['login'](p);const R=E[v(0x13f)]['auth'][v(0x142)]*0x3e8*0x3c;return f[v(0x143)]?.['cookie']&&(f['session']['cookie'][v(0x144)]=R),await f['session']['save'](),await E['audit']?.[v(0x145)]?.({'module':'auth','resource':'session','resourceId':f['session']['sessionId'],'action':'login','userId':p['id'],'ipAddress':g}),{'user':{'id':p['id'],'type':p['type'],'permissions':p[v(0x146)]},'redirectUrl':D};};S[o(0x147)]('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'querystring':authSchemas[o(0x148)]}},T),S['post']('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'body':authSchemas[o(0x148)]}},T),S['post']('/api/auth/registration',{'schema':{'tags':['fcore','auth'],'summary':o(0x149),'description':'Creates\x20a\x20regular\x20user\x20account.','access':'admin','permissions':[o(0x14a)],'body':authSchemas['credentials']}},async f=>J(f[o(0x14b)],E)),S[o(0x14c)](o(0x14d),{'schema':{'tags':['fcore','auth'],'summary':'Change\x20password','description':o(0x14e),'access':o(0x14f),'permissions':[],'body':authSchemas['password']}},async f=>{if(!f['user'])throw new UnauthorizedError('Not\x20authorized');return await N({'userId':f['user']['id'],...f['body']},E),{'success':!![]};}),S['post'](o(0x150),{'schema':{'tags':[o(0x151),'auth'],'summary':o(0x152),'description':'Terminates\x20the\x20current\x20user\x20session.','access':o(0x14f),'permissions':[]}},async(f,a)=>{const i=o,g={'redirectUrl':'/'};if(!f['user'])return g;return await E[i(0x153)]?.[i(0x145)]?.({'module':i(0x141),'resource':'session','resourceId':f['session'][i(0x154)],'action':i(0x155),'userId':f[i(0x14f)]?.['id']}),await f['session']['destroy'](),a['clearCookie'](E['config']['auth'][i(0x156)]),Object['defineProperty'](f,'session',{'value':null,'writable':![],'configurable':![]}),g;}),S['get'](o(0x157),{'schema':{'tags':['fcore','auth'],'summary':'Get\x20current\x20user','description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':o(0x14f),'permissions':[],'querystring':authSchemas['query']}},async f=>s({'user':f[o(0x14f)],'token':f[o(0x158)]['token']}));};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
function W(){const J=['Object'];W=function(){return J;};return W();}const s=n;import{Type}from'@sinclair/typebox';function n(s,J){s=s-0x13a;const N=W();let O=N[s];return O;}export const authSchemas={'query':Type[s(0x13a)]({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type['Object']({'user':Type['String']({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'password':Type[s(0x13a)]({'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'id':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type['Object']({'code':Type['String']({'minLength':0x1})})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:
|
|
1
|
+
import{hashPassword}from'../../../plugins/auth/index.js';function n(s,J){s=s-0x1a9;const N=W();let O=N[s];return O;}export default async function changePassword({id:s,password:J,userId:N},{pg:O}){const S=n,E=await hashPassword(J);await O['query'](S(0x1a9),[E,s||N,N]);}function W(){const T=['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'];W=function(){return T;};return W();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function n(s,J){s=s-0x6e;const N=W();let O=N[s];return O;}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(s){const S=n,{user:J}=s;if(!J)return{};if(s['token']){const {jwtSignToken:N}=await import('../../../plugins/jwt.js'),O=await N(J);J['token']=O;}return J[S(0x6e)]=[...new Set(J?.[S(0x6f)]['map'](E=>E['split'](':')[0x0]))],safeUser(J);}function W(){const T=['resources','permissions'];W=function(){return T;};return W();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';export default async function registration({user:s,password:J,type:N},{pg:O}){const f=n,E=await hashPassword(J),S=await O['query'](f(0x130),[s,E,N||f(0x131)]),T=S['rows'][0x0];if(!T)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':T};}function n(s,J){s=s-0x130;const N=W();let O=N[s];return O;}function W(){const a=['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','regular'];W=function(){return a;};return W();}
|
|
@@ -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(s,J){return unsupported('Two-factor\x20provider');}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function n(s,J){s=s-0x1d8;var N=W();var O=N[s];return O;}var s=n;function W(){var J=['image/jpeg','image/webp','image/tiff','application/msword','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.text','text/csv','application/geo+json','application/x-rar-compressed','application/vnd.rar','application/x-gzip','audio/mp4','video/quicktime','application/octet-stream'];W=function(){return J;};return W();}export default new Set([s(0x1d8),'image/png','image/gif',s(0x1d9),'image/bmp',s(0x1da),'image/svg+xml','image/x-icon','image/avif','application/pdf',s(0x1db),'application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel',s(0x1dc),'application/vnd.ms-powerpoint',s(0x1dd),s(0x1de),'application/vnd.oasis.opendocument.spreadsheet','application/vnd.oasis.opendocument.presentation','text/plain',s(0x1df),'text/markdown','application/json','application/xml','text/xml',s(0x1e0),'application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip','application/x-zip-compressed','application/x-7z-compressed',s(0x1e1),s(0x1e2),'application/gzip',s(0x1e3),'application/x-tar','audio/mpeg','audio/wav','audio/ogg','audio/webm',s(0x1e4),'video/mp4','video/mpeg','video/webm',s(0x1e5),'video/x-msvideo',s(0x1e6)]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';function
|
|
1
|
+
import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';function n(s,J){s=s-0xc6;const N=W();let O=N[s];return O;}function W(){const i=['fcore','Get\x20file\x20by\x20token','fileDownloadQuery','verify','params','application/octet-stream','application/pdf','header','public,\x20max-age=86400,\x20immutable','send','/api/file/upload','files:create','fields','value','resource','/api/file/:token/resize','file','Resize\x20file','Returns\x20a\x20resized\x20image\x20file.','inline'];W=function(){return i;};return W();}import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';export function fileRoutes(s){return async J=>{const D=n;J['get']('/api/file/:token',{'schema':{'tags':[D(0xc6),'file'],'summary':D(0xc7),'description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':'public','permissions':[],'params':fileSchemas['fileToken'],'querystring':fileSchemas[D(0xc8)]}},async(N,O)=>{const R=D,E=s['file'][R(0xc9)](N[R(0xca)]['token']),S=await getFile({'pathOrToken':E},s),T=await fileTypeFromBuffer(S),f=T?.['mime']??R(0xcb),a=N['query']['download']===!![],g=f['startsWith']('image/')||f===R(0xcc),p=E['split']('/')['pop']()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??'file';return O['type'](f),O['header']('Content-Disposition',(a||!g?'attachment':'inline')+';\x20filename=\x22'+p+'\x22')[R(0xcd)]('Cache-Control',R(0xce)),O[R(0xcf)](S);}),J['post'](D(0xd0),{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':[D(0xd1)]}},async N=>{const v=D,O=await N['file']();if(!O)throw new Error('File\x20is\x20required');return uploadFile({'file':O,'metadata':{'name':O['filename'],'path':O[v(0xd2)]['path']?.[v(0xd3)],'resource':O['fields'][v(0xd4)]?.['value'],'resourceId':O[v(0xd2)]['resourceId']?.['value']},'user':N['user']},s);}),J['get'](D(0xd5),{'schema':{'tags':['fcore',D(0xd6)],'summary':D(0xd7),'description':D(0xd8),'access':'user','permissions':['files:read'],'params':fileSchemas['fileToken'],'querystring':fileSchemas['resizeQuery']}},async(N,O)=>{const o=D,E=await resizeFile({'pathOrToken':s['file']?.['verify'](N['params']['token']),...N['query']},s),S=await fileTypeFromBuffer(E);return O['type'](S?.['mime']??'image/png'),O[o(0xcd)]('Content-Disposition',o(0xd9))['header']('Cache-Control','public,\x20max-age=86400,\x20immutable'),O[o(0xcf)](E);});};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
const s=n;function W(){const J=['Object','Optional','Any','String','Integer','Literal'];W=function(){return J;};return W();}import{Type}from'@sinclair/typebox';function n(s,J){s=s-0x160;const N=W();let O=N[s];return O;}export const fileSchemas={'fileId':Type['Object']({'id':Type['String']({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type[s(0x160)]({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type['Object']({'download':Type[s(0x161)](Type['Boolean']())}),'filePath':Type['Object']({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type[s(0x162)](),'metadata':Type['Object']({'name':Type[s(0x161)](Type[s(0x163)]({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type[s(0x161)](Type['String']({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type[s(0x161)](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))}),'resizeQuery':Type[s(0x160)]({'width':Type['Optional'](Type[s(0x164)]({'minimum':0x1,'default':0xc8})),'height':Type[s(0x161)](Type[s(0x164)]({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type['Literal']('cover'),Type['Literal']('contain'),Type[s(0x165)]('fill'),Type['Literal']('inside'),Type['Literal']('outside')]))})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function n(s,J){s=s-0xad;var N=W();var O=N[s];return O;}import{NotFoundError}from'../../../errors.js';function W(){var O=['File\x20not\x20found','pathOrToken'];W=function(){return O;};return W();}export async function getFile(s,J){var N=n;if(!J['file'])throw new Error('empty\x20file');if(!await J['file']['exists'](s['pathOrToken']))throw new NotFoundError(N(0xad)+s['pathOrToken']);return J['file']['get'](s[N(0xae)]);}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NotFoundError,ValidationError}from'../../../errors.js';function
|
|
1
|
+
import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';function n(s,J){s=s-0x1e1;const N=W();let O=N[s];return O;}import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import s from'node:path';import J from'sharp';export async function resizeFile(N,O){const o=n,E=N['pathOrToken']??N['path'];if(!E)throw new ValidationError('File\x20path\x20is\x20required');const S=parseDimension(N[o(0x1e1)],o(0x1e1))??0xc8,T=parseDimension(N['height'],o(0x1e2)),f=createHash('sha256')['update'](E+':'+S+':'+(T??'auto')+':'+(N['fit']??'cover'))['digest'](o(0x1e3)),a=s['resolve']('logs',o(0x1e4)),g=s[o(0x1e5)](a,f+o(0x1e6));try{return await readFile(g);}catch(v){if(v['code']!=='ENOENT')throw v;}if(!await O['file']['exists'](E))throw new NotFoundError(o(0x1e7));const p=await O['file'][o(0x1e8)](E),D=await fileTypeFromBuffer(p);if(!D?.['mime']['startsWith']('image/'))throw new ValidationError(o(0x1e9));const R=await J(p)['resize']({'width':S,'height':T,'fit':N['fit']??'cover'})['toBuffer']();return await mkdir(a,{'recursive':!![]}),await writeFile(g,R),R;}function parseDimension(N,O){const i=n;if(N===undefined||N==='')return undefined;const E=Number(N);if(!Number[i(0x1ea)](E)||E<=0x0)throw new ValidationError(O+i(0x1eb));return E;}function W(){const Q=['width','height','hex','resize','join','.jpg','File\x20not\x20found','get','Only\x20image\x20files\x20can\x20be\x20resized','isInteger','\x20must\x20be\x20a\x20positive\x20integer'];W=function(){return Q;};return W();}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fileTypeFromBuffer}from'file-type';import
|
|
1
|
+
import{fileTypeFromBuffer}from'file-type';import s from'../mime.js';function n(s,J){s=s-0x14a;const N=W();let O=N[s];return O;}function W(){const v=['metadata','slice','padStart','resource','file','Unsupported\x20file\x20type:\x20','mimetype','pop'];W=function(){return v;};return W();}import{randomUUID}from'node:crypto';export async function uploadFile(J,N){const R=n,O=(J[R(0x14a)]['name']??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),E=new Date(),S=String(E['getFullYear']())[R(0x14b)](-0x2),T=String(E['getMonth']()+0x1)['padStart'](0x2,'0'),f=String(E['getDate']())[R(0x14c)](0x2,'0'),a=J['metadata']['path']??(J[R(0x14a)][R(0x14d)]?J['metadata']['resource']+'/'+(J['metadata']['resourceId']??randomUUID())+'/'+O:null)??'uploads/'+S+'/'+T+'-'+f+'/'+O,g=await J[R(0x14e)]['toBuffer'](),p=await fileTypeFromBuffer(g);if(!s['has'](J['file']['mimetype'])&&(p?.['mime']?!s['has'](p['mime']):!![]))throw new Error(R(0x14f)+J['file'][R(0x150)]);await N[R(0x14e)]['put'](a,g);const D=await N['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',[J[R(0x14a)]['resource']??null,J[R(0x14a)]['resourceId']??null,a,J[R(0x14e)]['mimetype'],J['file']['file']['bytesRead'],J['metadata']['name'],O,J['file']['mimetype']['split']('/')[R(0x151)]()??null,J['user']?.['id']??null]);return D['rows'][0x0];}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
function W(){const a=['get','/api/resource/:resource/search','fcore','user','Suggest\x20resource\x20values','params','config','resource','auth','Returns\x20records\x20from\x20a\x20registered\x20resource.','$resource:read','query','/api/resource/:resource/:id','Get\x20resource\x20record','resourceId','Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','delete','Delete\x20resource\x20record','post','/api/resource/:resource/:id/upload','$resource:update','file','File\x20is\x20required','admin','Missing\x20permission:\x20','filename','path','Returns\x20related\x20records\x20for\x20a\x20resource\x20record.','resourceIdRelation','Create\x20resource\x20relation','/api/resource/:resource/:id/:relation/:relationId','resourceIdRelationId','Update\x20resource\x20relation'];W=function(){return a;};return W();}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';function n(s,J){s=s-0x1cb;const N=W();let O=N[s];return O;}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';const user=s=>s['user'];export function resourceRoutes(s){return async J=>{const T=n;J[T(0x1cb)](T(0x1cc),{'schema':{'tags':[T(0x1cd),'resource'],'summary':'Search\x20resource','description':'Searches\x20records\x20in\x20a\x20registered\x20resource.','access':'user','permissions':['$resource:read'],'params':resourceSchemas['resource']}},async N=>searchResource({...N['query'],...N['params'],'user':user(N)||s['config']?.['auth']?.[T(0x1ce)]},s)),J[T(0x1cb)]('/api/suggest/:resource/:field',{'schema':{'tags':['fcore','resource'],'summary':T(0x1cf),'description':'Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','access':'user','permissions':['$resource:read'],'params':resourceSchemas['resourceField'],'querystring':resourceSchemas['suggestQuery']}},async N=>suggestResource({...N['query'],...N[T(0x1d0)],'user':user(N)||s[T(0x1d1)]?.['auth']?.[T(0x1ce)]},s)),J['get']('/api/resource/:resource/export',{'schema':{'tags':['fcore',T(0x1d2)],'summary':'Export\x20resource\x20records','description':'Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','access':T(0x1ce),'permissions':['$resource:read'],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas['exportResourceQuery']}},async N=>exportResource({...N['query'],...N[T(0x1d0)],'user':user(N)||s['config']?.[T(0x1d3)]?.['user']},s)),J['get']('/api/resource/:resource',{'schema':{'tags':['fcore',T(0x1d2)],'summary':'List\x20resource\x20records','description':T(0x1d4),'access':T(0x1ce),'permissions':[T(0x1d5)],'params':resourceSchemas['resource']}},async N=>listResources({...N[T(0x1d6)],...N['params'],'user':user(N)||s[T(0x1d1)]?.['auth']?.['user']},s)),J['post']('/api/resource/:resource',{'schema':{'tags':['fcore','resource'],'summary':'Create\x20resource\x20record','description':'Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':'user','permissions':['$resource:create'],'params':resourceSchemas['resource']}},async N=>createResource({...N['params'],'data':N['body'],'user':user(N)||s['config']?.['auth']?.['user']},s)),J[T(0x1cb)](T(0x1d7),{'schema':{'tags':['fcore','resource'],'summary':T(0x1d8),'description':'Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','access':'user','permissions':['$resource:read'],'params':resourceSchemas[T(0x1d9)],'querystring':resourceSchemas['resourceIncludeQuery']}},async N=>getResource({...N['query'],...N[T(0x1d0)],'user':user(N)||s['config']?.['auth']?.['user']},s)),J['put']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Update\x20resource\x20record','description':T(0x1da),'access':'user','permissions':['$resource:update'],'params':resourceSchemas['resourceId']}},async N=>updateResource({...N['params'],'patch':N['body'],'user':user(N)||s[T(0x1d1)]?.[T(0x1d3)]?.['user']},s)),J[T(0x1db)]('/api/resource/:resource/:id',{'schema':{'tags':[T(0x1cd),T(0x1d2)],'summary':T(0x1dc),'description':'Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','access':T(0x1ce),'permissions':['$resource:delete'],'params':resourceSchemas['resourceId']}},async N=>deleteResource({...N['params'],'user':user(N)||s[T(0x1d1)]?.[T(0x1d3)]?.[T(0x1ce)]},s)),J[T(0x1dd)](T(0x1de),{'schema':{'tags':['fcore',T(0x1d2)],'summary':'Upload\x20resource\x20file','description':'Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','access':T(0x1ce),'permissions':[T(0x1df)],'params':resourceSchemas['uploadResourceFile']}},async N=>{const f=T,O=await N[f(0x1e0)]();if(!O)throw new Error(f(0x1e1));const E=N[f(0x1d0)]['resource'],S=N[f(0x1d0)]['id'];if(N[f(0x1ce)]?.['type']!==f(0x1e2)&&!N[f(0x1ce)]?.['permissions']['includes'](E+':update'))throw new ForbiddenError(f(0x1e3)+E+':update');return uploadFile({'file':O,'metadata':{'name':O[f(0x1e4)],'path':O['fields'][f(0x1e5)]?.['value'],'resource':E,'resourceId':S},'user':N['user']},s);}),J['get']('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore','resource'],'summary':'List\x20resource\x20relations','description':T(0x1e6),'access':T(0x1ce),'params':resourceSchemas[T(0x1e7)],'permissions':[T(0x1d5)]}},async N=>listResourceRelation({...N['query'],...N['params'],'user':user(N)||s['config']?.['auth']?.['user']},s)),J['post']('/api/resource/:resource/:id/:relation',{'schema':{'tags':[T(0x1cd),'resource'],'summary':T(0x1e8),'description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':'user','permissions':['$resource:create'],'params':resourceSchemas['resourceIdRelation']}},async N=>createResourceRelation({...N[T(0x1d0)],'data':N['body'],'user':user(N)||s['config']?.[T(0x1d3)]?.[T(0x1ce)]},s)),J[T(0x1db)](T(0x1e9),{'schema':{'tags':[T(0x1cd),'resource'],'summary':'Delete\x20resource\x20relation','description':'Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','access':'user','permissions':['$resource:delete'],'params':resourceSchemas[T(0x1ea)]}},async N=>deleteResourceRelation({...N[T(0x1d0)],'user':user(N)||s['config']?.[T(0x1d3)]?.[T(0x1ce)]},s)),J['put'](T(0x1e9),{'schema':{'tags':['fcore','resource'],'summary':T(0x1eb),'description':'Updates\x20a\x20related\x20resource\x20record.','access':'user','permissions':[T(0x1df)],'params':resourceSchemas[T(0x1ea)]}},async N=>updateResourceRelation({...N['params'],'data':N['body'],'user':user(N)||s['config']?.['auth']?.['user']},s));};}
|