Compare commits

...

32 Commits

Author SHA1 Message Date
standardci
ed1a708c40 chore(release): publish new version
- @standardnotes/analytics@2.24.7
 - @standardnotes/api-gateway@1.65.4
 - @standardnotes/auth-server@1.122.1
 - @standardnotes/domain-core@1.21.0
 - @standardnotes/event-store@1.11.4
 - @standardnotes/files-server@1.19.4
 - @standardnotes/home-server@1.11.27
 - @standardnotes/revisions-server@1.23.8
 - @standardnotes/scheduler-server@1.20.6
 - @standardnotes/settings@1.21.11
 - @standardnotes/syncing-server@1.54.0
 - @standardnotes/websockets-server@1.9.7
2023-07-06 09:34:50 +00:00
Karol Sójko
e905128d45 feat: getting shared vault users and removing shared vault user (#642)
* feat: getting shared vault users.

Co-authored-by: Mo <mo@standardnotes.com>

* feat: removing shared vault user.

Co-authored-by: Mo <mo@standardnotes.com>

---------

Co-authored-by: Mo <mo@standardnotes.com>
2023-07-06 11:18:06 +02:00
standardci
fd598f372a chore(release): publish new version
- @standardnotes/home-server@1.11.26
 - @standardnotes/syncing-server@1.53.0
2023-07-05 13:33:44 +00:00
Karol Sójko
7a3946a9e2 feat: http controllers for shared vaults. (#641)
Co-authored-by: Mo <mo@standardnotes.com>
2023-07-05 15:17:43 +02:00
standardci
cbdd2584d0 chore(release): publish new version
- @standardnotes/analytics@2.24.6
 - @standardnotes/api-gateway@1.65.3
 - @standardnotes/auth-server@1.122.0
 - @standardnotes/domain-core@1.20.0
 - @standardnotes/domain-events-infra@1.12.8
 - @standardnotes/domain-events@2.113.0
 - @standardnotes/event-store@1.11.3
 - @standardnotes/files-server@1.19.3
 - @standardnotes/home-server@1.11.25
 - @standardnotes/revisions-server@1.23.7
 - @standardnotes/scheduler-server@1.20.5
 - @standardnotes/settings@1.21.10
 - @standardnotes/syncing-server@1.52.0
 - @standardnotes/websockets-server@1.9.6
2023-07-05 11:59:55 +00:00
Karol Sójko
f3161c2712 feat: deleting shared vaults. (#640)
Co-authored-by: Mo <mo@standardnotes.com>
2023-07-05 13:45:49 +02:00
standardci
148542dd5a chore(release): publish new version
- @standardnotes/home-server@1.11.24
 - @standardnotes/syncing-server@1.51.0
2023-07-05 09:17:53 +00:00
Karol Sójko
d2b2c339f2 feat: add getting shared vaults for a user (#639) 2023-07-05 11:01:21 +02:00
standardci
d2578c48f0 chore(release): publish new version
- @standardnotes/auth-server@1.121.0
 - @standardnotes/home-server@1.11.23
2023-07-05 08:21:19 +00:00
Karol Sójko
fecfd54728 feat(auth): add notifications model (#638) 2023-07-05 10:03:01 +02:00
Karol Sójko
17e4162d3e Revert "fix: unplug node-gyp based deps (#637)"
This reverts commit 742209d773.
2023-07-04 12:56:10 +02:00
Karol Sójko
742209d773 fix: unplug node-gyp based deps (#637) 2023-07-04 10:42:44 +02:00
standardci
1fa4b7cf27 chore(release): publish new version
- @standardnotes/home-server@1.11.22
 - @standardnotes/syncing-server@1.50.0
2023-07-03 17:55:21 +00:00
Karol Sójko
5dc5507039 feat: add invite users to a shared vault. (#636)
Co-authored-by: Mo <mo@standardnotes.com>
2023-07-03 19:40:36 +02:00
standardci
3035a20b9f chore(release): publish new version
- @standardnotes/home-server@1.11.21
 - @standardnotes/syncing-server@1.49.0
2023-07-03 16:58:01 +00:00
Karol Sójko
04b3bb034f feat: add creating shared vault file valet tokens. (#635)
Co-authored-by: Mo <mo@standardnotes.com>
2023-07-03 18:43:32 +02:00
standardci
bf84be0136 chore(release): publish new version
- @standardnotes/home-server@1.11.20
 - @standardnotes/syncing-server@1.48.0
2023-07-03 10:14:10 +00:00
Karol Sójko
890cf48749 feat: add shared vault invite model. (#634)
Co-authored-by: Mo <mo@standardnotes.com>
2023-07-03 11:54:52 +02:00
standardci
2b3436c6ce chore(release): publish new version
- @standardnotes/home-server@1.11.19
 - @standardnotes/syncing-server@1.47.0
2023-06-30 13:25:38 +00:00
Karol Sójko
4df8c3b2e5 feat: add use case for creating shared vaults and adding users to it. (#633)
Co-authored-by: Mo <mo@standardnotes.com>
2023-06-30 15:11:12 +02:00
standardci
25a2696c32 chore(release): publish new version
- @standardnotes/home-server@1.11.18
 - @standardnotes/syncing-server@1.46.0
2023-06-30 11:33:49 +00:00
Karol Sójko
52f879f842 feat: add shared vaults user model. (#632)
Co-authored-by: Mo <mo@standardnotes.com>
2023-06-30 13:19:31 +02:00
standardci
4f70fa156d chore(release): publish new version
- @standardnotes/analytics@2.24.5
 - @standardnotes/api-gateway@1.65.2
 - @standardnotes/auth-server@1.120.2
 - @standardnotes/domain-core@1.19.0
 - @standardnotes/event-store@1.11.2
 - @standardnotes/files-server@1.19.2
 - @standardnotes/home-server@1.11.17
 - @standardnotes/revisions-server@1.23.6
 - @standardnotes/scheduler-server@1.20.4
 - @standardnotes/settings@1.21.9
 - @standardnotes/syncing-server@1.45.0
 - @standardnotes/websockets-server@1.9.5
2023-06-30 11:00:32 +00:00
Karol Sójko
38e77f04be feat: add shared vaults model. (#631)
Co-authored-by: Mo <mo@standardnotes.com>
2023-06-30 12:44:27 +02:00
standardci
060206ddd4 chore(release): publish new version
- @standardnotes/analytics@2.24.4
 - @standardnotes/api-gateway@1.65.1
 - @standardnotes/auth-server@1.120.1
 - @standardnotes/domain-events-infra@1.12.7
 - @standardnotes/domain-events@2.112.1
 - @standardnotes/event-store@1.11.1
 - @standardnotes/files-server@1.19.1
 - @standardnotes/home-server@1.11.16
 - @standardnotes/revisions-server@1.23.5
 - @standardnotes/scheduler-server@1.20.3
 - @standardnotes/security@1.8.1
 - @standardnotes/syncing-server@1.44.6
 - @standardnotes/websockets-server@1.9.4
2023-06-30 10:24:00 +00:00
Mo
0bc0909386 chore: types lint (#630) 2023-06-30 05:07:47 -05:00
standardci
667d528a8c chore(release): publish new version
- @standardnotes/analytics@2.24.3
 - @standardnotes/api-gateway@1.65.0
 - @standardnotes/auth-server@1.120.0
 - @standardnotes/common@1.49.0
 - @standardnotes/domain-events-infra@1.12.6
 - @standardnotes/domain-events@2.112.0
 - @standardnotes/event-store@1.11.0
 - @standardnotes/files-server@1.19.0
 - @standardnotes/home-server@1.11.15
 - @standardnotes/revisions-server@1.23.4
 - @standardnotes/scheduler-server@1.20.2
 - @standardnotes/security@1.8.0
 - @standardnotes/syncing-server@1.44.5
 - @standardnotes/websockets-server@1.9.3
2023-06-30 09:47:02 +00:00
Karol Sójko
fa7fbe26e7 feat: shared vaults functionality in api-gateway,auth,files,common,security,domain-events. (#629)
Co-authored-by: Mo <mo@standardnotes.com>
2023-06-30 11:31:25 +02:00
standardci
ba422a29d0 chore(release): publish new version
- @standardnotes/auth-server@1.119.6
 - @standardnotes/home-server@1.11.14
2023-06-28 16:11:23 +00:00
Karol Sójko
d220ec5bf7 fix(auth): add debug logs for authentication method resolver 2023-06-28 17:56:59 +02:00
standardci
7baf5492bc chore(release): publish new version
- @standardnotes/api-gateway@1.64.3
 - @standardnotes/auth-server@1.119.5
 - @standardnotes/home-server@1.11.13
 - @standardnotes/syncing-server@1.44.4
2023-06-28 12:45:50 +00:00
Karol Sójko
d5a8409bb5 fix: add debug logs for invalid-auth responses 2023-06-28 14:30:39 +02:00
201 changed files with 4553 additions and 249 deletions

3
.pnp.cjs generated
View File

@@ -5179,6 +5179,7 @@ const RAW_RUNTIME_STATE =
["@standardnotes/responses", "npm:1.13.24"],\
["@standardnotes/security", "workspace:packages/security"],\
["@standardnotes/settings", "workspace:packages/settings"],\
["@standardnotes/sncrypto-node", "workspace:packages/sncrypto-node"],\
["@standardnotes/time", "workspace:packages/time"],\
["@types/cors", "npm:2.8.13"],\
["@types/dotenv", "npm:8.2.0"],\
@@ -5188,6 +5189,7 @@ const RAW_RUNTIME_STATE =
["@types/newrelic", "npm:9.14.0"],\
["@types/node", "npm:20.2.5"],\
["@types/prettyjson", "npm:0.0.30"],\
["@types/semver", "npm:7.5.0"],\
["@types/ua-parser-js", "npm:0.7.36"],\
["@types/uuid", "npm:8.3.4"],\
["@typescript-eslint/eslint-plugin", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:5.59.8"],\
@@ -5210,6 +5212,7 @@ const RAW_RUNTIME_STATE =
["prettier", "npm:2.8.8"],\
["prettyjson", "npm:1.2.5"],\
["reflect-metadata", "npm:0.1.13"],\
["semver", "npm:7.5.1"],\
["sqlite3", "virtual:31b5a94a105c89c9294c3d524a7f8929fe63ee5a2efadf21951ca4c0cfd2ecf02e8f4ef5a066bbda091f1e3a56e57c6749069a080618c96b22e51131a330fc4a#npm:5.1.6"],\
["ts-jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.0"],\
["typeorm", "virtual:365b8c88cdf194291829ee28b79556e2328175d26a621363e703848100bea0042e9500db2a1206c9bbc3a4a76a1d169639ef774b2ea3a1a98584a9936b58c6be#npm:0.3.16"],\

View File

@@ -3,6 +3,26 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [2.24.7](https://github.com/standardnotes/server/compare/@standardnotes/analytics@2.24.6...@standardnotes/analytics@2.24.7) (2023-07-06)
**Note:** Version bump only for package @standardnotes/analytics
## [2.24.6](https://github.com/standardnotes/server/compare/@standardnotes/analytics@2.24.5...@standardnotes/analytics@2.24.6) (2023-07-05)
**Note:** Version bump only for package @standardnotes/analytics
## [2.24.5](https://github.com/standardnotes/server/compare/@standardnotes/analytics@2.24.4...@standardnotes/analytics@2.24.5) (2023-06-30)
**Note:** Version bump only for package @standardnotes/analytics
## [2.24.4](https://github.com/standardnotes/server/compare/@standardnotes/analytics@2.24.3...@standardnotes/analytics@2.24.4) (2023-06-30)
**Note:** Version bump only for package @standardnotes/analytics
## [2.24.3](https://github.com/standardnotes/server/compare/@standardnotes/analytics@2.24.2...@standardnotes/analytics@2.24.3) (2023-06-30)
**Note:** Version bump only for package @standardnotes/analytics
## [2.24.2](https://github.com/standardnotes/server/compare/@standardnotes/analytics@2.24.1...@standardnotes/analytics@2.24.2) (2023-06-28)
**Note:** Version bump only for package @standardnotes/analytics

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/analytics",
"version": "2.24.2",
"version": "2.24.7",
"engines": {
"node": ">=18.0.0 <21.0.0"
},

View File

@@ -3,6 +3,34 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.65.4](https://github.com/standardnotes/api-gateway/compare/@standardnotes/api-gateway@1.65.3...@standardnotes/api-gateway@1.65.4) (2023-07-06)
**Note:** Version bump only for package @standardnotes/api-gateway
## [1.65.3](https://github.com/standardnotes/api-gateway/compare/@standardnotes/api-gateway@1.65.2...@standardnotes/api-gateway@1.65.3) (2023-07-05)
**Note:** Version bump only for package @standardnotes/api-gateway
## [1.65.2](https://github.com/standardnotes/api-gateway/compare/@standardnotes/api-gateway@1.65.1...@standardnotes/api-gateway@1.65.2) (2023-06-30)
**Note:** Version bump only for package @standardnotes/api-gateway
## [1.65.1](https://github.com/standardnotes/api-gateway/compare/@standardnotes/api-gateway@1.65.0...@standardnotes/api-gateway@1.65.1) (2023-06-30)
**Note:** Version bump only for package @standardnotes/api-gateway
# [1.65.0](https://github.com/standardnotes/api-gateway/compare/@standardnotes/api-gateway@1.64.3...@standardnotes/api-gateway@1.65.0) (2023-06-30)
### Features
* shared vaults functionality in api-gateway,auth,files,common,security,domain-events. ([#629](https://github.com/standardnotes/api-gateway/issues/629)) ([fa7fbe2](https://github.com/standardnotes/api-gateway/commit/fa7fbe26e7b0707fc21d71e04af76870f5248baf))
## [1.64.3](https://github.com/standardnotes/api-gateway/compare/@standardnotes/api-gateway@1.64.2...@standardnotes/api-gateway@1.64.3) (2023-06-28)
### Bug Fixes
* add debug logs for invalid-auth responses ([d5a8409](https://github.com/standardnotes/api-gateway/commit/d5a8409bb5d35b9caf410a36ea0d5cb747129e8d))
## [1.64.2](https://github.com/standardnotes/api-gateway/compare/@standardnotes/api-gateway@1.64.1...@standardnotes/api-gateway@1.64.2) (2023-06-22)
### Bug Fixes

View File

@@ -16,6 +16,8 @@ import '../src/Controller/v1/OfflineController'
import '../src/Controller/v1/FilesController'
import '../src/Controller/v1/SubscriptionInvitesController'
import '../src/Controller/v1/AuthenticatorsController'
import '../src/Controller/v1/AsymmetricMessagesController'
import '../src/Controller/v1/SharedVaultsController'
import '../src/Controller/v2/PaymentsControllerV2'
import '../src/Controller/v2/ActionsControllerV2'
@@ -45,28 +47,29 @@ void container.load().then((container) => {
response.setHeader('X-API-Gateway-Version', container.get(TYPES.VERSION))
next()
})
/* eslint-disable */
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["https: 'self'"],
baseUri: ["'self'"],
childSrc: ["*", "blob:"],
connectSrc: ["*"],
fontSrc: ["*", "'self'"],
formAction: ["'self'"],
frameAncestors: ["*", "*.standardnotes.org", "*.standardnotes.com"],
frameSrc: ["*", "blob:"],
imgSrc: ["'self'", "*", "data:"],
manifestSrc: ["'self'"],
mediaSrc: ["'self'"],
objectSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'"]
}
}
}))
/* eslint-enable */
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["https: 'self'"],
baseUri: ["'self'"],
childSrc: ['*', 'blob:'],
connectSrc: ['*'],
fontSrc: ['*', "'self'"],
formAction: ["'self'"],
frameAncestors: ['*', '*.standardnotes.org', '*.standardnotes.com'],
frameSrc: ['*', 'blob:'],
imgSrc: ["'self'", '*', 'data:'],
manifestSrc: ["'self'"],
mediaSrc: ["'self'"],
objectSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'"],
},
},
}),
)
app.use(json({ limit: '50mb' }))
app.use(
text({

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/api-gateway",
"version": "1.64.2",
"version": "1.65.4",
"engines": {
"node": ">=18.0.0 <21.0.0"
},

View File

@@ -17,7 +17,7 @@ export abstract class AuthMiddleware extends BaseMiddleware {
private crossServiceTokenCacheTTL: number,
private crossServiceTokenCache: CrossServiceTokenCacheInterface,
private timer: TimerInterface,
private logger: Logger,
protected logger: Logger,
) {
super()
}

View File

@@ -42,6 +42,8 @@ export class RequiredCrossServiceTokenMiddleware extends AuthMiddleware {
_next: NextFunction,
): boolean {
if (!authHeaderValue) {
this.logger.debug('Missing auth header')
response.status(401).send({
error: {
tag: 'invalid-auth',

View File

@@ -4,6 +4,7 @@ export * from './SubscriptionTokenAuthMiddleware'
export * from './TokenAuthenticationMethod'
export * from './WebSocketAuthMiddleware'
export * from './v1/ActionsController'
export * from './v1/AsymmetricMessagesController'
export * from './v1/AuthenticatorsController'
export * from './v1/FilesController'
export * from './v1/InvoicesController'
@@ -12,6 +13,7 @@ export * from './v1/OfflineController'
export * from './v1/PaymentsController'
export * from './v1/RevisionsController'
export * from './v1/SessionsController'
export * from './v1/SharedVaultsController'
export * from './v1/SubscriptionInvitesController'
export * from './v1/TokensController'
export * from './v1/UsersController'

View File

@@ -0,0 +1,17 @@
import { Request, Response } from 'express'
import { inject } from 'inversify'
import { BaseHttpController, controller, all } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types'
import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
@controller('/v1/asymmetric-messages')
export class AsymmetricMessagesController extends BaseHttpController {
constructor(@inject(TYPES.ServiceProxy) private serviceProxy: ServiceProxyInterface) {
super()
}
@all('*', TYPES.RequiredCrossServiceTokenMiddleware)
async subscriptions(request: Request, response: Response): Promise<void> {
await this.serviceProxy.callSyncingServer(request, response, request.path.replace('/v1/', ''), request.body)
}
}

View File

@@ -0,0 +1,17 @@
import { Request, Response } from 'express'
import { inject } from 'inversify'
import { BaseHttpController, controller, all } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types'
import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
@controller('/v1/shared-vaults')
export class SharedVaultsController extends BaseHttpController {
constructor(@inject(TYPES.ServiceProxy) private serviceProxy: ServiceProxyInterface) {
super()
}
@all('*', TYPES.RequiredCrossServiceTokenMiddleware)
async subscriptions(request: Request, response: Response): Promise<void> {
await this.serviceProxy.callSyncingServer(request, response, request.path.replace('/v1/', ''), request.body)
}
}

View File

@@ -3,6 +3,48 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.122.1](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.122.0...@standardnotes/auth-server@1.122.1) (2023-07-06)
**Note:** Version bump only for package @standardnotes/auth-server
# [1.122.0](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.121.0...@standardnotes/auth-server@1.122.0) (2023-07-05)
### Features
* deleting shared vaults. ([#640](https://github.com/standardnotes/server/issues/640)) ([f3161c2](https://github.com/standardnotes/server/commit/f3161c271296159331639814b2dbb2e566cc54c9))
# [1.121.0](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.120.2...@standardnotes/auth-server@1.121.0) (2023-07-05)
### Features
* **auth:** add notifications model ([#638](https://github.com/standardnotes/server/issues/638)) ([fecfd54](https://github.com/standardnotes/server/commit/fecfd5472824b5adae708db95d351e4ad65ee87b))
## [1.120.2](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.120.1...@standardnotes/auth-server@1.120.2) (2023-06-30)
**Note:** Version bump only for package @standardnotes/auth-server
## [1.120.1](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.120.0...@standardnotes/auth-server@1.120.1) (2023-06-30)
**Note:** Version bump only for package @standardnotes/auth-server
# [1.120.0](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.119.6...@standardnotes/auth-server@1.120.0) (2023-06-30)
### Features
* shared vaults functionality in api-gateway,auth,files,common,security,domain-events. ([#629](https://github.com/standardnotes/server/issues/629)) ([fa7fbe2](https://github.com/standardnotes/server/commit/fa7fbe26e7b0707fc21d71e04af76870f5248baf))
## [1.119.6](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.119.5...@standardnotes/auth-server@1.119.6) (2023-06-28)
### Bug Fixes
* **auth:** add debug logs for authentication method resolver ([d220ec5](https://github.com/standardnotes/server/commit/d220ec5bf7509f9eb19dcda71c3667aaf388a35b))
## [1.119.5](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.119.4...@standardnotes/auth-server@1.119.5) (2023-06-28)
### Bug Fixes
* add debug logs for invalid-auth responses ([d5a8409](https://github.com/standardnotes/server/commit/d5a8409bb5d35b9caf410a36ea0d5cb747129e8d))
## [1.119.4](https://github.com/standardnotes/server/compare/@standardnotes/auth-server@1.119.3...@standardnotes/auth-server@1.119.4) (2023-06-28)
**Note:** Version bump only for package @standardnotes/auth-server

Binary file not shown.

View File

@@ -0,0 +1,16 @@
import { MigrationInterface, QueryRunner } from 'typeorm'
export class AddNotifications1688540448427 implements MigrationInterface {
name = 'AddNotifications1688540448427'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
'CREATE TABLE `notifications` (`uuid` varchar(36) NOT NULL, `user_uuid` varchar(36) NOT NULL, `type` varchar(36) NOT NULL, `payload` text NOT NULL, `created_at_timestamp` bigint NOT NULL, `updated_at_timestamp` bigint NOT NULL, INDEX `index_notifications_on_user_uuid` (`user_uuid`), PRIMARY KEY (`uuid`)) ENGINE=InnoDB',
)
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('DROP INDEX `index_notifications_on_user_uuid` ON `notifications`')
await queryRunner.query('DROP TABLE `notifications`')
}
}

View File

@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm'
export class AddNotifications1688540623272 implements MigrationInterface {
name = 'AddNotifications1688540623272'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
'CREATE TABLE "notifications" ("uuid" varchar PRIMARY KEY NOT NULL, "user_uuid" varchar(36) NOT NULL, "type" varchar(36) NOT NULL, "payload" text NOT NULL, "created_at_timestamp" bigint NOT NULL, "updated_at_timestamp" bigint NOT NULL)',
)
await queryRunner.query('CREATE INDEX "index_notifications_on_user_uuid" ON "notifications" ("user_uuid") ')
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('DROP INDEX "index_notifications_on_user_uuid"')
await queryRunner.query('DROP TABLE "notifications"')
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/auth-server",
"version": "1.119.4",
"version": "1.122.1",
"engines": {
"node": ">=18.0.0 <21.0.0"
},
@@ -32,7 +32,8 @@
"weekly-backup:email": "yarn node dist/bin/backup.js email weekly",
"content-recalculation": "yarn node dist/bin/content.js",
"typeorm": "typeorm-ts-node-commonjs",
"upgrade:snjs": "yarn ncu -u '@standardnotes/*'"
"upgrade:snjs": "yarn ncu -u '@standardnotes/*'",
"migrate": "yarn build && yarn typeorm migration:run -d dist/src/Bootstrap/DataSource.js"
},
"dependencies": {
"@aws-sdk/client-sns": "^3.332.0",

View File

@@ -18,21 +18,26 @@ import { TypeORMEmergencyAccessInvitation } from '../Infra/TypeORM/TypeORMEmerge
import { TypeORMSessionTrace } from '../Infra/TypeORM/TypeORMSessionTrace'
import { Env } from './Env'
import { SqliteConnectionOptions } from 'typeorm/driver/sqlite/SqliteConnectionOptions'
import { TypeORMNotification } from '../Infra/TypeORM/TypeORMNotification'
export class AppDataSource {
private dataSource: DataSource | undefined
private _dataSource: DataSource | undefined
constructor(private env: Env) {}
getRepository<Entity extends ObjectLiteral>(target: EntityTarget<Entity>): Repository<Entity> {
if (!this.dataSource) {
if (!this._dataSource) {
throw new Error('DataSource not initialized')
}
return this.dataSource.getRepository(target)
return this._dataSource.getRepository(target)
}
async initialize(): Promise<void> {
await this.dataSource.initialize()
}
get dataSource(): DataSource {
this.env.load()
const isConfiguredForMySQL = this.env.get('DB_TYPE') === 'mysql'
@@ -60,6 +65,7 @@ export class AppDataSource {
TypeORMAuthenticatorChallenge,
TypeORMEmergencyAccessInvitation,
TypeORMCacheEntry,
TypeORMNotification,
],
migrations: [`${__dirname}/../../migrations/${isConfiguredForMySQL ? 'mysql' : 'sqlite'}/*.js`],
migrationsRun: true,
@@ -104,7 +110,7 @@ export class AppDataSource {
database: inReplicaMode ? undefined : this.env.get('DB_DATABASE'),
}
this.dataSource = new DataSource(mySQLDataSourceOptions)
this._dataSource = new DataSource(mySQLDataSourceOptions)
} else {
const sqliteDataSourceOptions: SqliteConnectionOptions = {
...commonDataSourceOptions,
@@ -112,9 +118,9 @@ export class AppDataSource {
database: this.env.get('DB_SQLITE_DATABASE_PATH'),
}
this.dataSource = new DataSource(sqliteDataSourceOptions)
this._dataSource = new DataSource(sqliteDataSourceOptions)
}
await this.dataSource.initialize()
return this._dataSource
}
}

View File

@@ -0,0 +1,7 @@
import { AppDataSource } from './DataSource'
import { Env } from './Env'
const env: Env = new Env()
env.load()
export const MigrationsDataSource = new AppDataSource(env).dataSource

View File

@@ -1,9 +1,5 @@
import { ProtocolVersion } from '@standardnotes/common'
import { SimpleUserProjection } from '../../Projection/SimpleUserProjection'
export interface AuthResponse {
user: {
uuid: string
email: string
protocolVersion: ProtocolVersion
}
user: SimpleUserProjection
}

View File

@@ -4,13 +4,13 @@ import {
TokenEncoderInterface,
} from '@standardnotes/security'
import { DomainEventPublisherInterface } from '@standardnotes/domain-events'
import { ProtocolVersion } from '@standardnotes/common'
import { SessionBody } from '@standardnotes/responses'
import { inject, injectable } from 'inversify'
import { Logger } from 'winston'
import TYPES from '../../Bootstrap/Types'
import { ProjectorInterface } from '../../Projection/ProjectorInterface'
import { SimpleUserProjection } from '../../Projection/SimpleUserProjection'
import { SessionServiceInterface } from '../Session/SessionServiceInterface'
import { KeyParamsFactoryInterface } from '../User/KeyParamsFactoryInterface'
import { User } from '../User/User'
@@ -54,11 +54,7 @@ export class AuthResponseFactory20200115 extends AuthResponseFactory20190520 {
return {
session: sessionPayload,
key_params: this.keyParamsFactory.create(dto.user, true),
user: this.userProjector.projectSimple(dto.user) as {
uuid: string
email: string
protocolVersion: ProtocolVersion
},
user: this.userProjector.projectSimple(dto.user) as SimpleUserProjection,
}
}

View File

@@ -9,6 +9,7 @@ import { User } from '../User/User'
import { UserRepositoryInterface } from '../User/UserRepositoryInterface'
import { AuthenticationMethodResolver } from './AuthenticationMethodResolver'
import { Logger } from 'winston'
describe('AuthenticationMethodResolver', () => {
let userRepository: UserRepositoryInterface
@@ -18,11 +19,15 @@ describe('AuthenticationMethodResolver', () => {
let user: User
let session: Session
let revokedSession: RevokedSession
let logger: Logger
const createResolver = () =>
new AuthenticationMethodResolver(userRepository, sessionService, sessionTokenDecoder, fallbackTokenDecoder)
new AuthenticationMethodResolver(userRepository, sessionService, sessionTokenDecoder, fallbackTokenDecoder, logger)
beforeEach(() => {
logger = {} as jest.Mocked<Logger>
logger.debug = jest.fn()
user = {} as jest.Mocked<User>
session = {} as jest.Mocked<Session>

View File

@@ -5,6 +5,7 @@ import { SessionServiceInterface } from '../Session/SessionServiceInterface'
import { UserRepositoryInterface } from '../User/UserRepositoryInterface'
import { AuthenticationMethod } from './AuthenticationMethod'
import { AuthenticationMethodResolverInterface } from './AuthenticationMethodResolverInterface'
import { Logger } from 'winston'
@injectable()
export class AuthenticationMethodResolver implements AuthenticationMethodResolverInterface {
@@ -14,15 +15,20 @@ export class AuthenticationMethodResolver implements AuthenticationMethodResolve
@inject(TYPES.Auth_SessionTokenDecoder) private sessionTokenDecoder: TokenDecoderInterface<SessionTokenData>,
@inject(TYPES.Auth_FallbackSessionTokenDecoder)
private fallbackSessionTokenDecoder: TokenDecoderInterface<SessionTokenData>,
@inject(TYPES.Auth_Logger) private logger: Logger,
) {}
async resolve(token: string): Promise<AuthenticationMethod | undefined> {
let decodedToken: SessionTokenData | undefined = this.sessionTokenDecoder.decodeToken(token)
if (decodedToken === undefined) {
this.logger.debug('Could not decode token with primary decoder, trying fallback decoder.')
decodedToken = this.fallbackSessionTokenDecoder.decodeToken(token)
}
if (decodedToken) {
this.logger.debug('Token decoded successfully. User found.')
return {
type: 'jwt',
user: await this.userRepository.findOneByUuid(<string>decodedToken.user_uuid),
@@ -32,6 +38,8 @@ export class AuthenticationMethodResolver implements AuthenticationMethodResolve
const session = await this.sessionService.getSessionFromToken(token)
if (session) {
this.logger.debug('Token decoded successfully. Session found.')
return {
type: 'session_token',
user: await this.userRepository.findOneByUuid(session.userUuid),
@@ -41,6 +49,8 @@ export class AuthenticationMethodResolver implements AuthenticationMethodResolve
const revokedSession = await this.sessionService.getRevokedSessionFromToken(token)
if (revokedSession) {
this.logger.debug('Token decoded successfully. Revoked session found.')
return {
type: 'revoked',
revokedSession: await this.sessionService.markRevokedSessionAsReceived(revokedSession),
@@ -48,6 +58,8 @@ export class AuthenticationMethodResolver implements AuthenticationMethodResolve
}
}
this.logger.debug('Could not decode token.')
return undefined
}
}

View File

@@ -0,0 +1,17 @@
import { NotificationType, Timestamps, Uuid } from '@standardnotes/domain-core'
import { Notification } from './Notification'
describe('Notification', () => {
it('should create an entity', () => {
const entityOrError = Notification.create({
timestamps: Timestamps.create(123456789, 123456789).getValue(),
userUuid: Uuid.create('00000000-0000-0000-0000-000000000000').getValue(),
payload: 'payload',
type: NotificationType.create(NotificationType.TYPES.SharedVaultItemRemoved).getValue(),
})
expect(entityOrError.isFailed()).toBeFalsy()
expect(entityOrError.getValue().id).not.toBeNull()
})
})

View File

@@ -0,0 +1,17 @@
import { Entity, Result, UniqueEntityId } from '@standardnotes/domain-core'
import { NotificationProps } from './NotificationProps'
export class Notification extends Entity<NotificationProps> {
get id(): UniqueEntityId {
return this._id
}
private constructor(props: NotificationProps, id?: UniqueEntityId) {
super(props, id)
}
static create(props: NotificationProps, id?: UniqueEntityId): Result<Notification> {
return Result.ok<Notification>(new Notification(props, id))
}
}

View File

@@ -0,0 +1,8 @@
import { NotificationType, Timestamps, Uuid } from '@standardnotes/domain-core'
export interface NotificationProps {
userUuid: Uuid
type: NotificationType
payload: string
timestamps: Timestamps
}

View File

@@ -37,7 +37,7 @@ describe('SettingService', () => {
user = {
uuid: '4-5-6',
} as jest.Mocked<User>
user.isPotentiallyAVaultAccount = jest.fn().mockReturnValue(false)
user.isPotentiallyAPrivateUsernameAccount = jest.fn().mockReturnValue(false)
setting = {
name: SettingName.NAMES.DropboxBackupToken,
@@ -66,7 +66,7 @@ describe('SettingService', () => {
]),
)
settingsAssociationService.getDefaultSettingsAndValuesForNewVaultAccount = jest.fn().mockReturnValue(
settingsAssociationService.getDefaultSettingsAndValuesForNewPrivateUsernameAccount = jest.fn().mockReturnValue(
new Map([
[
SettingName.NAMES.LogSessionUserAgent,
@@ -98,7 +98,7 @@ describe('SettingService', () => {
})
it('should create default settings for a newly registered vault account', async () => {
user.isPotentiallyAVaultAccount = jest.fn().mockReturnValue(true)
user.isPotentiallyAPrivateUsernameAccount = jest.fn().mockReturnValue(true)
await createService().applyDefaultSettingsUponRegistration(user)

View File

@@ -28,8 +28,9 @@ export class SettingService implements SettingServiceInterface {
async applyDefaultSettingsUponRegistration(user: User): Promise<void> {
let defaultSettingsWithValues = this.settingsAssociationService.getDefaultSettingsAndValuesForNewUser()
if (user.isPotentiallyAVaultAccount()) {
defaultSettingsWithValues = this.settingsAssociationService.getDefaultSettingsAndValuesForNewVaultAccount()
if (user.isPotentiallyAPrivateUsernameAccount()) {
defaultSettingsWithValues =
this.settingsAssociationService.getDefaultSettingsAndValuesForNewPrivateUsernameAccount()
}
for (const settingName of defaultSettingsWithValues.keys()) {

View File

@@ -55,7 +55,7 @@ describe('SettingsAssociationService', () => {
})
it('should return the default set of settings for a newly registered vault account', () => {
const settings = createService().getDefaultSettingsAndValuesForNewVaultAccount()
const settings = createService().getDefaultSettingsAndValuesForNewPrivateUsernameAccount()
const flatSettings = [...(settings as Map<string, SettingDescription>).keys()]
expect(flatSettings).toEqual(['MUTE_MARKETING_EMAILS', 'LOG_SESSION_USER_AGENT'])

View File

@@ -66,7 +66,7 @@ export class SettingsAssociationService implements SettingsAssociationServiceInt
],
])
private readonly vaultAccountDefaultSettingsOverwrites = new Map<string, SettingDescription>([
private readonly privateUsernameAccountDefaultSettingsOverwrites = new Map<string, SettingDescription>([
[
SettingName.NAMES.LogSessionUserAgent,
{
@@ -114,16 +114,18 @@ export class SettingsAssociationService implements SettingsAssociationServiceInt
return this.defaultSettings
}
getDefaultSettingsAndValuesForNewVaultAccount(): Map<string, SettingDescription> {
const defaultVaultSettings = new Map(this.defaultSettings)
getDefaultSettingsAndValuesForNewPrivateUsernameAccount(): Map<string, SettingDescription> {
const defaultPrivateUsernameSettings = new Map(this.defaultSettings)
for (const vaultAccountDefaultSettingOverwriteKey of this.vaultAccountDefaultSettingsOverwrites.keys()) {
defaultVaultSettings.set(
vaultAccountDefaultSettingOverwriteKey,
this.vaultAccountDefaultSettingsOverwrites.get(vaultAccountDefaultSettingOverwriteKey) as SettingDescription,
for (const privateUsernameAccountDefaultSettingOverwriteKey of this.privateUsernameAccountDefaultSettingsOverwrites.keys()) {
defaultPrivateUsernameSettings.set(
privateUsernameAccountDefaultSettingOverwriteKey,
this.privateUsernameAccountDefaultSettingsOverwrites.get(
privateUsernameAccountDefaultSettingOverwriteKey,
) as SettingDescription,
)
}
return defaultVaultSettings
return defaultPrivateUsernameSettings
}
}

View File

@@ -6,7 +6,7 @@ import { SettingDescription } from './SettingDescription'
export interface SettingsAssociationServiceInterface {
getDefaultSettingsAndValuesForNewUser(): Map<string, SettingDescription>
getDefaultSettingsAndValuesForNewVaultAccount(): Map<string, SettingDescription>
getDefaultSettingsAndValuesForNewPrivateUsernameAccount(): Map<string, SettingDescription>
getPermissionAssociatedWithSetting(settingName: SettingName): PermissionName | undefined
getEncryptionVersionForSetting(settingName: SettingName): EncryptionVersion
getSensitivityForSetting(settingName: SettingName): boolean

View File

@@ -16,6 +16,8 @@ export class AuthenticateRequest implements UseCaseInterface {
async execute(dto: AuthenticateRequestDTO): Promise<AuthenticateRequestResponse> {
if (!dto.authorizationHeader) {
this.logger.debug('Authorization header not provided.')
return {
success: false,
responseCode: 401,

View File

@@ -7,6 +7,7 @@ import { AuthenticateUser } from './AuthenticateUser'
import { RevokedSession } from '../Session/RevokedSession'
import { AuthenticationMethodResolverInterface } from '../Auth/AuthenticationMethodResolverInterface'
import { TimerInterface } from '@standardnotes/time'
import { Logger } from 'winston'
describe('AuthenticateUser', () => {
let user: User
@@ -14,11 +15,15 @@ describe('AuthenticateUser', () => {
let revokedSession: RevokedSession
let authenticationMethodResolver: AuthenticationMethodResolverInterface
let timer: TimerInterface
let logger: Logger
const accessTokenAge = 3600
const createUseCase = () => new AuthenticateUser(authenticationMethodResolver, timer, accessTokenAge)
const createUseCase = () => new AuthenticateUser(authenticationMethodResolver, timer, accessTokenAge, logger)
beforeEach(() => {
logger = {} as jest.Mocked<Logger>
logger.debug = jest.fn()
user = {} as jest.Mocked<User>
user.supportsSessions = jest.fn().mockReturnValue(false)

View File

@@ -9,6 +9,7 @@ import { Session } from '../Session/Session'
import { AuthenticateUserDTO } from './AuthenticateUserDTO'
import { AuthenticateUserResponse } from './AuthenticateUserResponse'
import { UseCaseInterface } from './UseCaseInterface'
import { Logger } from 'winston'
@injectable()
export class AuthenticateUser implements UseCaseInterface {
@@ -17,11 +18,14 @@ export class AuthenticateUser implements UseCaseInterface {
private authenticationMethodResolver: AuthenticationMethodResolverInterface,
@inject(TYPES.Auth_Timer) private timer: TimerInterface,
@inject(TYPES.Auth_ACCESS_TOKEN_AGE) private accessTokenAge: number,
@inject(TYPES.Auth_Logger) private logger: Logger,
) {}
async execute(dto: AuthenticateUserDTO): Promise<AuthenticateUserResponse> {
const authenticationMethod = await this.authenticationMethodResolver.resolve(dto.token)
if (!authenticationMethod) {
this.logger.debug('No authentication method found for token.')
return {
success: false,
failureType: 'INVALID_AUTH',
@@ -37,6 +41,8 @@ export class AuthenticateUser implements UseCaseInterface {
const user = authenticationMethod.user
if (!user) {
this.logger.debug('No user found for authentication method.')
return {
success: false,
failureType: 'INVALID_AUTH',
@@ -44,6 +50,8 @@ export class AuthenticateUser implements UseCaseInterface {
}
if (authenticationMethod.type == 'jwt' && user.supportsSessions()) {
this.logger.debug('User supports sessions but is trying to authenticate with a JWT.')
return {
success: false,
failureType: 'INVALID_AUTH',
@@ -56,6 +64,8 @@ export class AuthenticateUser implements UseCaseInterface {
const encryptedPasswordDigest = crypto.createHash('sha256').update(user.encryptedPassword).digest('hex')
if (!pwHash || !crypto.timingSafeEqual(Buffer.from(pwHash), Buffer.from(encryptedPasswordDigest))) {
this.logger.debug('Password hash does not match.')
return {
success: false,
failureType: 'INVALID_AUTH',
@@ -66,6 +76,8 @@ export class AuthenticateUser implements UseCaseInterface {
case 'session_token': {
const session = authenticationMethod.session
if (!session) {
this.logger.debug('No session found for authentication method.')
return {
success: false,
failureType: 'INVALID_AUTH',
@@ -73,6 +85,8 @@ export class AuthenticateUser implements UseCaseInterface {
}
if (session.refreshExpiration < this.timer.getUTCDate()) {
this.logger.debug('Session refresh token has expired.')
return {
success: false,
failureType: 'INVALID_AUTH',

View File

@@ -2,7 +2,7 @@ import { inject, injectable } from 'inversify'
import { SubscriptionName } from '@standardnotes/common'
import { TimerInterface } from '@standardnotes/time'
import { TokenEncoderInterface, ValetTokenData } from '@standardnotes/security'
import { CreateValetTokenPayload, CreateValetTokenResponseData } from '@standardnotes/responses'
import { CreateValetTokenResponseData } from '@standardnotes/responses'
import { SettingName } from '@standardnotes/settings'
import TYPES from '../../../Bootstrap/Types'
@@ -12,6 +12,7 @@ import { SubscriptionSettingServiceInterface } from '../../Setting/SubscriptionS
import { CreateValetTokenDTO } from './CreateValetTokenDTO'
import { SubscriptionSettingsAssociationServiceInterface } from '../../Setting/SubscriptionSettingsAssociationServiceInterface'
import { UserSubscriptionServiceInterface } from '../../Subscription/UserSubscriptionServiceInterface'
import { CreateValetTokenPayload } from '../../ValetToken/CreateValetTokenPayload'
@injectable()
export class CreateValetToken implements UseCaseInterface {

View File

@@ -69,7 +69,7 @@ export class InviteToSharedSubscription implements UseCaseInterface {
sharedSubscriptionInvition.inviterIdentifier = dto.inviterEmail
sharedSubscriptionInvition.inviterIdentifierType = InviterIdentifierType.Email
sharedSubscriptionInvition.inviteeIdentifier = dto.inviteeIdentifier
sharedSubscriptionInvition.inviteeIdentifierType = this.isInviteeIdentifierPotentiallyAVaultAccount(
sharedSubscriptionInvition.inviteeIdentifierType = this.isInviteeIdentifierPotentiallyAPrivateUsernameAccount(
dto.inviteeIdentifier,
)
? InviteeIdentifierType.Hash
@@ -107,7 +107,7 @@ export class InviteToSharedSubscription implements UseCaseInterface {
}
}
private isInviteeIdentifierPotentiallyAVaultAccount(identifier: string): boolean {
private isInviteeIdentifierPotentiallyAPrivateUsernameAccount(identifier: string): boolean {
return identifier.length === 64 && !identifier.includes('@')
}
}

View File

@@ -44,21 +44,13 @@ describe('UpdateUser', () => {
user,
updatedWithUserAgent: 'Mozilla',
apiVersion: '20190520',
version: '004',
pwCost: 11,
pwSalt: 'qweqwe',
pwNonce: undefined,
}),
).toEqual({ success: true, authResponse: { foo: 'bar' } })
expect(userRepository.save).toHaveBeenCalledWith({
createdAt: new Date(1),
pwCost: 11,
email: 'test@test.te',
pwSalt: 'qweqwe',
updatedWithUserAgent: 'Mozilla',
uuid: '123',
version: '004',
updatedAt: new Date(1),
})
})

View File

@@ -17,25 +17,17 @@ export class UpdateUser implements UseCaseInterface {
) {}
async execute(dto: UpdateUserDTO): Promise<UpdateUserResponse> {
const { user, apiVersion, ...updateFields } = dto
dto.user.updatedAt = this.timer.getUTCDate()
Object.keys(updateFields).forEach(
(key) => (updateFields[key] === undefined || updateFields[key] === null) && delete updateFields[key],
)
const updatedUser = await this.userRepository.save(dto.user)
Object.assign(user, updateFields)
user.updatedAt = this.timer.getUTCDate()
await this.userRepository.save(user)
const authResponseFactory = this.authResponseFactoryResolver.resolveAuthResponseFactoryVersion(apiVersion)
const authResponseFactory = this.authResponseFactoryResolver.resolveAuthResponseFactoryVersion(dto.apiVersion)
return {
success: true,
authResponse: await authResponseFactory.createResponse({
user,
apiVersion,
user: updatedUser,
apiVersion: dto.apiVersion,
userAgent: dto.updatedWithUserAgent,
ephemeralSession: false,
readonlyAccess: false,

View File

@@ -1,18 +1,7 @@
import { User } from '../User/User'
export type UpdateUserDTO = {
[key: string]: string | User | Date | undefined | number
user: User
updatedWithUserAgent: string
apiVersion: string
email?: string
pwFunc?: string
pwAlg?: string
pwCost?: number
pwKeySize?: number
pwNonce?: string
pwSalt?: string
kpOrigination?: string
kpCreated?: Date
version?: string
updatedWithUserAgent: string
}

View File

@@ -21,13 +21,13 @@ describe('User', () => {
const user = createUser()
user.email = 'a75a31ce95365904ef0e0a8e6cefc1f5e99adfef81bbdb6d4499eeb10ae0ff67'
expect(user.isPotentiallyAVaultAccount()).toBeTruthy()
expect(user.isPotentiallyAPrivateUsernameAccount()).toBeTruthy()
})
it('should indicate if the user is not a vault account', () => {
const user = createUser()
user.email = 'test@test.te'
expect(user.isPotentiallyAVaultAccount()).toBeFalsy()
expect(user.isPotentiallyAPrivateUsernameAccount()).toBeFalsy()
})
})

View File

@@ -202,7 +202,7 @@ export class User {
return parseInt(this.version) >= parseInt(ProtocolVersion.V004)
}
isPotentiallyAVaultAccount(): boolean {
isPotentiallyAPrivateUsernameAccount(): boolean {
return this.email.length === 64 && !this.email.includes('@')
}
}

View File

@@ -0,0 +1,7 @@
export type CreateValetTokenPayload = {
operation: 'read' | 'write' | 'delete' | 'move'
resources: Array<{
remoteIdentifier: string
unencryptedFileSize?: number
}>
}

View File

@@ -60,15 +60,6 @@ export class HomeServerUsersController extends BaseHttpController {
user: response.locals.user,
updatedWithUserAgent: <string>request.headers['user-agent'],
apiVersion: request.body.api,
pwFunc: request.body.pw_func,
pwAlg: request.body.pw_alg,
pwCost: request.body.pw_cost,
pwKeySize: request.body.pw_key_size,
pwNonce: request.body.pw_nonce,
pwSalt: request.body.pw_salt,
kpOrigination: request.body.origination,
kpCreated: request.body.created,
version: request.body.version,
})
if (updateResult.success) {

View File

@@ -1,10 +1,11 @@
import { ControllerContainerInterface, Uuid } from '@standardnotes/domain-core'
import { Request, Response } from 'express'
import { BaseHttpController, results } from 'inversify-express-utils'
import { ErrorTag } from '@standardnotes/responses'
import { ValetTokenOperation } from '@standardnotes/security'
import { CreateValetToken } from '../../../Domain/UseCase/CreateValetToken/CreateValetToken'
import { CreateValetTokenPayload, ErrorTag } from '@standardnotes/responses'
import { ValetTokenOperation } from '@standardnotes/security'
import { CreateValetTokenPayload } from '../../../Domain/ValetToken/CreateValetTokenPayload'
export class HomeServerValetTokenController extends BaseHttpController {
constructor(protected createValetKey: CreateValetToken, private controllerContainer?: ControllerContainerInterface) {

View File

@@ -99,9 +99,7 @@ describe('InversifyExpressUsersController', () => {
expect(updateUser.execute).toHaveBeenCalledWith({
apiVersion: '20190520',
kpOrigination: 'test',
updatedWithUserAgent: 'Google Chrome',
version: '002',
user: {
uuid: '123',
email: 'test@test.te',
@@ -143,9 +141,7 @@ describe('InversifyExpressUsersController', () => {
expect(updateUser.execute).toHaveBeenCalledWith({
apiVersion: '20190520',
kpOrigination: 'test',
updatedWithUserAgent: 'Google Chrome',
version: '002',
user: {
uuid: '123',
email: 'test@test.te',

View File

@@ -0,0 +1,38 @@
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm'
@Entity({ name: 'notifications' })
export class TypeORMNotification {
@PrimaryGeneratedColumn('uuid')
declare uuid: string
@Column({
name: 'user_uuid',
length: 36,
})
@Index('index_notifications_on_user_uuid')
declare userUuid: string
@Column({
name: 'type',
length: 36,
})
declare type: string
@Column({
name: 'payload',
type: 'text',
})
declare payload: string
@Column({
name: 'created_at_timestamp',
type: 'bigint',
})
declare createdAtTimestamp: number
@Column({
name: 'updated_at_timestamp',
type: 'bigint',
})
declare updatedAtTimestamp: number
}

View File

@@ -0,0 +1,5 @@
export type SimpleUserProjection = {
uuid: string
email: string
protocolVersion: string
}

View File

@@ -2,10 +2,11 @@ import { injectable } from 'inversify'
import { User } from '../Domain/User/User'
import { ProjectorInterface } from './ProjectorInterface'
import { SimpleUserProjection } from './SimpleUserProjection'
@injectable()
export class UserProjector implements ProjectorInterface<User> {
projectSimple(user: User): Record<string, unknown> {
projectSimple(user: User): SimpleUserProjection {
return {
uuid: user.uuid,
email: user.email,

View File

@@ -3,6 +3,12 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [1.49.0](https://github.com/standardnotes/server/compare/@standardnotes/common@1.48.3...@standardnotes/common@1.49.0) (2023-06-30)
### Features
* shared vaults functionality in api-gateway,auth,files,common,security,domain-events. ([#629](https://github.com/standardnotes/server/issues/629)) ([fa7fbe2](https://github.com/standardnotes/server/commit/fa7fbe26e7b0707fc21d71e04af76870f5248baf))
## [1.48.3](https://github.com/standardnotes/server/compare/@standardnotes/common@1.48.2...@standardnotes/common@1.48.3) (2023-06-28)
**Note:** Version bump only for package @standardnotes/common

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/common",
"version": "1.48.3",
"version": "1.49.0",
"engines": {
"node": ">=18.0.0 <21.0.0"
},

View File

@@ -3,7 +3,6 @@ export enum ProtocolVersion {
V002 = '002',
V003 = '003',
V004 = '004',
V005 = '005',
}
export const ProtocolVersionLatest = ProtocolVersion.V004

View File

@@ -3,6 +3,24 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [1.21.0](https://github.com/standardnotes/server/compare/@standardnotes/domain-core@1.20.0...@standardnotes/domain-core@1.21.0) (2023-07-06)
### Features
* getting shared vault users and removing shared vault user ([#642](https://github.com/standardnotes/server/issues/642)) ([e905128](https://github.com/standardnotes/server/commit/e905128d45eaadb34d3465d4480dfb3a2c5f3f79))
# [1.20.0](https://github.com/standardnotes/server/compare/@standardnotes/domain-core@1.19.0...@standardnotes/domain-core@1.20.0) (2023-07-05)
### Features
* deleting shared vaults. ([#640](https://github.com/standardnotes/server/issues/640)) ([f3161c2](https://github.com/standardnotes/server/commit/f3161c271296159331639814b2dbb2e566cc54c9))
# [1.19.0](https://github.com/standardnotes/server/compare/@standardnotes/domain-core@1.18.0...@standardnotes/domain-core@1.19.0) (2023-06-30)
### Features
* add shared vaults model. ([#631](https://github.com/standardnotes/server/issues/631)) ([38e77f0](https://github.com/standardnotes/server/commit/38e77f04be441b7506c3390fb0d9894b34119c3e))
# [1.18.0](https://github.com/standardnotes/server/compare/@standardnotes/domain-core@1.17.0...@standardnotes/domain-core@1.18.0) (2023-06-02)
### Features

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/domain-core",
"version": "1.18.0",
"version": "1.21.0",
"engines": {
"node": ">=18.0.0 <21.0.0"
},

View File

@@ -20,7 +20,7 @@ export class Dates extends ValueObject<DatesProps> {
return Result.fail<Dates>(`Could not create Dates. Creation date should be a date object, given: ${createdAt}`)
}
if (!(updatedAt instanceof Date)) {
return Result.fail<Dates>(`Could not create Dates. Update date should be a date object, given: ${createdAt}`)
return Result.fail<Dates>(`Could not create Dates. Update date should be a date object, given: ${updatedAt}`)
}
return Result.ok<Dates>(new Dates({ createdAt, updatedAt }))

View File

@@ -28,7 +28,7 @@ export class RoleNameCollection extends ValueObject<RoleNameCollectionProps> {
return false
}
equals(roleNameCollection: RoleNameCollection): boolean {
override equals(roleNameCollection: RoleNameCollection): boolean {
if (this.props.value.length !== roleNameCollection.value.length) {
return false
}

View File

@@ -0,0 +1,30 @@
import { Result } from '../Core/Result'
import { ValueObject } from '../Core/ValueObject'
import { TimestampsProps } from './TimestampsProps'
export class Timestamps extends ValueObject<TimestampsProps> {
get createdAt(): number {
return this.props.createdAt
}
get updatedAt(): number {
return this.props.updatedAt
}
private constructor(props: TimestampsProps) {
super(props)
}
static create(createdAt: number, updatedAt: number): Result<Timestamps> {
if (isNaN(createdAt)) {
return Result.fail<Timestamps>(
`Could not create Timestamps. Creation date should be a number, given: ${createdAt}`,
)
}
if (isNaN(updatedAt)) {
return Result.fail<Timestamps>(`Could not create Timestamps. Update date should be a number, given: ${updatedAt}`)
}
return Result.ok<Timestamps>(new Timestamps({ createdAt, updatedAt }))
}
}

View File

@@ -0,0 +1,4 @@
export interface TimestampsProps {
createdAt: number
updatedAt: number
}

View File

@@ -13,4 +13,25 @@ describe('Uuid', () => {
expect(valueOrError.isFailed()).toBeTruthy()
})
it('should check equality between two value objects', () => {
const uuid1 = Uuid.create('84c0f8e8-544a-4c7e-9adf-26209303bc1d').getValue()
const uuid2 = Uuid.create('84c0f8e8-544a-4c7e-9adf-26209303bc1d').getValue()
expect(uuid1.equals(uuid2)).toBeTruthy()
})
it('should check inequality between two value objects', () => {
const uuid1 = Uuid.create('84c0f8e8-544a-4c7e-9adf-26209303bc1d').getValue()
const uuid2 = Uuid.create('84c0f8e8-544a-4c7e-9adf-26209303bc1e').getValue()
expect(uuid1.equals(uuid2)).toBeFalsy()
})
it('should check inequality between two value objects of different types', () => {
const uuid1 = Uuid.create('84c0f8e8-544a-4c7e-9adf-26209303bc1d').getValue()
expect(uuid1.equals(null as unknown as Uuid)).toBeFalsy()
expect(uuid1.equals(undefined as unknown as Uuid)).toBeFalsy()
})
})

View File

@@ -7,4 +7,12 @@ export abstract class ValueObject<T extends ValueObjectProps> {
constructor(props: T) {
this.props = Object.freeze(props)
}
public equals(vo?: ValueObject<T>): boolean {
if (vo === null || vo === undefined) {
return false
}
return JSON.stringify(this.props) === JSON.stringify(vo.props)
}
}

View File

@@ -0,0 +1,16 @@
import { NotificationType } from './NotificationType'
describe('NotificationType', () => {
it('should create a value object', () => {
const valueOrError = NotificationType.create(NotificationType.TYPES.SharedVaultItemRemoved)
expect(valueOrError.isFailed()).toBeFalsy()
expect(valueOrError.getValue().value).toEqual('shared_vault_item_removed')
})
it('should not create an invalid value object', () => {
const valueOrError = NotificationType.create('TEST')
expect(valueOrError.isFailed()).toBeTruthy()
})
})

View File

@@ -0,0 +1,28 @@
import { Result } from '../Core/Result'
import { ValueObject } from '../Core/ValueObject'
import { NotificationTypeProps } from './NotificationTypeProps'
export class NotificationType extends ValueObject<NotificationTypeProps> {
static readonly TYPES = {
SharedVaultItemRemoved: 'shared_vault_item_removed',
RemovedFromSharedVault: 'removed_from_shared_vault',
}
get value(): string {
return this.props.value
}
private constructor(props: NotificationTypeProps) {
super(props)
}
static create(notificationType: string): Result<NotificationType> {
const isValidPermission = Object.values(this.TYPES).includes(notificationType)
if (!isValidPermission) {
return Result.fail<NotificationType>(`Invalid shared vault user permission ${notificationType}`)
} else {
return Result.ok<NotificationType>(new NotificationType({ value: notificationType }))
}
}
}

View File

@@ -0,0 +1,3 @@
export interface NotificationTypeProps {
value: string
}

View File

@@ -17,6 +17,8 @@ export * from './Common/RoleName'
export * from './Common/RoleNameProps'
export * from './Common/RoleNameCollection'
export * from './Common/RoleNameCollectionProps'
export * from './Common/Timestamps'
export * from './Common/TimestampsProps'
export * from './Common/Username'
export * from './Common/UsernameProps'
export * from './Common/Uuid'
@@ -41,6 +43,9 @@ export * from './Env/AbstractEnv'
export * from './Mapping/MapperInterface'
export * from './Notification/NotificationType'
export * from './Notification/NotificationTypeProps'
export * from './Service/ServiceConfiguration'
export * from './Service/ServiceContainer'
export * from './Service/ServiceContainerInterface'

View File

@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.12.8](https://github.com/standardnotes/server/compare/@standardnotes/domain-events-infra@1.12.7...@standardnotes/domain-events-infra@1.12.8) (2023-07-05)
**Note:** Version bump only for package @standardnotes/domain-events-infra
## [1.12.7](https://github.com/standardnotes/server/compare/@standardnotes/domain-events-infra@1.12.6...@standardnotes/domain-events-infra@1.12.7) (2023-06-30)
**Note:** Version bump only for package @standardnotes/domain-events-infra
## [1.12.6](https://github.com/standardnotes/server/compare/@standardnotes/domain-events-infra@1.12.5...@standardnotes/domain-events-infra@1.12.6) (2023-06-30)
**Note:** Version bump only for package @standardnotes/domain-events-infra
## [1.12.5](https://github.com/standardnotes/server/compare/@standardnotes/domain-events-infra@1.12.4...@standardnotes/domain-events-infra@1.12.5) (2023-06-01)
**Note:** Version bump only for package @standardnotes/domain-events-infra

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/domain-events-infra",
"version": "1.12.5",
"version": "1.12.8",
"engines": {
"node": ">=18.0.0 <21.0.0"
},

View File

@@ -3,6 +3,22 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [2.113.0](https://github.com/standardnotes/server/compare/@standardnotes/domain-events@2.112.1...@standardnotes/domain-events@2.113.0) (2023-07-05)
### Features
* deleting shared vaults. ([#640](https://github.com/standardnotes/server/issues/640)) ([f3161c2](https://github.com/standardnotes/server/commit/f3161c271296159331639814b2dbb2e566cc54c9))
## [2.112.1](https://github.com/standardnotes/server/compare/@standardnotes/domain-events@2.112.0...@standardnotes/domain-events@2.112.1) (2023-06-30)
**Note:** Version bump only for package @standardnotes/domain-events
# [2.112.0](https://github.com/standardnotes/server/compare/@standardnotes/domain-events@2.111.4...@standardnotes/domain-events@2.112.0) (2023-06-30)
### Features
* shared vaults functionality in api-gateway,auth,files,common,security,domain-events. ([#629](https://github.com/standardnotes/server/issues/629)) ([fa7fbe2](https://github.com/standardnotes/server/commit/fa7fbe26e7b0707fc21d71e04af76870f5248baf))
## [2.111.4](https://github.com/standardnotes/server/compare/@standardnotes/domain-events@2.111.3...@standardnotes/domain-events@2.111.4) (2023-06-01)
**Note:** Version bump only for package @standardnotes/domain-events

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/domain-events",
"version": "2.111.4",
"version": "2.113.0",
"engines": {
"node": ">=18.0.0 <21.0.0"
},

View File

@@ -7,7 +7,7 @@ export interface DomainEventInterface {
meta: {
correlation: {
userIdentifier: string
userIdentifierType: 'uuid' | 'email'
userIdentifierType: 'uuid' | 'email' | 'shared-vault-uuid'
}
origin: DomainEventService
target?: DomainEventService

View File

@@ -0,0 +1,7 @@
import { DomainEventInterface } from './DomainEventInterface'
import { NotificationRequestedEventPayload } from './NotificationRequestedEventPayload'
export interface NotificationRequestedEvent extends DomainEventInterface {
type: 'NOTIFICATION_REQUESTED'
payload: NotificationRequestedEventPayload
}

View File

@@ -0,0 +1,5 @@
export interface NotificationRequestedEventPayload {
userUuid: string
type: string
payload: string
}

View File

@@ -0,0 +1,7 @@
import { DomainEventInterface } from './DomainEventInterface'
import { SharedVaultFileRemovedEventPayload } from './SharedVaultFileRemovedEventPayload'
export interface SharedVaultFileRemovedEvent extends DomainEventInterface {
type: 'SHARED_VAULT_FILE_REMOVED'
payload: SharedVaultFileRemovedEventPayload
}

View File

@@ -0,0 +1,6 @@
export interface SharedVaultFileRemovedEventPayload {
sharedVaultUuid: string
fileByteSize: number
filePath: string
fileName: string
}

View File

@@ -0,0 +1,7 @@
import { DomainEventInterface } from './DomainEventInterface'
import { SharedVaultFileUploadedEventPayload } from './SharedVaultFileUploadedEventPayload'
export interface SharedVaultFileUploadedEvent extends DomainEventInterface {
type: 'SHARED_VAULT_FILE_UPLOADED'
payload: SharedVaultFileUploadedEventPayload
}

View File

@@ -0,0 +1,6 @@
export interface SharedVaultFileUploadedEventPayload {
sharedVaultUuid: string
fileByteSize: number
filePath: string
fileName: string
}

View File

@@ -42,6 +42,8 @@ export * from './Event/ListedAccountRequestedEvent'
export * from './Event/ListedAccountRequestedEventPayload'
export * from './Event/MuteEmailsSettingChangedEvent'
export * from './Event/MuteEmailsSettingChangedEventPayload'
export * from './Event/NotificationRequestedEvent'
export * from './Event/NotificationRequestedEventPayload'
export * from './Event/PaymentFailedEvent'
export * from './Event/PaymentFailedEventPayload'
export * from './Event/PaymentSuccessEvent'
@@ -62,6 +64,10 @@ export * from './Event/SharedSubscriptionInvitationCanceledEvent'
export * from './Event/SharedSubscriptionInvitationCanceledEventPayload'
export * from './Event/SharedSubscriptionInvitationCreatedEvent'
export * from './Event/SharedSubscriptionInvitationCreatedEventPayload'
export * from './Event/SharedVaultFileRemovedEvent'
export * from './Event/SharedVaultFileRemovedEventPayload'
export * from './Event/SharedVaultFileUploadedEvent'
export * from './Event/SharedVaultFileUploadedEventPayload'
export * from './Event/StatisticPersistenceRequestedEvent'
export * from './Event/StatisticPersistenceRequestedEventPayload'
export * from './Event/SubscriptionCancelledEvent'

View File

@@ -3,6 +3,28 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.11.4](https://github.com/standardnotes/server/compare/@standardnotes/event-store@1.11.3...@standardnotes/event-store@1.11.4) (2023-07-06)
**Note:** Version bump only for package @standardnotes/event-store
## [1.11.3](https://github.com/standardnotes/server/compare/@standardnotes/event-store@1.11.2...@standardnotes/event-store@1.11.3) (2023-07-05)
**Note:** Version bump only for package @standardnotes/event-store
## [1.11.2](https://github.com/standardnotes/server/compare/@standardnotes/event-store@1.11.1...@standardnotes/event-store@1.11.2) (2023-06-30)
**Note:** Version bump only for package @standardnotes/event-store
## [1.11.1](https://github.com/standardnotes/server/compare/@standardnotes/event-store@1.11.0...@standardnotes/event-store@1.11.1) (2023-06-30)
**Note:** Version bump only for package @standardnotes/event-store
# [1.11.0](https://github.com/standardnotes/server/compare/@standardnotes/event-store@1.10.1...@standardnotes/event-store@1.11.0) (2023-06-30)
### Features
* shared vaults functionality in api-gateway,auth,files,common,security,domain-events. ([#629](https://github.com/standardnotes/server/issues/629)) ([fa7fbe2](https://github.com/standardnotes/server/commit/fa7fbe26e7b0707fc21d71e04af76870f5248baf))
## [1.10.1](https://github.com/standardnotes/server/compare/@standardnotes/event-store@1.10.0...@standardnotes/event-store@1.10.1) (2023-06-02)
### Bug Fixes

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/event-store",
"version": "1.10.1",
"version": "1.11.4",
"description": "Event Store Service",
"private": true,
"main": "dist/src/index.js",

View File

@@ -3,6 +3,28 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.19.4](https://github.com/standardnotes/files/compare/@standardnotes/files-server@1.19.3...@standardnotes/files-server@1.19.4) (2023-07-06)
**Note:** Version bump only for package @standardnotes/files-server
## [1.19.3](https://github.com/standardnotes/files/compare/@standardnotes/files-server@1.19.2...@standardnotes/files-server@1.19.3) (2023-07-05)
**Note:** Version bump only for package @standardnotes/files-server
## [1.19.2](https://github.com/standardnotes/files/compare/@standardnotes/files-server@1.19.1...@standardnotes/files-server@1.19.2) (2023-06-30)
**Note:** Version bump only for package @standardnotes/files-server
## [1.19.1](https://github.com/standardnotes/files/compare/@standardnotes/files-server@1.19.0...@standardnotes/files-server@1.19.1) (2023-06-30)
**Note:** Version bump only for package @standardnotes/files-server
# [1.19.0](https://github.com/standardnotes/files/compare/@standardnotes/files-server@1.18.3...@standardnotes/files-server@1.19.0) (2023-06-30)
### Features
* shared vaults functionality in api-gateway,auth,files,common,security,domain-events. ([#629](https://github.com/standardnotes/files/issues/629)) ([fa7fbe2](https://github.com/standardnotes/files/commit/fa7fbe26e7b0707fc21d71e04af76870f5248baf))
## [1.18.3](https://github.com/standardnotes/files/compare/@standardnotes/files-server@1.18.2...@standardnotes/files-server@1.18.3) (2023-06-22)
### Bug Fixes

View File

@@ -4,6 +4,7 @@ import * as busboy from 'connect-busboy'
import '../src/Infra/InversifyExpress/InversifyExpressHealthCheckController'
import '../src/Infra/InversifyExpress/InversifyExpressFilesController'
import '../src/Infra/InversifyExpress/InversifyExpressSharedVaultFilesController'
import helmet from 'helmet'
import * as cors from 'cors'

View File

@@ -1,6 +1,6 @@
{
"name": "@standardnotes/files-server",
"version": "1.18.3",
"version": "1.19.4",
"engines": {
"node": ">=18.0.0 <21.0.0"
},

View File

@@ -48,6 +48,11 @@ import { AccountDeletionRequestedEventHandler } from '../Domain/Handler/AccountD
import { SharedSubscriptionInvitationCanceledEventHandler } from '../Domain/Handler/SharedSubscriptionInvitationCanceledEventHandler'
import { InMemoryUploadRepository } from '../Infra/InMemory/InMemoryUploadRepository'
import { Transform } from 'stream'
import { FileMoverInterface } from '../Domain/Services/FileMoverInterface'
import { S3FileMover } from '../Infra/S3/S3FileMover'
import { FSFileMover } from '../Infra/FS/FSFileMover'
import { MoveFile } from '../Domain/UseCase/MoveFile/MoveFile'
import { SharedVaultValetTokenAuthMiddleware } from '../Infra/InversifyExpress/Middleware/SharedVaultValetTokenAuthMiddleware'
export class ContainerConfigLoader {
async load(configuration?: {
@@ -177,6 +182,7 @@ export class ContainerConfigLoader {
container.bind<FileDownloaderInterface>(TYPES.Files_FileDownloader).to(S3FileDownloader)
container.bind<FileUploaderInterface>(TYPES.Files_FileUploader).to(S3FileUploader)
container.bind<FileRemoverInterface>(TYPES.Files_FileRemover).to(S3FileRemover)
container.bind<FileMoverInterface>(TYPES.Files_FileMover).to(S3FileMover)
} else {
container.bind<FileDownloaderInterface>(TYPES.Files_FileDownloader).to(FSFileDownloader)
container
@@ -185,6 +191,7 @@ export class ContainerConfigLoader {
new FSFileUploader(container.get(TYPES.Files_FILE_UPLOAD_PATH), container.get(TYPES.Files_Logger)),
)
container.bind<FileRemoverInterface>(TYPES.Files_FileRemover).to(FSFileRemover)
container.bind<FileMoverInterface>(TYPES.Files_FileMover).to(FSFileMover)
}
// use cases
@@ -194,10 +201,14 @@ export class ContainerConfigLoader {
container.bind<FinishUploadSession>(TYPES.Files_FinishUploadSession).to(FinishUploadSession)
container.bind<GetFileMetadata>(TYPES.Files_GetFileMetadata).to(GetFileMetadata)
container.bind<RemoveFile>(TYPES.Files_RemoveFile).to(RemoveFile)
container.bind<MoveFile>(TYPES.Files_MoveFile).to(MoveFile)
container.bind<MarkFilesToBeRemoved>(TYPES.Files_MarkFilesToBeRemoved).to(MarkFilesToBeRemoved)
// middleware
container.bind<ValetTokenAuthMiddleware>(TYPES.Files_ValetTokenAuthMiddleware).to(ValetTokenAuthMiddleware)
container
.bind<SharedVaultValetTokenAuthMiddleware>(TYPES.Files_SharedVaultValetTokenAuthMiddleware)
.to(SharedVaultValetTokenAuthMiddleware)
// services
container

View File

@@ -13,6 +13,7 @@ const TYPES = {
Files_FinishUploadSession: Symbol.for('Files_FinishUploadSession'),
Files_GetFileMetadata: Symbol.for('Files_GetFileMetadata'),
Files_RemoveFile: Symbol.for('Files_RemoveFile'),
Files_MoveFile: Symbol.for('Files_MoveFile'),
Files_MarkFilesToBeRemoved: Symbol.for('Files_MarkFilesToBeRemoved'),
// services
@@ -23,12 +24,14 @@ const TYPES = {
Files_FileUploader: Symbol.for('Files_FileUploader'),
Files_FileDownloader: Symbol.for('Files_FileDownloader'),
Files_FileRemover: Symbol.for('Files_FileRemover'),
Files_FileMover: Symbol.for('Files_FileMover'),
// repositories
Files_UploadRepository: Symbol.for('Files_UploadRepository'),
// middleware
Files_ValetTokenAuthMiddleware: Symbol.for('Files_ValetTokenAuthMiddleware'),
Files_SharedVaultValetTokenAuthMiddleware: Symbol.for('Files_SharedVaultValetTokenAuthMiddleware'),
// env vars
Files_S3_ENDPOINT: Symbol.for('Files_S3_ENDPOINT'),

View File

@@ -14,6 +14,60 @@ describe('DomainEventFactory', () => {
timer.getUTCDate = jest.fn().mockReturnValue(new Date(1))
})
it('should create a SHARED_VAULT_FILE_UPLOADED event', () => {
expect(
createFactory().createSharedVaultFileUploadedEvent({
sharedVaultUuid: '1-2-3',
filePath: 'foo/bar',
fileName: 'baz',
fileByteSize: 123,
}),
).toEqual({
createdAt: new Date(1),
meta: {
correlation: {
userIdentifier: '1-2-3',
userIdentifierType: 'shared-vault-uuid',
},
origin: 'files',
},
payload: {
sharedVaultUuid: '1-2-3',
filePath: 'foo/bar',
fileName: 'baz',
fileByteSize: 123,
},
type: 'SHARED_VAULT_FILE_UPLOADED',
})
})
it('should create a SHARED_VAULT_FILE_REMOVED event', () => {
expect(
createFactory().createSharedVaultFileRemovedEvent({
sharedVaultUuid: '1-2-3',
filePath: 'foo/bar',
fileName: 'baz',
fileByteSize: 123,
}),
).toEqual({
createdAt: new Date(1),
meta: {
correlation: {
userIdentifier: '1-2-3',
userIdentifierType: 'shared-vault-uuid',
},
origin: 'files',
},
payload: {
sharedVaultUuid: '1-2-3',
filePath: 'foo/bar',
fileName: 'baz',
fileByteSize: 123,
},
type: 'SHARED_VAULT_FILE_REMOVED',
})
})
it('should create a FILE_UPLOADED event', () => {
expect(
createFactory().createFileUploadedEvent({

View File

@@ -1,4 +1,10 @@
import { FileUploadedEvent, FileRemovedEvent, DomainEventService } from '@standardnotes/domain-events'
import {
FileUploadedEvent,
FileRemovedEvent,
DomainEventService,
SharedVaultFileUploadedEvent,
SharedVaultFileRemovedEvent,
} from '@standardnotes/domain-events'
import { TimerInterface } from '@standardnotes/time'
import { inject, injectable } from 'inversify'
@@ -49,4 +55,44 @@ export class DomainEventFactory implements DomainEventFactoryInterface {
payload,
}
}
createSharedVaultFileUploadedEvent(payload: {
sharedVaultUuid: string
filePath: string
fileName: string
fileByteSize: number
}): SharedVaultFileUploadedEvent {
return {
type: 'SHARED_VAULT_FILE_UPLOADED',
createdAt: this.timer.getUTCDate(),
meta: {
correlation: {
userIdentifier: payload.sharedVaultUuid,
userIdentifierType: 'shared-vault-uuid',
},
origin: DomainEventService.Files,
},
payload,
}
}
createSharedVaultFileRemovedEvent(payload: {
sharedVaultUuid: string
filePath: string
fileName: string
fileByteSize: number
}): SharedVaultFileRemovedEvent {
return {
type: 'SHARED_VAULT_FILE_REMOVED',
createdAt: this.timer.getUTCDate(),
meta: {
correlation: {
userIdentifier: payload.sharedVaultUuid,
userIdentifierType: 'shared-vault-uuid',
},
origin: DomainEventService.Files,
},
payload,
}
}
}

View File

@@ -1,4 +1,9 @@
import { FileUploadedEvent, FileRemovedEvent } from '@standardnotes/domain-events'
import {
FileUploadedEvent,
FileRemovedEvent,
SharedVaultFileRemovedEvent,
SharedVaultFileUploadedEvent,
} from '@standardnotes/domain-events'
export interface DomainEventFactoryInterface {
createFileUploadedEvent(payload: {
@@ -14,4 +19,16 @@ export interface DomainEventFactoryInterface {
fileByteSize: number
regularSubscriptionUuid: string
}): FileRemovedEvent
createSharedVaultFileUploadedEvent(payload: {
sharedVaultUuid: string
filePath: string
fileName: string
fileByteSize: number
}): SharedVaultFileUploadedEvent
createSharedVaultFileRemovedEvent(payload: {
sharedVaultUuid: string
filePath: string
fileName: string
fileByteSize: number
}): SharedVaultFileRemovedEvent
}

View File

@@ -44,7 +44,7 @@ describe('AccountDeletionRequestedEventHandler', () => {
it('should mark files to be remove for user', async () => {
await createHandler().handle(event)
expect(markFilesToBeRemoved.execute).toHaveBeenCalledWith({ userUuid: '1-2-3' })
expect(markFilesToBeRemoved.execute).toHaveBeenCalledWith({ ownerUuid: '1-2-3' })
expect(domainEventPublisher.publish).toHaveBeenCalled()
})
@@ -66,7 +66,7 @@ describe('AccountDeletionRequestedEventHandler', () => {
await createHandler().handle(event)
expect(markFilesToBeRemoved.execute).toHaveBeenCalledWith({ userUuid: '1-2-3' })
expect(markFilesToBeRemoved.execute).toHaveBeenCalledWith({ ownerUuid: '1-2-3' })
expect(domainEventPublisher.publish).not.toHaveBeenCalled()
})

View File

@@ -23,7 +23,7 @@ export class AccountDeletionRequestedEventHandler implements DomainEventHandlerI
}
const response = await this.markFilesToBeRemoved.execute({
userUuid: event.payload.userUuid,
ownerUuid: event.payload.userUuid,
})
if (!response.success) {

View File

@@ -44,7 +44,7 @@ describe('SharedSubscriptionInvitationCanceledEventHandler', () => {
it('should mark files to be remove for user', async () => {
await createHandler().handle(event)
expect(markFilesToBeRemoved.execute).toHaveBeenCalledWith({ userUuid: '1-2-3' })
expect(markFilesToBeRemoved.execute).toHaveBeenCalledWith({ ownerUuid: '1-2-3' })
expect(domainEventPublisher.publish).toHaveBeenCalled()
})
@@ -66,7 +66,7 @@ describe('SharedSubscriptionInvitationCanceledEventHandler', () => {
await createHandler().handle(event)
expect(markFilesToBeRemoved.execute).toHaveBeenCalledWith({ userUuid: '1-2-3' })
expect(markFilesToBeRemoved.execute).toHaveBeenCalledWith({ ownerUuid: '1-2-3' })
expect(domainEventPublisher.publish).not.toHaveBeenCalled()
})

View File

@@ -23,7 +23,7 @@ export class SharedSubscriptionInvitationCanceledEventHandler implements DomainE
}
const response = await this.markFilesToBeRemoved.execute({
userUuid: event.payload.inviteeIdentifier,
ownerUuid: event.payload.inviteeIdentifier,
})
if (!response.success) {

View File

@@ -0,0 +1,3 @@
export interface FileMoverInterface {
moveFile(sourcePath: string, destinationPath: string): Promise<void>
}

View File

@@ -33,7 +33,7 @@ describe('CreateUploadSession', () => {
expect(
await createUseCase().execute({
resourceRemoteIdentifier: '2-3-4',
userUuid: '1-2-3',
ownerUuid: '1-2-3',
}),
).toEqual({
success: false,
@@ -44,7 +44,7 @@ describe('CreateUploadSession', () => {
it('should create an upload session', async () => {
await createUseCase().execute({
resourceRemoteIdentifier: '2-3-4',
userUuid: '1-2-3',
ownerUuid: '1-2-3',
})
expect(fileUploader.createUploadSession).toHaveBeenCalledWith('1-2-3/2-3-4')

View File

@@ -20,7 +20,7 @@ export class CreateUploadSession implements UseCaseInterface {
try {
this.logger.debug(`Creating upload session for resource: ${dto.resourceRemoteIdentifier}`)
const filePath = `${dto.userUuid}/${dto.resourceRemoteIdentifier}`
const filePath = `${dto.ownerUuid}/${dto.resourceRemoteIdentifier}`
const uploadId = await this.fileUploader.createUploadSession(filePath)

View File

@@ -1,4 +1,4 @@
export type CreateUploadSessionDTO = {
userUuid: string
ownerUuid: string
resourceRemoteIdentifier: string
}

View File

@@ -1,6 +1,10 @@
import 'reflect-metadata'
import { DomainEventPublisherInterface, FileUploadedEvent } from '@standardnotes/domain-events'
import {
DomainEventPublisherInterface,
FileUploadedEvent,
SharedVaultFileUploadedEvent,
} from '@standardnotes/domain-events'
import { Logger } from 'winston'
import { DomainEventFactoryInterface } from '../../Event/DomainEventFactoryInterface'
import { FileUploaderInterface } from '../../Services/FileUploaderInterface'
@@ -31,6 +35,9 @@ describe('FinishUploadSession', () => {
domainEventFactory = {} as jest.Mocked<DomainEventFactoryInterface>
domainEventFactory.createFileUploadedEvent = jest.fn().mockReturnValue({} as jest.Mocked<FileUploadedEvent>)
domainEventFactory.createSharedVaultFileUploadedEvent = jest
.fn()
.mockReturnValue({} as jest.Mocked<SharedVaultFileUploadedEvent>)
logger = {} as jest.Mocked<Logger>
logger.debug = jest.fn()
@@ -43,7 +50,8 @@ describe('FinishUploadSession', () => {
await createUseCase().execute({
resourceRemoteIdentifier: '2-3-4',
userUuid: '1-2-3',
ownerUuid: '1-2-3',
ownerType: 'user',
uploadBytesLimit: 100,
uploadBytesUsed: 0,
})
@@ -60,7 +68,8 @@ describe('FinishUploadSession', () => {
expect(
await createUseCase().execute({
resourceRemoteIdentifier: '2-3-4',
userUuid: '1-2-3',
ownerUuid: '1-2-3',
ownerType: 'user',
uploadBytesLimit: 100,
uploadBytesUsed: 0,
}),
@@ -76,7 +85,23 @@ describe('FinishUploadSession', () => {
it('should finish an upload session', async () => {
await createUseCase().execute({
resourceRemoteIdentifier: '2-3-4',
userUuid: '1-2-3',
ownerUuid: '1-2-3',
ownerType: 'user',
uploadBytesLimit: 100,
uploadBytesUsed: 0,
})
expect(fileUploader.finishUploadSession).toHaveBeenCalledWith('123', '1-2-3/2-3-4', [
{ tag: '123', chunkId: 1, chunkSize: 1 },
])
expect(domainEventPublisher.publish).toHaveBeenCalled()
})
it('should finish an upload session for a vault shared file', async () => {
await createUseCase().execute({
resourceRemoteIdentifier: '2-3-4',
ownerUuid: '1-2-3',
ownerType: 'shared-vault',
uploadBytesLimit: 100,
uploadBytesUsed: 0,
})
@@ -97,7 +122,8 @@ describe('FinishUploadSession', () => {
expect(
await createUseCase().execute({
resourceRemoteIdentifier: '2-3-4',
userUuid: '1-2-3',
ownerUuid: '1-2-3',
ownerType: 'user',
uploadBytesLimit: 100,
uploadBytesUsed: 20,
}),

View File

@@ -24,7 +24,7 @@ export class FinishUploadSession implements UseCaseInterface {
try {
this.logger.debug(`Finishing upload session for resource: ${dto.resourceRemoteIdentifier}`)
const filePath = `${dto.userUuid}/${dto.resourceRemoteIdentifier}`
const filePath = `${dto.ownerUuid}/${dto.resourceRemoteIdentifier}`
const uploadId = await this.uploadRepository.retrieveUploadSessionId(filePath)
if (uploadId === undefined) {
@@ -53,14 +53,25 @@ export class FinishUploadSession implements UseCaseInterface {
await this.fileUploader.finishUploadSession(uploadId, filePath, uploadChunkResults)
await this.domainEventPublisher.publish(
this.domainEventFactory.createFileUploadedEvent({
userUuid: dto.userUuid,
filePath: `${dto.userUuid}/${dto.resourceRemoteIdentifier}`,
fileName: dto.resourceRemoteIdentifier,
fileByteSize: totalFileSize,
}),
)
if (dto.ownerType === 'user') {
await this.domainEventPublisher.publish(
this.domainEventFactory.createFileUploadedEvent({
userUuid: dto.ownerUuid,
filePath: `${dto.ownerUuid}/${dto.resourceRemoteIdentifier}`,
fileName: dto.resourceRemoteIdentifier,
fileByteSize: totalFileSize,
}),
)
} else {
await this.domainEventPublisher.publish(
this.domainEventFactory.createSharedVaultFileUploadedEvent({
sharedVaultUuid: dto.ownerUuid,
filePath: `${dto.ownerUuid}/${dto.resourceRemoteIdentifier}`,
fileName: dto.resourceRemoteIdentifier,
fileByteSize: totalFileSize,
}),
)
}
return {
success: true,

View File

@@ -1,5 +1,6 @@
export type FinishUploadSessionDTO = {
userUuid: string
ownerUuid: string
ownerType: 'user' | 'shared-vault'
resourceRemoteIdentifier: string
uploadBytesUsed: number
uploadBytesLimit: number

View File

@@ -19,7 +19,7 @@ describe('GetFileMetadata', () => {
})
it('should return the file metadata', async () => {
expect(await createUseCase().execute({ resourceRemoteIdentifier: '1-2-3', userUuid: '2-3-4' })).toEqual({
expect(await createUseCase().execute({ resourceRemoteIdentifier: '1-2-3', ownerUuid: '2-3-4' })).toEqual({
success: true,
size: 123,
})
@@ -30,7 +30,7 @@ describe('GetFileMetadata', () => {
throw new Error('ooops')
})
expect(await createUseCase().execute({ resourceRemoteIdentifier: '1-2-3', userUuid: '2-3-4' })).toEqual({
expect(await createUseCase().execute({ resourceRemoteIdentifier: '1-2-3', ownerUuid: '2-3-4' })).toEqual({
success: false,
message: 'Could not get file metadata.',
})

View File

@@ -15,14 +15,14 @@ export class GetFileMetadata implements UseCaseInterface {
async execute(dto: GetFileMetadataDTO): Promise<GetFileMetadataResponse> {
try {
const size = await this.fileDownloader.getFileSize(`${dto.userUuid}/${dto.resourceRemoteIdentifier}`)
const size = await this.fileDownloader.getFileSize(`${dto.ownerUuid}/${dto.resourceRemoteIdentifier}`)
return {
success: true,
size,
}
} catch (error) {
this.logger.error(`Could not get file metadata for resource: ${dto.userUuid}/${dto.resourceRemoteIdentifier}`)
this.logger.error(`Could not get file metadata for resource: ${dto.ownerUuid}/${dto.resourceRemoteIdentifier}`)
return {
success: false,
message: 'Could not get file metadata.',

View File

@@ -1,4 +1,4 @@
export type GetFileMetadataDTO = {
userUuid: string
ownerUuid: string
resourceRemoteIdentifier: string
}

View File

@@ -21,7 +21,7 @@ describe('MarkFilesToBeRemoved', () => {
})
it('should mark files for being removed', async () => {
expect(await createUseCase().execute({ userUuid: '1-2-3' })).toEqual({ success: true })
expect(await createUseCase().execute({ ownerUuid: '1-2-3' })).toEqual({ success: true })
expect(fileRemover.markFilesToBeRemoved).toHaveBeenCalledWith('1-2-3')
})
@@ -31,7 +31,7 @@ describe('MarkFilesToBeRemoved', () => {
throw new Error('Oops')
})
expect(await createUseCase().execute({ userUuid: '1-2-3' })).toEqual({
expect(await createUseCase().execute({ ownerUuid: '1-2-3' })).toEqual({
success: false,
message: 'Could not mark resources for removal',
})

View File

@@ -16,16 +16,16 @@ export class MarkFilesToBeRemoved implements UseCaseInterface {
async execute(dto: MarkFilesToBeRemovedDTO): Promise<MarkFilesToBeRemovedResponse> {
try {
this.logger.debug(`Marking files for later removal for user: ${dto.userUuid}`)
this.logger.debug(`Marking files for later removal for user: ${dto.ownerUuid}`)
const filesRemoved = await this.fileRemover.markFilesToBeRemoved(dto.userUuid)
const filesRemoved = await this.fileRemover.markFilesToBeRemoved(dto.ownerUuid)
return {
success: true,
filesRemoved,
}
} catch (error) {
this.logger.error(`Could not mark resources for removal: ${dto.userUuid} - ${(error as Error).message}`)
this.logger.error(`Could not mark resources for removal: ${dto.ownerUuid} - ${(error as Error).message}`)
return {
success: false,

Some files were not shown because too many files have changed in this diff Show More