@ossy/workspaces 1.10.0 → 1.12.0

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/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@ossy/workspaces",
3
3
  "description": "Workspaces feature package — create, select, and manage workspaces, users, and invitations",
4
- "version": "1.10.0",
4
+ "version": "1.12.0",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
7
7
  "module": "./src/index.js",
8
8
  "exports": {
9
- ".": "./src/index.js"
9
+ ".": "./src/index.js",
10
+ "./workspace-invitation.email.jsx": "./src/workspace-invitation.email.jsx"
10
11
  },
11
12
  "author": "Ossy <yourfriends@ossy.se> (https://ossy.se)",
12
13
  "license": "MIT",
@@ -27,5 +28,5 @@
27
28
  "/src",
28
29
  "README.md"
29
30
  ],
30
- "gitHead": "9a8a1bb0466d35001425d241d77c2c9ab31e11d3"
31
+ "gitHead": "c6697078268867d88553ca0bac08faad5cea1546"
31
32
  }
@@ -0,0 +1,85 @@
1
+ import jwt from 'jsonwebtoken'
2
+ import { Aggregate } from '@ossy/event-store'
3
+ import { Workspace, WorkspacesEvents } from '@ossy/workspaces'
4
+ import { User, UsersEvents } from '@ossy/users'
5
+ import { Token, TokenEvents } from '@ossy/tokens'
6
+ import { ConfigService } from '@ossy/platform'
7
+ import { createLogger } from '@ossy/observability'
8
+
9
+ const log = createLogger('workspaces/accept-invitation')
10
+
11
+ function verifyToken(token) {
12
+ return new Promise((resolve, reject) => {
13
+ if (!token) return reject(new Error('No token'))
14
+ jwt.verify(token, ConfigService.TokenSecret, { algorithms: ['HS256'] }, (err, payload) => {
15
+ if (err) return reject(err)
16
+ resolve(payload)
17
+ })
18
+ })
19
+ }
20
+
21
+ export const id = 'workspaces/accept-invitation'
22
+ export const access = 'public'
23
+
24
+ export async function run({ payload, req }) {
25
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
26
+ const verificationToken = payload?.token ?? req?.query?.token
27
+
28
+ const { aud: tokenWorkspaceId, sub: email } = await verifyToken(verificationToken)
29
+ .catch(() => { throw Object.assign(new Error('Invalid token'), { status: 401 }) })
30
+
31
+ const resolvedWorkspaceId = tokenWorkspaceId ?? workspaceId
32
+ const workspace = await Aggregate.Of(Workspace, resolvedWorkspaceId).then(Aggregate.View())
33
+
34
+ if (!email) throw Object.assign(new Error('No email found in token payload'), { status: 401 })
35
+
36
+ const existingUser = await Aggregate.Collection.findOne({ type: 'User', 'state.email': email }).then(agg => agg?.state)
37
+
38
+ if (existingUser && workspace.users.includes(existingUser.id)) {
39
+ throw Object.assign(new Error('User already in workspace'), { status: 400 })
40
+ }
41
+
42
+ let userId
43
+ let signInToken
44
+ let signInExpiresAt
45
+
46
+ if (existingUser) {
47
+ userId = existingUser.id
48
+ const signInExpiresIn = ConfigService.TokenValidity
49
+ signInExpiresAt = Date.now() + signInExpiresIn * 1000
50
+ signInToken = jwt.sign({ sub: userId, type: 'WebAuth' }, ConfigService.TokenSecret, { expiresIn: signInExpiresIn })
51
+ const signInEvent = TokenEvents.Created({
52
+ type: 'WebAuth',
53
+ subject: userId,
54
+ createdBy: userId,
55
+ token: signInToken,
56
+ expiresAt: signInExpiresAt,
57
+ })
58
+ const userInvitationAccepted = WorkspacesEvents.UserInvitationAccepted({ email, createdBy: userId })
59
+ await Promise.all([
60
+ Aggregate.Of(Token, signInEvent),
61
+ Aggregate.Of(Workspace, resolvedWorkspaceId).then(Aggregate.Add(userInvitationAccepted)),
62
+ ])
63
+ } else {
64
+ const signUpEvent = UsersEvents.SignedUp({ email })
65
+ userId = signUpEvent.createdBy
66
+ const signInExpiresIn = ConfigService.TokenValidity
67
+ signInExpiresAt = Date.now() + signInExpiresIn * 1000
68
+ signInToken = jwt.sign({ sub: userId, type: 'WebAuth' }, ConfigService.TokenSecret, { expiresIn: signInExpiresIn })
69
+ const signInEvent = TokenEvents.Created({
70
+ type: 'WebAuth',
71
+ subject: userId,
72
+ createdBy: userId,
73
+ token: signInToken,
74
+ expiresAt: signInExpiresAt,
75
+ })
76
+ const userInvitationAccepted = WorkspacesEvents.UserInvitationAccepted({ email, createdBy: userId })
77
+ await Promise.all([
78
+ Aggregate.Of(User, signUpEvent),
79
+ Aggregate.Of(Token, signInEvent),
80
+ Aggregate.Of(Workspace, resolvedWorkspaceId).then(Aggregate.Add(userInvitationAccepted)),
81
+ ])
82
+ }
83
+
84
+ return { authToken: signInToken, authExpiresAt: signInExpiresAt }
85
+ }
@@ -0,0 +1,17 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace, WorkspacesEvents } from '@ossy/workspaces'
3
+
4
+ export const id = 'workspaces/create-api-token'
5
+ export const access = 'workspace'
6
+
7
+ export async function run({ payload, req }) {
8
+ const createdBy = payload?.userId ?? req?.userId
9
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
10
+ const description = payload?.description
11
+
12
+ const event = WorkspacesEvents.ApiTokenCreated({ createdBy, workspaceId, description })
13
+
14
+ const aggregate = await Aggregate.Of(Workspace, workspaceId).then(Aggregate.Add(event))
15
+ const last = aggregate.events[aggregate.events.length - 1]
16
+ return { id: last.id, token: event.payload.token }
17
+ }
@@ -0,0 +1,30 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace, WorkspacesEvents } from '@ossy/workspaces'
3
+ import { ConfigService } from '@ossy/platform'
4
+
5
+ export const id = 'workspaces/create'
6
+ export const access = 'authenticated'
7
+
8
+ export async function run({ payload, req }) {
9
+ const createdBy = payload?.userId ?? req?.userId
10
+ const name = (payload?.name ?? req?.body?.name)?.trim?.()
11
+
12
+ if (!name || typeof name !== 'string') {
13
+ throw Object.assign(new Error('Invalid name'), { status: 400 })
14
+ }
15
+
16
+ const createdEvent = WorkspacesEvents.Created({ createdBy, name })
17
+ const botUserInvitedEvent = WorkspacesEvents.UserInvited({
18
+ createdBy: ConfigService.BotUserId,
19
+ email: ConfigService.BotUserEmail,
20
+ })
21
+ const botUserAcceptedEvent = WorkspacesEvents.UserInvitationAccepted({
22
+ createdBy: ConfigService.BotUserId,
23
+ email: ConfigService.BotUserEmail,
24
+ })
25
+
26
+ return Aggregate.Of(Workspace, createdEvent)
27
+ .then(Aggregate.Add(botUserInvitedEvent))
28
+ .then(Aggregate.Add(botUserAcceptedEvent))
29
+ .then(Aggregate.View())
30
+ }
@@ -0,0 +1,30 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'workspaces.current',
5
+ path: '/api/v0/workspaces/current',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method !== 'GET') {
10
+ res.setHeader('Allow', 'GET')
11
+ res.status(405).json({ error: 'Method Not Allowed' })
12
+ return
13
+ }
14
+
15
+ const workspaceId = req.workspaceId || req.user?.workspaces?.[0]
16
+ if (!workspaceId) {
17
+ res.status(404).json(null)
18
+ return
19
+ }
20
+
21
+ try {
22
+ const workspace = await ActionService.invoke('workspaces/get', {
23
+ payload: { workspaceId },
24
+ req: { ...req, workspaceId },
25
+ })
26
+ res.json(workspace)
27
+ } catch (err) {
28
+ res.status(err?.status ?? 500).json({ error: err?.message })
29
+ }
30
+ }
@@ -0,0 +1,28 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace, WorkspacesEvents } from '@ossy/workspaces'
3
+
4
+ export const id = 'workspaces/disable-service'
5
+ export const access = 'workspace'
6
+
7
+ const AVAILABLE_SERVICES = [
8
+ '@ossy/tasks/visual-content-descriptors',
9
+ '@ossy/tasks/resize-common-web',
10
+ '@ossy/resumes',
11
+ '@ossy/consultancy',
12
+ '@ossy/apps',
13
+ '@ossy/domains',
14
+ ]
15
+
16
+ export async function run({ payload, req }) {
17
+ const createdBy = payload?.userId ?? req?.userId
18
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
19
+ const service = payload?.service
20
+
21
+ if (!AVAILABLE_SERVICES.includes(service)) {
22
+ throw Object.assign(new Error(`Service ${service} is not available`), { status: 400 })
23
+ }
24
+
25
+ const event = WorkspacesEvents.ServiceDisabled({ createdBy, service })
26
+ await Aggregate.Of(Workspace, workspaceId).then(Aggregate.Add(event))
27
+ return null
28
+ }
@@ -0,0 +1,28 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace, WorkspacesEvents } from '@ossy/workspaces'
3
+
4
+ export const id = 'workspaces/enable-service'
5
+ export const access = 'workspace'
6
+
7
+ const AVAILABLE_SERVICES = [
8
+ '@ossy/tasks/visual-content-descriptors',
9
+ '@ossy/tasks/resize-common-web',
10
+ '@ossy/resumes',
11
+ '@ossy/consultancy',
12
+ '@ossy/apps',
13
+ '@ossy/domains',
14
+ ]
15
+
16
+ export async function run({ payload, req }) {
17
+ const createdBy = payload?.userId ?? req?.userId
18
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
19
+ const service = payload?.service ?? payload
20
+
21
+ if (!AVAILABLE_SERVICES.includes(service)) {
22
+ throw Object.assign(new Error(`Service ${service} is not available`), { status: 400 })
23
+ }
24
+
25
+ const event = WorkspacesEvents.ServiceEnabled({ createdBy, service })
26
+ await Aggregate.Of(Workspace, workspaceId).then(Aggregate.Add(event))
27
+ return null
28
+ }
@@ -0,0 +1,11 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace } from '@ossy/workspaces'
3
+
4
+ export const id = 'workspaces/get-api-tokens'
5
+ export const access = 'workspace'
6
+
7
+ export async function run({ payload, req }) {
8
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
9
+ const workspace = await Aggregate.Of(Workspace, workspaceId).then(Aggregate.View())
10
+ return workspace.apiTokens
11
+ }
@@ -0,0 +1,11 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace } from '@ossy/workspaces'
3
+
4
+ export const id = 'workspaces/get-invitations'
5
+ export const access = 'workspace'
6
+
7
+ export async function run({ payload, req }) {
8
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
9
+ const workspace = await Aggregate.Of(Workspace, workspaceId).then(Aggregate.View())
10
+ return workspace.invitations
11
+ }
@@ -0,0 +1,19 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace } from '@ossy/workspaces'
3
+ import { getSystemResourceTemplates } from '@ossy/platform'
4
+
5
+ export const id = 'workspaces/get-resource-templates'
6
+ export const access = 'workspace'
7
+
8
+ export async function run({ payload, req }) {
9
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
10
+
11
+ const workspace = await Aggregate.Of(Workspace, workspaceId).then(Aggregate.View())
12
+ const systemTemplates = getSystemResourceTemplates()
13
+ const workspaceTemplates = workspace.resourceTemplates || []
14
+ const workspaceIds = new Set(workspaceTemplates.map(t => t.id))
15
+ return [
16
+ ...systemTemplates.filter(t => !workspaceIds.has(t.id)),
17
+ ...workspaceTemplates,
18
+ ]
19
+ }
@@ -0,0 +1,14 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace } from '@ossy/workspaces'
3
+ import { User } from '@ossy/users'
4
+
5
+ export const id = 'workspaces/get-users'
6
+ export const access = 'workspace'
7
+
8
+ export async function run({ payload, req }) {
9
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
10
+ const workspace = await Aggregate.Of(Workspace, workspaceId).then(Aggregate.View())
11
+ return Promise.all(
12
+ workspace.users.map(userId => Aggregate.Of(User, userId).then(Aggregate.View(User.UserForWorkspace)))
13
+ )
14
+ }
@@ -0,0 +1,14 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace } from '@ossy/workspaces'
3
+
4
+ export const id = 'workspaces/get'
5
+ export const access = 'workspace'
6
+
7
+ export async function run({ payload, req }) {
8
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
9
+ if (!workspaceId) throw Object.assign(new Error('workspaceId is required'), { status: 404 })
10
+
11
+ const workspace = await Aggregate.Of(Workspace, workspaceId).then(Aggregate.View())
12
+ if (!workspace?.id) throw Object.assign(new Error('Workspace not found'), { status: 404 })
13
+ return workspace
14
+ }
@@ -0,0 +1,27 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace, WorkspacesEvents } from '@ossy/workspaces'
3
+ import { validateResourceTemplatesForImport } from '@ossy/platform'
4
+
5
+ export const id = 'workspaces/import-resource-templates'
6
+ export const access = 'workspace'
7
+
8
+ export async function run({ payload, req }) {
9
+ const userId = payload?.userId ?? req?.userId
10
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
11
+ const templates = payload?.templates ?? payload
12
+
13
+ if (!Array.isArray(templates)) {
14
+ throw Object.assign(new Error('templates must be an array'), { status: 400 })
15
+ }
16
+
17
+ const reservedIds = new Set([])
18
+ const validation = validateResourceTemplatesForImport(templates, reservedIds)
19
+ if (!validation.ok) {
20
+ throw Object.assign(new Error(validation.message), { status: 400, type: validation.code })
21
+ }
22
+
23
+ const event = WorkspacesEvents.ResourceTemplatesImported({ createdBy: userId, templates })
24
+
25
+ await Aggregate.Of(Workspace, workspaceId).then(Aggregate.Add(event))
26
+ return event.payload.templates
27
+ }
@@ -0,0 +1,46 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'invitations.root',
5
+ path: '/api/v0/invitations',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method === 'POST') {
10
+ try {
11
+ await ActionService.invoke('workspaces/invite-user', {
12
+ payload: {
13
+ email: req.body,
14
+ workspaceId: req.workspaceId,
15
+ userId: req.userId,
16
+ inviterEmail: req.user?.email,
17
+ },
18
+ integrations: req.integrations,
19
+ req,
20
+ })
21
+ res.json('')
22
+ } catch (err) {
23
+ res.status(err?.status ?? 400).json(err?.message ?? 'Could not invite user')
24
+ }
25
+ return
26
+ }
27
+ if (req.method === 'GET') {
28
+ try {
29
+ const result = await ActionService.invoke('workspaces/accept-invitation', {
30
+ payload: { workspaceId: req.workspaceId, token: req.query?.token },
31
+ req,
32
+ })
33
+ res.cookie('auth', result.authToken, {
34
+ httpOnly: true,
35
+ signed: true,
36
+ expires: new Date(result.authExpiresAt),
37
+ })
38
+ res.json('')
39
+ } catch (err) {
40
+ res.status(err?.status ?? 401).json('')
41
+ }
42
+ return
43
+ }
44
+ res.setHeader('Allow', 'GET, POST')
45
+ res.status(405).json({ error: 'Method Not Allowed' })
46
+ }
@@ -0,0 +1,82 @@
1
+ import jwt from 'jsonwebtoken'
2
+ import { Aggregate } from '@ossy/event-store'
3
+ import { Workspace, WorkspacesEvents } from '@ossy/workspaces'
4
+ import { Token, TokenEvents } from '@ossy/tokens'
5
+ import { EmailRenderer } from '@ossy/email'
6
+ import { ConfigService } from '@ossy/platform'
7
+ import { createLogger } from '@ossy/observability'
8
+ import WorkspaceInvitationEmail, { subject as workspaceInvitationSubject } from './workspace-invitation.email.jsx'
9
+
10
+ const log = createLogger('workspaces/invite-user')
11
+
12
+ const isEmailLike = maybeEmail => /.@.+\.../.test(maybeEmail)
13
+
14
+ function createVerificationToken(workspaceId) {
15
+ const expiresIn = ConfigService.TokenValidity
16
+ return jwt.sign({ aud: workspaceId }, ConfigService.TokenSecret, { expiresIn })
17
+ }
18
+
19
+ export const id = 'workspaces/invite-user'
20
+ export const access = 'workspace'
21
+
22
+ export async function run({ payload, integrations, req }) {
23
+ const createdBy = payload?.userId ?? req?.userId
24
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
25
+ const email = payload?.email ?? req?.body
26
+ const inviterEmail = payload?.inviterEmail ?? req?.user?.email
27
+
28
+ if (!isEmailLike(email)) {
29
+ throw Object.assign(new Error('Invalid email'), { status: 400 })
30
+ }
31
+
32
+ const workspace = await Aggregate.Of(Workspace, workspaceId).then(Aggregate.View())
33
+
34
+ const userInvitation = workspace.invitations.find(inv => inv.email === email)
35
+ if (userInvitation && userInvitation.expiresAt > Date.now()) {
36
+ throw Object.assign(new Error('User already invited'), { status: 400 })
37
+ }
38
+
39
+ const expiresIn = ConfigService.TokenValidity
40
+ const expiresAt = Date.now() + expiresIn * 1000
41
+ const inviteEvent = WorkspacesEvents.UserInvited({ createdBy, email, expiresAt })
42
+
43
+ const rawToken = createVerificationToken(workspaceId)
44
+ const tokenEvent = TokenEvents.Created({
45
+ type: 'Verification',
46
+ createdBy,
47
+ name: 'Workspace Invitation',
48
+ subject: email,
49
+ audience: workspace.id,
50
+ token: rawToken,
51
+ expiresAt,
52
+ })
53
+
54
+ const existingUser = await Aggregate.Collection.findOne({ type: 'User', 'state.email': email }).then(agg => agg?.state)
55
+ if (existingUser && workspace.users.includes(existingUser.id)) {
56
+ throw Object.assign(new Error('User already in workspace'), { status: 400 })
57
+ }
58
+
59
+ await Promise.all([
60
+ Aggregate.Of(Workspace, workspace.id).then(Aggregate.Add(inviteEvent)),
61
+ Aggregate.Of(Token, tokenEvent),
62
+ ])
63
+
64
+ const baseUrl = ConfigService.getWebClientBaseUrl(req)
65
+ const { html, text } = EmailRenderer.render(WorkspaceInvitationEmail, {
66
+ workspace,
67
+ verificationToken: rawToken,
68
+ invitedBy: inviterEmail,
69
+ baseUrl,
70
+ })
71
+
72
+ const emailClient = integrations?.get?.('email')
73
+ if (emailClient) {
74
+ await emailClient.send({ to: email, from: 'noreply@ossy.se', subject: workspaceInvitationSubject, html, text })
75
+ } else if (ConfigService.BuildEnvironment === 'local') {
76
+ log.info('-----------YOU GOT MAIL-----------')
77
+ log.info('Email', { to: email, subject: workspaceInvitationSubject })
78
+ log.info('----------------------------------')
79
+ }
80
+
81
+ return ''
82
+ }
@@ -0,0 +1,32 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'workspaces.item',
5
+ path: '/api/v0/workspaces/:workspaceId',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method !== 'GET') {
10
+ res.setHeader('Allow', 'GET')
11
+ res.status(405).json({ error: 'Method Not Allowed' })
12
+ return
13
+ }
14
+
15
+ const pathname = (req.path || new URL(req.originalUrl, 'http://localhost').pathname).replace(/\/+$/, '')
16
+ const m = pathname.match(/^\/api\/v0\/workspaces\/([^/]+)$/)
17
+ if (!m || m[1] === 'current') {
18
+ res.status(404).json('')
19
+ return
20
+ }
21
+
22
+ const workspaceId = decodeURIComponent(m[1])
23
+ try {
24
+ const workspace = await ActionService.invoke('workspaces/get', {
25
+ payload: { workspaceId },
26
+ req: { ...req, workspaceId },
27
+ })
28
+ res.json(workspace)
29
+ } catch (err) {
30
+ res.status(err?.status ?? 500).json({ error: err?.message })
31
+ }
32
+ }
@@ -0,0 +1,9 @@
1
+ import { WorkspacesQueries } from './workspaces.queries.js'
2
+
3
+ export const id = 'workspaces/list'
4
+ export const access = 'authenticated'
5
+
6
+ export async function run({ payload, req }) {
7
+ const userId = payload?.userId ?? req?.userId
8
+ return WorkspacesQueries.getAllByUserIncluded(userId)
9
+ }
@@ -0,0 +1,35 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'workspaces.list',
5
+ path: '/api/v0/workspaces',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method === 'POST') {
10
+ try {
11
+ const workspace = await ActionService.invoke('workspaces/create', {
12
+ payload: { name: req.body?.name, userId: req.userId },
13
+ req,
14
+ })
15
+ res.json(workspace)
16
+ } catch (err) {
17
+ res.status(err?.status ?? 400).json({ error: err?.message })
18
+ }
19
+ return
20
+ }
21
+ if (req.method === 'GET') {
22
+ try {
23
+ const workspaces = await ActionService.invoke('workspaces/list', {
24
+ payload: { userId: req.userId },
25
+ req,
26
+ })
27
+ res.json(workspaces)
28
+ } catch (err) {
29
+ res.status(err?.status ?? 400).json({ error: err?.message })
30
+ }
31
+ return
32
+ }
33
+ res.setHeader('Allow', 'GET, POST')
34
+ res.status(405).json({ error: 'Method Not Allowed' })
35
+ }
@@ -0,0 +1,42 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'workspaces.members',
5
+ path: '/api/v0/workspaces/:workspaceId/members/:userId',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method !== 'DELETE') {
10
+ res.setHeader('Allow', 'DELETE')
11
+ res.status(405).json({ error: 'Method Not Allowed' })
12
+ return
13
+ }
14
+
15
+ const pathname = (req.path || new URL(req.originalUrl, 'http://localhost').pathname).replace(/\/+$/, '')
16
+ const m = pathname.match(/^\/api\/v0\/workspaces\/([^/]+)\/members\/([^/]+)$/)
17
+ if (!m) {
18
+ res.status(404).json('')
19
+ return
20
+ }
21
+
22
+ const workspaceId = decodeURIComponent(m[1])
23
+ const memberId = decodeURIComponent(m[2])
24
+
25
+ const isMember = Array.isArray(req.user?.workspaces) && req.user.workspaces.includes(workspaceId)
26
+ const isSelf = req.user?.id === memberId
27
+
28
+ if (!isMember && !isSelf) {
29
+ res.status(403).json({ error: 'Forbidden' })
30
+ return
31
+ }
32
+
33
+ try {
34
+ await ActionService.invoke('workspaces/remove-member', {
35
+ payload: { workspaceId, memberId, userId: req.userId },
36
+ req,
37
+ })
38
+ res.json()
39
+ } catch (err) {
40
+ res.status(err?.status ?? 500).json({ error: err?.message })
41
+ }
42
+ }
@@ -0,0 +1,17 @@
1
+ import { Aggregate } from '@ossy/event-store'
2
+ import { Workspace, WorkspacesEvents } from '@ossy/workspaces'
3
+
4
+ export const id = 'workspaces/remove-member'
5
+ export const access = 'workspace'
6
+
7
+ export async function run({ payload, req }) {
8
+ const createdBy = payload?.userId ?? req?.userId
9
+ const workspaceId = payload?.workspaceId ?? req?.workspaceId
10
+ const memberId = payload?.memberId ?? req?.memberId
11
+
12
+ if (!memberId) throw Object.assign(new Error('memberId is required'), { status: 400 })
13
+
14
+ const event = WorkspacesEvents.UserRemoved({ createdBy, userId: memberId })
15
+ await Aggregate.Of(Workspace, workspaceId).then(Aggregate.Add(event))
16
+ return null
17
+ }
@@ -0,0 +1,35 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'resourceTemplates.root',
5
+ path: '/api/v0/resource-templates',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method === 'POST') {
10
+ try {
11
+ const templates = await ActionService.invoke('workspaces/import-resource-templates', {
12
+ payload: { templates: req.body, workspaceId: req.workspaceId, userId: req.userId },
13
+ req,
14
+ })
15
+ res.json(templates)
16
+ } catch (err) {
17
+ res.status(err?.status ?? 500).json({ type: err?.type, message: err?.message })
18
+ }
19
+ return
20
+ }
21
+ if (req.method === 'GET') {
22
+ try {
23
+ const templates = await ActionService.invoke('workspaces/get-resource-templates', {
24
+ payload: { workspaceId: req.workspaceId },
25
+ req,
26
+ })
27
+ res.json(templates)
28
+ } catch (err) {
29
+ res.status(err?.status ?? 500).json()
30
+ }
31
+ return
32
+ }
33
+ res.setHeader('Allow', 'GET, POST')
34
+ res.status(405).json({ error: 'Method Not Allowed' })
35
+ }
@@ -0,0 +1,23 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'workspaces.services.disable',
5
+ path: '/api/v0/services/disable',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method !== 'POST') {
10
+ res.setHeader('Allow', 'POST')
11
+ res.status(405).json({ error: 'Method Not Allowed' })
12
+ return
13
+ }
14
+ try {
15
+ await ActionService.invoke('workspaces/disable-service', {
16
+ payload: { service: req.body?.service, workspaceId: req.workspaceId, userId: req.userId },
17
+ req,
18
+ })
19
+ res.json()
20
+ } catch (err) {
21
+ res.status(err?.status ?? 400).json({ error: err?.message })
22
+ }
23
+ }
@@ -0,0 +1,23 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'workspaces.services.enable',
5
+ path: '/api/v0/services/enable',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method !== 'POST') {
10
+ res.setHeader('Allow', 'POST')
11
+ res.status(405).json({ error: 'Method Not Allowed' })
12
+ return
13
+ }
14
+ try {
15
+ await ActionService.invoke('workspaces/enable-service', {
16
+ payload: { service: req.body, workspaceId: req.workspaceId, userId: req.userId },
17
+ req,
18
+ })
19
+ res.json()
20
+ } catch (err) {
21
+ res.status(err?.status ?? 400).json({ error: err?.message })
22
+ }
23
+ }
@@ -0,0 +1,35 @@
1
+ import { ActionService } from '@ossy/platform'
2
+
3
+ export const metadata = {
4
+ id: 'workspaces.tokens',
5
+ path: '/api/v0/tokens',
6
+ }
7
+
8
+ export default async function handle(req, res) {
9
+ if (req.method === 'GET') {
10
+ try {
11
+ const tokens = await ActionService.invoke('workspaces/get-api-tokens', {
12
+ payload: { workspaceId: req.workspaceId },
13
+ req,
14
+ })
15
+ res.json(tokens)
16
+ } catch (err) {
17
+ res.status(err?.status ?? 500).json({ error: err?.message })
18
+ }
19
+ return
20
+ }
21
+ if (req.method === 'POST') {
22
+ try {
23
+ const token = await ActionService.invoke('workspaces/create-api-token', {
24
+ payload: { workspaceId: req.workspaceId, userId: req.userId, description: req.body?.description },
25
+ req,
26
+ })
27
+ res.json(token)
28
+ } catch (err) {
29
+ res.status(err?.status ?? 500).json({ error: err?.message })
30
+ }
31
+ return
32
+ }
33
+ res.setHeader('Allow', 'GET, POST')
34
+ res.status(405).json({ error: 'Method Not Allowed' })
35
+ }
@@ -0,0 +1,18 @@
1
+ import { EmailLayout, EmailButton, EmailText } from '@ossy/email'
2
+
3
+ export const id = 'workspaces/invitation'
4
+ export const subject = 'You have been invited'
5
+
6
+ export default function WorkspaceInvitationEmail({ workspace, invitedBy, verificationToken, baseUrl = 'https://app.ossy.se', theme }) {
7
+ const verificationUrl = `${baseUrl}/invitations/verify?token=${verificationToken}&workspaceId=${workspace.id}`
8
+
9
+ return (
10
+ <EmailLayout theme={theme}>
11
+ <h1 style={{ color: '#111111', margin: '0 0 16px' }}>You have been invited</h1>
12
+ <EmailText>
13
+ You have been invited to contribute to {workspace.name} by {invitedBy}.
14
+ </EmailText>
15
+ <EmailButton href={verificationUrl} theme={theme}>Accept invitation</EmailButton>
16
+ </EmailLayout>
17
+ )
18
+ }
@@ -0,0 +1,33 @@
1
+ import { EventStore } from '@ossy/event-store'
2
+ import { createLogger } from '@ossy/observability'
3
+
4
+ const log = createLogger('workspaces')
5
+
6
+ export class WorkspacesQueries {
7
+ static getAllByUserIncluded(userId) {
8
+ log.info('[WorkspacesQueries] getAllByUserIncluded()')
9
+ return EventStore.Aggregate([
10
+ { $group: { _id: { aggregateId: '$aggregateId', aggregateType: '$aggregateType' }, events: { $push: '$$ROOT' } } },
11
+ {
12
+ $match: {
13
+ '_id.aggregateType': 'Workspace',
14
+ 'events.createdBy': userId,
15
+ 'events.type': { $nin: ['Deleted'], $in: ['Created', 'UserInvitationAccepted'] },
16
+ },
17
+ },
18
+ {
19
+ $project: {
20
+ events: '$events',
21
+ currentState: {
22
+ $reduce: {
23
+ input: '$events',
24
+ initialValue: {},
25
+ in: { id: '$_id.aggregateId', name: { $ifNull: ['$$this.payload.name', '$$value.name'] } },
26
+ },
27
+ },
28
+ },
29
+ },
30
+ { $project: { _id: 0, id: '$currentState.id', name: '$currentState.name' } },
31
+ ]).catch(() => [])
32
+ }
33
+ }