@webiny/api-core-ddb 0.0.0-unstable.3fddf667ea → 0.0.0-unstable.48a4e5b6c1

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.
@@ -1,11 +1,18 @@
1
1
  import { createFeature } from "@webiny/feature/api";
2
- import { ApiCoreStorageOperationsFactory } from "@webiny/api-core";
2
+ import { ApiCoreStorageOperationsFactory, TenancyStorageOperationsFactory } from "@webiny/api-core";
3
3
  import { createApiCoreDdb } from "./createApiCoreDdb.js";
4
+ import { createStorageOperations } from "./tenancy/index.js";
4
5
  const ApiCoreDdbFeature = createFeature({
5
6
  name: "ApiCoreDdb",
6
7
  register (container, { documentClient }) {
7
8
  container.registerInstance(ApiCoreStorageOperationsFactory, {
8
- create: ()=>createApiCoreDdb({
9
+ create: ({ scopeTenant })=>createApiCoreDdb({
10
+ documentClient,
11
+ scopeTenant
12
+ })
13
+ });
14
+ container.registerInstance(TenancyStorageOperationsFactory, {
15
+ create: ()=>createStorageOperations({
9
16
  documentClient
10
17
  })
11
18
  });
@@ -1 +1 @@
1
- {"version":3,"file":"ApiCoreDdbFeature.js","sources":["../src/ApiCoreDdbFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { ApiCoreStorageOperationsFactory } from \"@webiny/api-core\";\nimport { createApiCoreDdb } from \"./createApiCoreDdb.js\";\n\nexport interface ApiCoreDdbConfig {\n documentClient: DynamoDBDocument;\n}\n\n/**\n * Registers the DynamoDB implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register\n * resolves + builds it. Mirrors HeadlessCmsDdbFeature.\n */\nexport const ApiCoreDdbFeature = createFeature<ApiCoreDdbConfig>({\n name: \"ApiCoreDdb\",\n register(container, { documentClient }) {\n container.registerInstance(ApiCoreStorageOperationsFactory, {\n create: () => createApiCoreDdb({ documentClient })\n });\n }\n});\n"],"names":["ApiCoreDdbFeature","createFeature","container","documentClient","ApiCoreStorageOperationsFactory","createApiCoreDdb"],"mappings":";;;AAaO,MAAMA,oBAAoBC,cAAgC;IAC7D,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,cAAc,EAAE;QAClCD,UAAU,gBAAgB,CAACE,iCAAiC;YACxD,QAAQ,IAAMC,iBAAiB;oBAAEF;gBAAe;QACpD;IACJ;AACJ"}
1
+ {"version":3,"file":"ApiCoreDdbFeature.js","sources":["../src/ApiCoreDdbFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { ApiCoreStorageOperationsFactory, TenancyStorageOperationsFactory } from \"@webiny/api-core\";\nimport { createApiCoreDdb } from \"./createApiCoreDdb.js\";\nimport { createStorageOperations as createTenancyStorageOperations } from \"./tenancy/index.js\";\n\nexport interface ApiCoreDdbConfig {\n documentClient: DynamoDBDocument;\n}\n\n/**\n * Registers the DynamoDB implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register\n * resolves + builds it. Mirrors HeadlessCmsDdbFeature.\n */\nexport const ApiCoreDdbFeature = createFeature<ApiCoreDdbConfig>({\n name: \"ApiCoreDdb\",\n register(container, { documentClient }) {\n container.registerInstance(ApiCoreStorageOperationsFactory, {\n create: ({ scopeTenant }) => createApiCoreDdb({ documentClient, scopeTenant })\n });\n // The tenant registry on its own: the request container reads the request's tenant from it.\n container.registerInstance(TenancyStorageOperationsFactory, {\n create: () => createTenancyStorageOperations({ documentClient })\n });\n }\n});\n"],"names":["ApiCoreDdbFeature","createFeature","container","documentClient","ApiCoreStorageOperationsFactory","scopeTenant","createApiCoreDdb","TenancyStorageOperationsFactory","createTenancyStorageOperations"],"mappings":";;;;AAcO,MAAMA,oBAAoBC,cAAgC;IAC7D,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,cAAc,EAAE;QAClCD,UAAU,gBAAgB,CAACE,iCAAiC;YACxD,QAAQ,CAAC,EAAEC,WAAW,EAAE,GAAKC,iBAAiB;oBAAEH;oBAAgBE;gBAAY;QAChF;QAEAH,UAAU,gBAAgB,CAACK,iCAAiC;YACxD,QAAQ,IAAMC,wBAA+B;oBAAEL;gBAAe;QAClE;IACJ;AACJ"}
@@ -2,7 +2,11 @@ import error from "@webiny/error";
2
2
  import { createTable, sortItems } from "@webiny/db-dynamodb";
3
3
  import { createUserEntity } from "./definitions/entities.js";
4
4
  const createStorageOperations = (params)=>{
5
- const { table: tableName, documentClient } = params;
5
+ const { table: tableName, documentClient, scopeTenant } = params;
6
+ const inScope = (user)=>({
7
+ ...user,
8
+ tenant: scopeTenant.getId()
9
+ });
6
10
  const table = createTable({
7
11
  name: tableName || process.env.DB_TABLE,
8
12
  documentClient
@@ -14,9 +18,12 @@ const createStorageOperations = (params)=>{
14
18
  PK: `T#${user.tenant}#ADMIN_USER#${user.id}`,
15
19
  SK: "A"
16
20
  });
21
+ const createUserIndexPartitionKey = (id)=>`ADMIN_USER#${id}`;
17
22
  const createUserGSIKeys = (user)=>({
18
23
  GSI1_PK: `T#${user.tenant}#ADMIN_USERS`,
19
24
  GSI1_SK: user.email,
25
+ GSI2_PK: createUserIndexPartitionKey(user.id),
26
+ GSI2_SK: `T#${user.tenant}`,
20
27
  GSI_TENANT: user.tenant
21
28
  });
22
29
  const storageOperations = {
@@ -26,7 +33,8 @@ const createStorageOperations = (params)=>{
26
33
  getEntities () {
27
34
  return entities;
28
35
  },
29
- async createUser ({ user }) {
36
+ async createUser (params) {
37
+ const user = inScope(params.user);
30
38
  const keys = {
31
39
  ...createUserKeys(user),
32
40
  ...createUserGSIKeys(user)
@@ -48,7 +56,8 @@ const createStorageOperations = (params)=>{
48
56
  });
49
57
  }
50
58
  },
51
- async deleteUser ({ user }) {
59
+ async deleteUser (params) {
60
+ const user = inScope(params.user);
52
61
  const keys = createUserKeys(user);
53
62
  try {
54
63
  await entities.users.delete(keys);
@@ -64,7 +73,8 @@ const createStorageOperations = (params)=>{
64
73
  }
65
74
  },
66
75
  async getUser (params) {
67
- const { where: { tenant, id, email } } = params;
76
+ const { where: { id, email } } = params;
77
+ const tenant = scopeTenant.getId();
68
78
  try {
69
79
  if (id) {
70
80
  const response = await entities.users.get(createUserKeys({
@@ -92,11 +102,55 @@ const createStorageOperations = (params)=>{
92
102
  });
93
103
  }
94
104
  },
105
+ async getUserAcrossTenants (params) {
106
+ const { id, tenants } = params;
107
+ if (0 === tenants.length) return [];
108
+ try {
109
+ const reader = entities.users.createEntityReader({
110
+ read: tenants.map((tenant)=>createUserKeys({
111
+ tenant,
112
+ id
113
+ }))
114
+ });
115
+ const items = await reader.execute();
116
+ return items.filter((item)=>!!item?.data).map((item)=>item.data);
117
+ } catch (err) {
118
+ throw error.from(err, {
119
+ message: "Could not load user across tenants.",
120
+ code: "GET_ADMIN_USER_ACROSS_TENANTS_ERROR",
121
+ data: {
122
+ id,
123
+ tenants
124
+ }
125
+ });
126
+ }
127
+ },
128
+ async listUserRecords (params) {
129
+ const { id } = params;
130
+ try {
131
+ const items = await entities.users.queryAll({
132
+ partitionKey: createUserIndexPartitionKey(id),
133
+ options: {
134
+ index: "GSI2"
135
+ }
136
+ });
137
+ return items.map((item)=>item.data);
138
+ } catch (err) {
139
+ throw error.from(err, {
140
+ message: "Could not list user records.",
141
+ code: "LIST_ADMIN_USER_RECORDS_ERROR",
142
+ data: {
143
+ id
144
+ }
145
+ });
146
+ }
147
+ },
95
148
  async listUsers ({ where, sort }) {
149
+ const tenant = scopeTenant.getId();
96
150
  let items;
97
151
  try {
98
152
  const ddbItems = await entities.users.queryAll({
99
- partitionKey: `T#${where.tenant}#ADMIN_USERS`,
153
+ partitionKey: `T#${tenant}#ADMIN_USERS`,
100
154
  options: {
101
155
  index: "GSI1"
102
156
  }
@@ -119,7 +173,8 @@ const createStorageOperations = (params)=>{
119
173
  sort
120
174
  });
121
175
  },
122
- async updateUser ({ user }) {
176
+ async updateUser (params) {
177
+ const user = inScope(params.user);
123
178
  const keys = {
124
179
  ...createUserKeys(user),
125
180
  ...createUserGSIKeys(user)
@@ -1 +1 @@
1
- {"version":3,"file":"adminUsers/index.js","sources":["../../src/adminUsers/index.ts"],"sourcesContent":["import type { AdminUsersStorageOperations, CreateAdminUsersStorageOperations } from \"./types.js\";\nimport WebinyError from \"@webiny/error\";\nimport { createTable, type IStandardEntityAttributes, sortItems } from \"@webiny/db-dynamodb\";\nimport { createUserEntity } from \"./definitions/entities.js\";\nimport type {\n AdminUser,\n StorageOperationsGetUserParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\n\nexport const createStorageOperations: CreateAdminUsersStorageOperations = params => {\n const { table: tableName, documentClient } = params;\n\n const table = createTable({\n name: tableName || (process.env.DB_TABLE as string),\n documentClient\n });\n\n const entities = {\n users: createUserEntity(table.table)\n };\n\n const createUserKeys = (user: Pick<AdminUser, \"tenant\" | \"id\">) => ({\n PK: `T#${user.tenant}#ADMIN_USER#${user.id}`,\n SK: `A`\n });\n\n const createUserGSIKeys = (user: AdminUser) => {\n return {\n GSI1_PK: `T#${user.tenant}#ADMIN_USERS`,\n GSI1_SK: user.email,\n GSI_TENANT: user.tenant\n };\n };\n\n const storageOperations: AdminUsersStorageOperations = {\n getTable() {\n return table;\n },\n getEntities() {\n return entities;\n },\n async createUser({ user }) {\n const keys = {\n ...createUserKeys(user),\n ...createUserGSIKeys(user)\n };\n\n try {\n await entities.users.put({\n ...keys,\n TYPE: \"adminUsers.user\",\n data: user\n });\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create admin user.\",\n code: \"CREATE_ADMIN_USER_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteUser({ user }) {\n const keys = createUserKeys(user);\n\n try {\n await entities.users.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete group.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, user }\n });\n }\n },\n async getUser<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserParams\n ): Promise<TUser | null> {\n const {\n where: { tenant, id, email }\n } = params;\n try {\n if (id) {\n const response = await entities.users.get<IStandardEntityAttributes<TUser>>(\n createUserKeys({ tenant, id })\n );\n return (response?.data as TUser) || null;\n }\n\n const response = await entities.users.queryOne<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${tenant}#ADMIN_USERS`,\n options: {\n index: \"GSI1\",\n eq: email\n }\n });\n\n return (response?.data as TUser) || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user.\",\n code: \"GET_ADMIN_USERS_ERROR\",\n data: { id, email }\n });\n }\n },\n async listUsers<TUser extends AdminUser = AdminUser>({\n where,\n sort\n }: StorageOperationsListUsersParams) {\n let items: TUser[];\n try {\n const ddbItems = await entities.users.queryAll<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${where.tenant}#ADMIN_USERS`,\n options: {\n index: \"GSI1\"\n }\n });\n items = ddbItems.map(item => {\n return item.data as TUser;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list users.\",\n code: \"LIST_ADMIN_USERS_ERROR\"\n });\n }\n\n const { id_in, teams_in } = where;\n\n const filtered = items.filter(item => {\n if (Array.isArray(id_in) && !id_in.includes(item.id)) {\n return false;\n }\n if (Array.isArray(teams_in)) {\n return (item.teams || []).some(team => teams_in.includes(team));\n }\n return true;\n });\n\n return sortItems({ items: filtered, sort });\n },\n async updateUser({ user }) {\n const keys = {\n ...createUserKeys(user),\n ...createUserGSIKeys(user)\n };\n\n try {\n await entities.users.put({\n ...keys,\n TYPE: \"adminUsers.user\",\n data: user\n });\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update user.\",\n code: \"UPDATE_ADMIN_USER_ERROR\",\n data: { keys, user }\n });\n }\n }\n };\n\n return storageOperations;\n};\n"],"names":["createStorageOperations","params","tableName","documentClient","table","createTable","process","entities","createUserEntity","createUserKeys","user","createUserGSIKeys","storageOperations","keys","err","WebinyError","tenant","id","email","response","where","sort","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C,OAAO;gBAEX,IAAII,MAAM,OAAO,CAACF,WACd,OAAQF,AAAAA,CAAAA,KAAK,KAAK,IAAI,EAAC,EAAG,IAAI,CAACK,CAAAA,OAAQH,SAAS,QAAQ,CAACG;gBAE7D,OAAO;YACX;YAEA,OAAOC,UAAU;gBAAE,OAAOH;gBAAUN;YAAK;QAC7C;QACA,MAAM,YAAW,EAAEX,IAAI,EAAE;YACrB,MAAMG,OAAO;gBACT,GAAGJ,eAAeC,KAAK;gBACvB,GAAGC,kBAAkBD,KAAK;YAC9B;YAEA,IAAI;gBACA,MAAMH,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,GAAGM,IAAI;oBACP,MAAM;oBACN,MAAMH;gBACV;gBACA,OAAOA;YACX,EAAE,OAAOI,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMH;oBAAK;gBACvB;YACJ;QACJ;IACJ;IAEA,OAAOE;AACX"}
1
+ {"version":3,"file":"adminUsers/index.js","sources":["../../src/adminUsers/index.ts"],"sourcesContent":["import type { AdminUsersStorageOperations, CreateAdminUsersStorageOperations } from \"./types.js\";\nimport WebinyError from \"@webiny/error\";\nimport { createTable, type IStandardEntityAttributes, sortItems } from \"@webiny/db-dynamodb\";\nimport { createUserEntity } from \"./definitions/entities.js\";\nimport type {\n AdminUser,\n StorageOperationsGetUserAcrossTenantsParams,\n StorageOperationsGetUserParams,\n StorageOperationsListUserRecordsParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\n\nexport const createStorageOperations: CreateAdminUsersStorageOperations = params => {\n const { table: tableName, documentClient, scopeTenant } = params;\n\n /** The user with its scope's tenant, whatever tenant it carries. */\n const inScope = <T extends AdminUser>(user: T): T => {\n return { ...user, tenant: scopeTenant.getId() };\n };\n\n const table = createTable({\n name: tableName || (process.env.DB_TABLE as string),\n documentClient\n });\n\n const entities = {\n users: createUserEntity(table.table)\n };\n\n const createUserKeys = (user: Pick<AdminUser, \"tenant\" | \"id\">) => ({\n PK: `T#${user.tenant}#ADMIN_USER#${user.id}`,\n SK: `A`\n });\n\n const createUserIndexPartitionKey = (id: string) => `ADMIN_USER#${id}`;\n\n const createUserGSIKeys = (user: AdminUser) => {\n return {\n GSI1_PK: `T#${user.tenant}#ADMIN_USERS`,\n GSI1_SK: user.email,\n // The user→tenant index: every tenant's record of one user, in one partition.\n GSI2_PK: createUserIndexPartitionKey(user.id),\n GSI2_SK: `T#${user.tenant}`,\n GSI_TENANT: user.tenant\n };\n };\n\n const storageOperations: AdminUsersStorageOperations = {\n getTable() {\n return table;\n },\n getEntities() {\n return entities;\n },\n async createUser(params) {\n const user = inScope(params.user);\n const keys = {\n ...createUserKeys(user),\n ...createUserGSIKeys(user)\n };\n\n try {\n await entities.users.put({\n ...keys,\n TYPE: \"adminUsers.user\",\n data: user\n });\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create admin user.\",\n code: \"CREATE_ADMIN_USER_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteUser(params) {\n const user = inScope(params.user);\n const keys = createUserKeys(user);\n\n try {\n await entities.users.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete group.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, user }\n });\n }\n },\n async getUser<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserParams\n ): Promise<TUser | null> {\n const {\n where: { id, email }\n } = params;\n const tenant = scopeTenant.getId();\n try {\n if (id) {\n const response = await entities.users.get<IStandardEntityAttributes<TUser>>(\n createUserKeys({ tenant, id })\n );\n return (response?.data as TUser) || null;\n }\n\n const response = await entities.users.queryOne<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${tenant}#ADMIN_USERS`,\n options: {\n index: \"GSI1\",\n eq: email\n }\n });\n\n return (response?.data as TUser) || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user.\",\n code: \"GET_ADMIN_USERS_ERROR\",\n data: { id, email }\n });\n }\n },\n // Cross-tenant by design: one user's records in the given tenants, not the scope's tenant.\n async getUserAcrossTenants<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserAcrossTenantsParams\n ): Promise<TUser[]> {\n const { id, tenants } = params;\n if (tenants.length === 0) {\n return [];\n }\n\n try {\n // The batch reader splits the keys into chunks of 100 (the BatchGetItem limit).\n const reader = entities.users.createEntityReader({\n read: tenants.map(tenant => createUserKeys({ tenant, id }))\n });\n const items = await reader.execute();\n\n return items\n .filter(item => !!item?.data)\n .map(item => {\n return item.data as unknown as TUser;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user across tenants.\",\n code: \"GET_ADMIN_USER_ACROSS_TENANTS_ERROR\",\n data: { id, tenants }\n });\n }\n },\n // Cross-tenant by design: every tenant's record of one user.\n async listUserRecords<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsListUserRecordsParams\n ): Promise<TUser[]> {\n const { id } = params;\n\n try {\n const items = await entities.users.queryAll<IStandardEntityAttributes<TUser>>({\n partitionKey: createUserIndexPartitionKey(id),\n options: {\n index: \"GSI2\"\n }\n });\n\n return items.map(item => item.data as TUser);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list user records.\",\n code: \"LIST_ADMIN_USER_RECORDS_ERROR\",\n data: { id }\n });\n }\n },\n async listUsers<TUser extends AdminUser = AdminUser>({\n where,\n sort\n }: StorageOperationsListUsersParams) {\n const tenant = scopeTenant.getId();\n let items: TUser[];\n try {\n const ddbItems = await entities.users.queryAll<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${tenant}#ADMIN_USERS`,\n options: {\n index: \"GSI1\"\n }\n });\n items = ddbItems.map(item => {\n return item.data as TUser;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list users.\",\n code: \"LIST_ADMIN_USERS_ERROR\"\n });\n }\n\n const { id_in, teams_in } = where;\n\n const filtered = items.filter(item => {\n if (Array.isArray(id_in) && !id_in.includes(item.id)) {\n return false;\n }\n if (Array.isArray(teams_in)) {\n return (item.teams || []).some(team => teams_in.includes(team));\n }\n return true;\n });\n\n return sortItems({ items: filtered, sort });\n },\n async updateUser(params) {\n const user = inScope(params.user);\n const keys = {\n ...createUserKeys(user),\n ...createUserGSIKeys(user)\n };\n\n try {\n await entities.users.put({\n ...keys,\n TYPE: \"adminUsers.user\",\n data: user\n });\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update user.\",\n code: \"UPDATE_ADMIN_USER_ERROR\",\n data: { keys, user }\n });\n }\n }\n };\n\n return storageOperations;\n};\n"],"names":["createStorageOperations","params","tableName","documentClient","scopeTenant","inScope","user","table","createTable","process","entities","createUserEntity","createUserKeys","createUserIndexPartitionKey","id","createUserGSIKeys","storageOperations","keys","err","WebinyError","email","tenant","response","tenants","reader","items","item","where","sort","ddbItems","id_in","teams_in","filtered","Array","team","sortItems"],"mappings":";;;AAYO,MAAMA,0BAA6DC,CAAAA;IACtE,MAAM,EAAE,OAAOC,SAAS,EAAEC,cAAc,EAAEC,WAAW,EAAE,GAAGH;IAG1D,MAAMI,UAAU,CAAsBC,OAC3B;YAAE,GAAGA,IAAI;YAAE,QAAQF,YAAY,KAAK;QAAG;IAGlD,MAAMG,QAAQC,YAAY;QACtB,MAAMN,aAAcO,QAAQ,GAAG,CAAC,QAAQ;QACxCN;IACJ;IAEA,MAAMO,WAAW;QACb,OAAOC,iBAAiBJ,MAAM,KAAK;IACvC;IAEA,MAAMK,iBAAiB,CAACN,OAA4C;YAChE,IAAI,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,YAAY,EAAEA,KAAK,EAAE,EAAE;YAC5C,IAAI;QACR;IAEA,MAAMO,8BAA8B,CAACC,KAAe,CAAC,WAAW,EAAEA,IAAI;IAEtE,MAAMC,oBAAoB,CAACT,OAChB;YACH,SAAS,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,YAAY,CAAC;YACvC,SAASA,KAAK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;oBACN,MAAM;wBAAED;wBAAMX;oBAAK;gBACvB;YACJ;QACJ;IACJ;IAEA,OAAOU;AACX"}
@@ -2,12 +2,15 @@ import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js"
2
2
  import type { AdminUsersStorageOperations as BaseAdminUsersStorageOperations } from "@webiny/api-core/types/users.js";
3
3
  import type { IAdminUserEntity } from "../adminUsers/definitions/types.js";
4
4
  import { ITable } from "@webiny/db-dynamodb";
5
+ import type { ScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
5
6
  export declare enum ENTITIES {
6
7
  SYSTEM = "AdminUsers.System",
7
8
  USERS = "AdminUsers.User"
8
9
  }
9
10
  export interface ICreateAdminUsersStorageOperationsParams {
10
11
  documentClient: DynamoDBDocument;
12
+ /** The tenant the storage acts on: its scope's. Reading one user across tenants doesn't use it. */
13
+ scopeTenant: ScopeTenant.Interface;
11
14
  table?: string;
12
15
  }
13
16
  export interface CreateAdminUsersStorageOperations {
@@ -1 +1 @@
1
- {"version":3,"file":"adminUsers/types.js","sources":["../../src/adminUsers/types.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport type { AdminUsersStorageOperations as BaseAdminUsersStorageOperations } from \"@webiny/api-core/types/users.js\";\nimport type { IAdminUserEntity } from \"~/adminUsers/definitions/types.js\";\nimport { ITable } from \"@webiny/db-dynamodb\";\n\nexport enum ENTITIES {\n SYSTEM = \"AdminUsers.System\",\n USERS = \"AdminUsers.User\"\n}\n\nexport interface ICreateAdminUsersStorageOperationsParams {\n documentClient: DynamoDBDocument;\n table?: string;\n}\n\nexport interface CreateAdminUsersStorageOperations {\n (params: ICreateAdminUsersStorageOperationsParams): AdminUsersStorageOperations;\n}\n\nexport interface IAdminUsersGetEntitiesResponse {\n users: IAdminUserEntity;\n}\n\nexport interface AdminUsersStorageOperations extends BaseAdminUsersStorageOperations {\n getTable(): ITable;\n getEntities(): IAdminUsersGetEntitiesResponse;\n}\n"],"names":["ENTITIES"],"mappings":"AAKO,IAAKA,iBAAQA,WAAAA,GAAAA,SAARA,QAAQ;;;WAARA"}
1
+ {"version":3,"file":"adminUsers/types.js","sources":["../../src/adminUsers/types.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport type { AdminUsersStorageOperations as BaseAdminUsersStorageOperations } from \"@webiny/api-core/types/users.js\";\nimport type { IAdminUserEntity } from \"~/adminUsers/definitions/types.js\";\nimport { ITable } from \"@webiny/db-dynamodb\";\nimport type { ScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.js\";\n\nexport enum ENTITIES {\n SYSTEM = \"AdminUsers.System\",\n USERS = \"AdminUsers.User\"\n}\n\nexport interface ICreateAdminUsersStorageOperationsParams {\n documentClient: DynamoDBDocument;\n /** The tenant the storage acts on: its scope's. Reading one user across tenants doesn't use it. */\n scopeTenant: ScopeTenant.Interface;\n table?: string;\n}\n\nexport interface CreateAdminUsersStorageOperations {\n (params: ICreateAdminUsersStorageOperationsParams): AdminUsersStorageOperations;\n}\n\nexport interface IAdminUsersGetEntitiesResponse {\n users: IAdminUserEntity;\n}\n\nexport interface AdminUsersStorageOperations extends BaseAdminUsersStorageOperations {\n getTable(): ITable;\n getEntities(): IAdminUsersGetEntitiesResponse;\n}\n"],"names":["ENTITIES"],"mappings":"AAMO,IAAKA,iBAAQA,WAAAA,GAAAA,SAAAA,QAAAA"}
@@ -1,7 +1,13 @@
1
1
  import type { ApiCoreStorageOperations } from "@webiny/api-core/types/core.js";
2
2
  import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
3
+ import type { ScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
3
4
  interface CreateApiCoreDdbParams {
4
5
  documentClient: DynamoDBDocument;
6
+ /**
7
+ * The tenant the storage acts on: its tenant scope's. The tenant records and the key-value store
8
+ * don't use it (the tenant registry is tenant-neutral, and the store is keyed by its own scope).
9
+ */
10
+ scopeTenant: ScopeTenant.Interface;
5
11
  }
6
- export declare const createApiCoreDdb: ({ documentClient }: CreateApiCoreDdbParams) => ApiCoreStorageOperations;
12
+ export declare const createApiCoreDdb: ({ documentClient, scopeTenant }: CreateApiCoreDdbParams) => ApiCoreStorageOperations;
7
13
  export {};
@@ -4,17 +4,19 @@ import { createStorageOperations as index_js_createStorageOperations } from "./t
4
4
  import { createStorageOperations as external_security_index_js_createStorageOperations } from "./security/index.js";
5
5
  import { createStorageOperations as external_keyValueStore_index_js_createStorageOperations } from "./keyValueStore/index.js";
6
6
  import { DdbServiceManifestLoader } from "./serviceDiscovery/index.js";
7
- const createApiCoreDdb = ({ documentClient })=>{
7
+ const createApiCoreDdb = ({ documentClient, scopeTenant })=>{
8
8
  ServiceDiscovery.setLoader(new DdbServiceManifestLoader(documentClient));
9
9
  return {
10
10
  usersStorageOperations: createStorageOperations({
11
- documentClient
11
+ documentClient,
12
+ scopeTenant
12
13
  }),
13
14
  tenancyStorageOperations: index_js_createStorageOperations({
14
15
  documentClient
15
16
  }),
16
17
  securityStorageOperations: external_security_index_js_createStorageOperations({
17
- documentClient
18
+ documentClient,
19
+ scopeTenant
18
20
  }),
19
21
  keyValueStorageOperations: external_keyValueStore_index_js_createStorageOperations({
20
22
  documentClient
@@ -1 +1 @@
1
- {"version":3,"file":"createApiCoreDdb.js","sources":["../src/createApiCoreDdb.ts"],"sourcesContent":["import type { ApiCoreStorageOperations } from \"@webiny/api-core/types/core.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport { createStorageOperations as createUsersStorageOperations } from \"./adminUsers/index.js\";\nimport { createStorageOperations as createTenancyStorageOperations } from \"./tenancy/index.js\";\nimport { createStorageOperations as createSecurityStorageOperations } from \"./security/index.js\";\nimport { createStorageOperations as createKeyValueStorageOperations } from \"./keyValueStore/index.js\";\nimport { DdbServiceManifestLoader } from \"./serviceDiscovery/index.js\";\n\ninterface CreateApiCoreDdbParams {\n documentClient: DynamoDBDocument;\n}\n\nexport const createApiCoreDdb = ({\n documentClient\n}: CreateApiCoreDdbParams): ApiCoreStorageOperations => {\n ServiceDiscovery.setLoader(new DdbServiceManifestLoader(documentClient));\n\n return {\n usersStorageOperations: createUsersStorageOperations({\n documentClient\n }),\n tenancyStorageOperations: createTenancyStorageOperations({\n documentClient\n }),\n securityStorageOperations: createSecurityStorageOperations({\n documentClient\n }),\n keyValueStorageOperations: createKeyValueStorageOperations({\n documentClient\n })\n };\n};\n"],"names":["createApiCoreDdb","documentClient","ServiceDiscovery","DdbServiceManifestLoader","createUsersStorageOperations","createTenancyStorageOperations","createSecurityStorageOperations","createKeyValueStorageOperations"],"mappings":";;;;;;AAaO,MAAMA,mBAAmB,CAAC,EAC7BC,cAAc,EACO;IACrBC,iBAAiB,SAAS,CAAC,IAAIC,yBAAyBF;IAExD,OAAO;QACH,wBAAwBG,wBAA6B;YACjDH;QACJ;QACA,0BAA0BI,iCAA+B;YACrDJ;QACJ;QACA,2BAA2BK,mDAAgC;YACvDL;QACJ;QACA,2BAA2BM,wDAAgC;YACvDN;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"createApiCoreDdb.js","sources":["../src/createApiCoreDdb.ts"],"sourcesContent":["import type { ApiCoreStorageOperations } from \"@webiny/api-core/types/core.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport { createStorageOperations as createUsersStorageOperations } from \"./adminUsers/index.js\";\nimport { createStorageOperations as createTenancyStorageOperations } from \"./tenancy/index.js\";\nimport { createStorageOperations as createSecurityStorageOperations } from \"./security/index.js\";\nimport { createStorageOperations as createKeyValueStorageOperations } from \"./keyValueStore/index.js\";\nimport { DdbServiceManifestLoader } from \"./serviceDiscovery/index.js\";\nimport type { ScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.js\";\n\ninterface CreateApiCoreDdbParams {\n documentClient: DynamoDBDocument;\n /**\n * The tenant the storage acts on: its tenant scope's. The tenant records and the key-value store\n * don't use it (the tenant registry is tenant-neutral, and the store is keyed by its own scope).\n */\n scopeTenant: ScopeTenant.Interface;\n}\n\nexport const createApiCoreDdb = ({\n documentClient,\n scopeTenant\n}: CreateApiCoreDdbParams): ApiCoreStorageOperations => {\n ServiceDiscovery.setLoader(new DdbServiceManifestLoader(documentClient));\n\n return {\n usersStorageOperations: createUsersStorageOperations({\n documentClient,\n scopeTenant\n }),\n tenancyStorageOperations: createTenancyStorageOperations({\n documentClient\n }),\n securityStorageOperations: createSecurityStorageOperations({\n documentClient,\n scopeTenant\n }),\n keyValueStorageOperations: createKeyValueStorageOperations({\n documentClient\n })\n };\n};\n"],"names":["createApiCoreDdb","documentClient","scopeTenant","ServiceDiscovery","DdbServiceManifestLoader","createUsersStorageOperations","createTenancyStorageOperations","createSecurityStorageOperations","createKeyValueStorageOperations"],"mappings":";;;;;;AAmBO,MAAMA,mBAAmB,CAAC,EAC7BC,cAAc,EACdC,WAAW,EACU;IACrBC,iBAAiB,SAAS,CAAC,IAAIC,yBAAyBH;IAExD,OAAO;QACH,wBAAwBI,wBAA6B;YACjDJ;YACAC;QACJ;QACA,0BAA0BI,iCAA+B;YACrDL;QACJ;QACA,2BAA2BM,mDAAgC;YACvDN;YACAC;QACJ;QACA,2BAA2BM,wDAAgC;YACvDP;QACJ;IACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/api-core-ddb",
3
- "version": "0.0.0-unstable.3fddf667ea",
3
+ "version": "0.0.0-unstable.48a4e5b6c1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./index.js",
@@ -21,20 +21,20 @@
21
21
  "author": "Webiny Ltd.",
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
- "@webiny/api": "0.0.0-unstable.3fddf667ea",
25
- "@webiny/api-core": "0.0.0-unstable.3fddf667ea",
26
- "@webiny/aws-sdk": "0.0.0-unstable.3fddf667ea",
27
- "@webiny/db-dynamodb": "0.0.0-unstable.3fddf667ea",
28
- "@webiny/error": "0.0.0-unstable.3fddf667ea",
29
- "@webiny/feature": "0.0.0-unstable.3fddf667ea"
24
+ "@webiny/api": "0.0.0-unstable.48a4e5b6c1",
25
+ "@webiny/api-core": "0.0.0-unstable.48a4e5b6c1",
26
+ "@webiny/aws-sdk": "0.0.0-unstable.48a4e5b6c1",
27
+ "@webiny/db-dynamodb": "0.0.0-unstable.48a4e5b6c1",
28
+ "@webiny/error": "0.0.0-unstable.48a4e5b6c1",
29
+ "@webiny/feature": "0.0.0-unstable.48a4e5b6c1"
30
30
  },
31
31
  "devDependencies": {
32
- "@webiny/api": "0.0.0-unstable.3fddf667ea",
33
- "@webiny/build-tools": "0.0.0-unstable.3fddf667ea",
32
+ "@webiny/api": "0.0.0-unstable.48a4e5b6c1",
33
+ "@webiny/build-tools": "0.0.0-unstable.48a4e5b6c1",
34
34
  "jest-dynalite": "3.6.1",
35
- "rimraf": "6.1.3",
35
+ "rimraf": "6.1.4",
36
36
  "typescript": "7.0.2",
37
- "vitest": "5.0.5"
37
+ "vitest": "5.1.1"
38
38
  },
39
39
  "publishConfig": {
40
40
  "access": "public"
package/security/index.js CHANGED
@@ -2,7 +2,11 @@ import error from "@webiny/error";
2
2
  import { createApiKeyEntity, createRoleEntity, createTeamEntity } from "./definitions/entities.js";
3
3
  import { createTable, sortItems } from "@webiny/db-dynamodb";
4
4
  const createStorageOperations = (params)=>{
5
- const { table: tableName, documentClient } = params;
5
+ const { table: tableName, documentClient, scopeTenant } = params;
6
+ const inScope = (record)=>({
7
+ ...record,
8
+ tenant: scopeTenant.getId()
9
+ });
6
10
  const table = createTable({
7
11
  name: tableName || process.env.DB_TABLE,
8
12
  documentClient
@@ -45,7 +49,8 @@ const createStorageOperations = (params)=>{
45
49
  TYPE: "security.team"
46
50
  });
47
51
  return {
48
- async createApiKey ({ apiKey }) {
52
+ async createApiKey (params) {
53
+ const apiKey = inScope(params.apiKey);
49
54
  const keys = {
50
55
  ...createApiKeyKeys(apiKey),
51
56
  ...createApiKeyGsiKeys(apiKey)
@@ -65,7 +70,8 @@ const createStorageOperations = (params)=>{
65
70
  });
66
71
  }
67
72
  },
68
- async createRole ({ role }) {
73
+ async createRole (params) {
74
+ const role = inScope(params.role);
69
75
  const keys = {
70
76
  ...createRoleKeys(role),
71
77
  ...createRoleGsiKeys(role)
@@ -85,7 +91,8 @@ const createStorageOperations = (params)=>{
85
91
  });
86
92
  }
87
93
  },
88
- async createTeam ({ team }) {
94
+ async createTeam (params) {
95
+ const team = inScope(params.team);
89
96
  const keys = {
90
97
  ...createTeamKeys(team),
91
98
  ...createTeamGsiKeys(team)
@@ -105,8 +112,8 @@ const createStorageOperations = (params)=>{
105
112
  });
106
113
  }
107
114
  },
108
- async deleteApiKey ({ apiKey }) {
109
- const keys = createApiKeyKeys(apiKey);
115
+ async deleteApiKey (params) {
116
+ const keys = createApiKeyKeys(inScope(params.apiKey));
110
117
  try {
111
118
  await entities.apiKeys.delete(keys);
112
119
  } catch (err) {
@@ -119,7 +126,8 @@ const createStorageOperations = (params)=>{
119
126
  });
120
127
  }
121
128
  },
122
- async deleteRole ({ role }) {
129
+ async deleteRole (params) {
130
+ const role = inScope(params.role);
123
131
  const keys = createRoleKeys(role);
124
132
  try {
125
133
  await entities.roles.delete(keys);
@@ -134,7 +142,8 @@ const createStorageOperations = (params)=>{
134
142
  });
135
143
  }
136
144
  },
137
- async deleteTeam ({ team }) {
145
+ async deleteTeam (params) {
146
+ const team = inScope(params.team);
138
147
  const keys = createTeamKeys(team);
139
148
  try {
140
149
  await entities.teams.delete(keys);
@@ -149,7 +158,9 @@ const createStorageOperations = (params)=>{
149
158
  });
150
159
  }
151
160
  },
152
- async getApiKey ({ id, tenant }) {
161
+ async getApiKey (params) {
162
+ const { id } = params;
163
+ const tenant = scopeTenant.getId();
153
164
  const keys = createApiKeyKeys({
154
165
  id,
155
166
  tenant
@@ -168,7 +179,9 @@ const createStorageOperations = (params)=>{
168
179
  });
169
180
  }
170
181
  },
171
- async getApiKeyByToken ({ tenant, token }) {
182
+ async getApiKeyByToken (params) {
183
+ const { token } = params;
184
+ const tenant = scopeTenant.getId();
172
185
  const queryParams = {
173
186
  partitionKey: `T#${tenant}#API_KEYS`,
174
187
  options: {
@@ -190,7 +203,9 @@ const createStorageOperations = (params)=>{
190
203
  });
191
204
  }
192
205
  },
193
- async getApiKeyBySlug ({ tenant, slug }) {
206
+ async getApiKeyBySlug (params) {
207
+ const { slug } = params;
208
+ const tenant = scopeTenant.getId();
194
209
  const queryParams = {
195
210
  partitionKey: `T#${tenant}#API_KEYS`,
196
211
  options: {
@@ -212,7 +227,9 @@ const createStorageOperations = (params)=>{
212
227
  });
213
228
  }
214
229
  },
215
- async getRole ({ where: { tenant, id, slug } }) {
230
+ async getRole ({ where }) {
231
+ const { id, slug } = where;
232
+ const tenant = scopeTenant.getId();
216
233
  try {
217
234
  if (id) {
218
235
  const result = await entities.roles.get(createRoleKeys({
@@ -240,7 +257,9 @@ const createStorageOperations = (params)=>{
240
257
  });
241
258
  }
242
259
  },
243
- async getTeam ({ where: { tenant, id, slug } }) {
260
+ async getTeam ({ where }) {
261
+ const { id, slug } = where;
262
+ const tenant = scopeTenant.getId();
244
263
  try {
245
264
  if (id) {
246
265
  const result = await entities.teams.get(createTeamKeys({
@@ -268,7 +287,8 @@ const createStorageOperations = (params)=>{
268
287
  });
269
288
  }
270
289
  },
271
- async listApiKeys ({ where: { tenant }, sort }) {
290
+ async listApiKeys ({ sort }) {
291
+ const tenant = scopeTenant.getId();
272
292
  let items;
273
293
  try {
274
294
  items = await entities.apiKeys.queryAll({
@@ -288,7 +308,9 @@ const createStorageOperations = (params)=>{
288
308
  sort
289
309
  }).map((item)=>item.data);
290
310
  },
291
- async listRoles ({ where: { tenant, id_in, slug_in }, sort }) {
311
+ async listRoles ({ where, sort }) {
312
+ const { id_in, slug_in } = where;
313
+ const tenant = scopeTenant.getId();
292
314
  let items;
293
315
  try {
294
316
  const ddbItems = await entities.roles.queryAll({
@@ -312,7 +334,9 @@ const createStorageOperations = (params)=>{
312
334
  if (Array.isArray(slug_in)) return items.filter((item)=>slug_in.includes(item.slug));
313
335
  return items;
314
336
  },
315
- async listTeams ({ where: { tenant, id_in, slug_in }, sort }) {
337
+ async listTeams ({ where, sort }) {
338
+ const { id_in, slug_in } = where;
339
+ const tenant = scopeTenant.getId();
316
340
  let items;
317
341
  try {
318
342
  const ddbRecords = await entities.teams.queryAll({
@@ -336,7 +360,8 @@ const createStorageOperations = (params)=>{
336
360
  if (Array.isArray(slug_in)) return items.filter((item)=>slug_in.includes(item.slug));
337
361
  return items;
338
362
  },
339
- async updateApiKey ({ apiKey }) {
363
+ async updateApiKey (params) {
364
+ const apiKey = inScope(params.apiKey);
340
365
  const keys = {
341
366
  ...createApiKeyKeys(apiKey),
342
367
  ...createApiKeyGsiKeys(apiKey)
@@ -356,7 +381,8 @@ const createStorageOperations = (params)=>{
356
381
  });
357
382
  }
358
383
  },
359
- async updateRole ({ role }) {
384
+ async updateRole (params) {
385
+ const role = inScope(params.role);
360
386
  const keys = createRoleKeys(role);
361
387
  try {
362
388
  await entities.roles.put({
@@ -375,7 +401,8 @@ const createStorageOperations = (params)=>{
375
401
  });
376
402
  }
377
403
  },
378
- async updateTeam ({ team }) {
404
+ async updateTeam (params) {
405
+ const team = inScope(params.team);
379
406
  const keys = createTeamKeys(team);
380
407
  try {
381
408
  await entities.teams.put({
@@ -1 +1 @@
1
- {"version":3,"file":"security/index.js","sources":["../../src/security/index.ts"],"sourcesContent":["import type { SecurityStorageParams } from \"./types.js\";\nimport type {\n StorageApiKey,\n StorageRole,\n SecurityStorageOperations,\n StorageTeam\n} from \"@webiny/api-core/types/security.js\";\nimport WebinyError from \"@webiny/error\";\nimport { createApiKeyEntity, createRoleEntity, createTeamEntity } from \"./definitions/entities.js\";\nimport { createTable, type IEntityQueryOneParams, sortItems } from \"@webiny/db-dynamodb\";\n\nexport const createStorageOperations = (\n params: SecurityStorageParams\n): SecurityStorageOperations => {\n const { table: tableName, documentClient } = params;\n\n const table = createTable({\n name: tableName || (process.env.DB_TABLE as string),\n documentClient\n });\n\n const entities = {\n apiKeys: createApiKeyEntity(table.table),\n roles: createRoleEntity(table.table),\n teams: createTeamEntity(table.table)\n };\n\n const createApiKeyKeys = ({ id, tenant }: Pick<StorageApiKey, \"id\" | \"tenant\">) => ({\n PK: `T#${tenant}#API_KEY#${id}`,\n SK: `A`,\n GSI_TENANT: tenant,\n TYPE: \"security.apiKey\"\n });\n\n const createApiKeyGsiKeys = ({\n slug,\n token,\n tenant\n }: Pick<StorageApiKey, \"slug\" | \"tenant\" | \"token\">) => ({\n GSI1_PK: `T#${tenant}#API_KEYS`,\n GSI1_SK: token,\n GSI2_PK: `T#${tenant}#API_KEYS`,\n GSI2_SK: slug\n });\n\n const createRoleKeys = (role: Pick<StorageRole, \"tenant\" | \"id\">) => ({\n PK: `T#${role.tenant}#ROLE#${role.id}`,\n SK: `A`\n });\n\n const createRoleGsiKeys = (role: Pick<StorageRole, \"tenant\" | \"slug\">) => ({\n GSI1_PK: `T#${role.tenant}#ROLES`,\n GSI1_SK: role.slug,\n GSI_TENANT: role.tenant as string,\n TYPE: \"security.role\"\n });\n\n const createTeamKeys = (team: Pick<StorageTeam, \"tenant\" | \"id\">) => ({\n PK: `T#${team.tenant}#TEAM#${team.id}`,\n SK: `A`\n });\n\n const createTeamGsiKeys = (team: Pick<StorageTeam, \"tenant\" | \"slug\">) => ({\n GSI1_PK: `T#${team.tenant}#TEAMS`,\n GSI1_SK: team.slug,\n GSI_TENANT: team.tenant as string,\n TYPE: \"security.team\"\n });\n\n return {\n async createApiKey({ apiKey }): Promise<void> {\n const keys = {\n ...createApiKeyKeys(apiKey),\n ...createApiKeyGsiKeys(apiKey)\n };\n\n try {\n await entities.apiKeys.put({\n data: apiKey,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create api key.\",\n code: \"CREATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async createRole({ role }): Promise<void> {\n const keys = {\n ...createRoleKeys(role),\n ...createRoleGsiKeys(role)\n };\n\n try {\n await entities.roles.put({\n data: role,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create role.\",\n code: \"CREATE_ROLE_ERROR\",\n data: { keys }\n });\n }\n },\n async createTeam({ team }): Promise<void> {\n const keys = {\n ...createTeamKeys(team),\n ...createTeamGsiKeys(team)\n };\n\n try {\n await entities.teams.put({\n data: team,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create team.\",\n code: \"CREATE_TEAM_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteApiKey({ apiKey }) {\n const keys = createApiKeyKeys(apiKey);\n\n try {\n await entities.apiKeys.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteRole({ role }) {\n const keys = createRoleKeys(role);\n\n try {\n await entities.roles.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete role.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, role }\n });\n }\n },\n async deleteTeam({ team }) {\n const keys = createTeamKeys(team);\n\n try {\n await entities.teams.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete team.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, team }\n });\n }\n },\n async getApiKey({ id, tenant }) {\n const keys = createApiKeyKeys({ id, tenant });\n\n try {\n const response = await entities.apiKeys.get(keys);\n\n return response?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key.\",\n code: \"GET_API_KEY_ERROR\",\n data: { id, keys }\n });\n }\n },\n async getApiKeyByToken({ tenant, token }) {\n const queryParams: IEntityQueryOneParams = {\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n eq: token,\n index: \"GSI1\"\n }\n };\n\n try {\n const result = await entities.apiKeys.queryOne(queryParams);\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by token.\",\n code: \"GET_BY_TOKEN_API_KEY_ERROR\",\n data: { partitionKey: queryParams.partitionKey, options: queryParams.options }\n });\n }\n },\n async getApiKeyBySlug({ tenant, slug }) {\n const queryParams: IEntityQueryOneParams = {\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n eq: slug,\n index: \"GSI2\"\n }\n };\n\n try {\n const result = await entities.apiKeys.queryOne(queryParams);\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by slug.\",\n code: \"GET_BY_SLUG_API_KEY_ERROR\",\n data: { partitionKey: queryParams.partitionKey, options: queryParams.options }\n });\n }\n },\n async getRole({ where: { tenant, id, slug } }) {\n try {\n if (id) {\n const result = await entities.roles.get(createRoleKeys({ tenant, id }));\n return result?.data || null;\n }\n const result = await entities.roles.queryOne({\n partitionKey: `T#${tenant}#ROLES`,\n options: {\n index: \"GSI1\",\n eq: slug\n }\n });\n\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load role.\",\n code: \"GET_ROLE_ERROR\",\n data: { id, slug }\n });\n }\n },\n async getTeam({ where: { tenant, id, slug } }) {\n try {\n if (id) {\n const result = await entities.teams.get(createTeamKeys({ tenant, id }));\n\n return result?.data || null;\n }\n\n const result = await entities.teams.queryOne({\n partitionKey: `T#${tenant}#TEAMS`,\n options: {\n index: \"GSI1\",\n eq: slug\n }\n });\n\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load team.\",\n code: \"GET_TEAM_ERROR\",\n data: { id, slug }\n });\n }\n },\n async listApiKeys({ where: { tenant }, sort }): Promise<StorageApiKey[]> {\n let items;\n try {\n items = await entities.apiKeys.queryAll({\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n index: \"GSI1\"\n }\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list api keys.\",\n code: \"LIST_API_KEY_ERROR\"\n });\n }\n\n return sortItems({ items, sort }).map(item => item.data);\n },\n async listRoles({ where: { tenant, id_in, slug_in }, sort }): Promise<StorageRole[]> {\n let items: StorageRole[];\n try {\n const ddbItems = await entities.roles.queryAll({\n partitionKey: `T#${tenant}#ROLES`,\n options: {\n index: \"GSI1\"\n }\n });\n items = ddbItems.map(item => item.data);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list roles.\",\n code: \"LIST_ROLE_ERROR\"\n });\n }\n\n items = sortItems({ items, sort });\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n if (Array.isArray(slug_in)) {\n return items.filter(item => slug_in.includes(item.slug));\n }\n\n return items;\n },\n async listTeams({ where: { tenant, id_in, slug_in }, sort }): Promise<StorageTeam[]> {\n let items: StorageTeam[];\n try {\n const ddbRecords = await entities.teams.queryAll({\n partitionKey: `T#${tenant}#TEAMS`,\n options: {\n index: \"GSI1\"\n }\n });\n\n items = ddbRecords.map(item => item.data);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list teams.\",\n code: \"LIST_TEAM_ERROR\"\n });\n }\n\n items = sortItems({ items, sort });\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n if (Array.isArray(slug_in)) {\n return items.filter(item => slug_in.includes(item.slug));\n }\n return items;\n },\n async updateApiKey({ apiKey }): Promise<void> {\n const keys = {\n ...createApiKeyKeys(apiKey),\n ...createApiKeyGsiKeys(apiKey)\n };\n\n try {\n await entities.apiKeys.put({\n data: apiKey,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async updateRole({ role }): Promise<void> {\n const keys = createRoleKeys(role);\n\n try {\n await entities.roles.put({\n data: role,\n ...keys,\n ...createRoleGsiKeys(role)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update role.\",\n code: \"UPDATE_ROLE_ERROR\",\n data: { keys, role }\n });\n }\n },\n async updateTeam({ team }): Promise<void> {\n const keys = createTeamKeys(team);\n\n try {\n await entities.teams.put({\n data: team,\n ...keys,\n ...createTeamGsiKeys(team)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update team.\",\n code: \"UPDATE_TEAM_ERROR\",\n data: { keys, team }\n });\n }\n }\n };\n};\n"],"names":["createStorageOperations","params","tableName","documentClient","table","createTable","process","entities","createApiKeyEntity","createRoleEntity","createTeamEntity","createApiKeyKeys","id","tenant","createApiKeyGsiKeys","slug","token","createRoleKeys","role","createRoleGsiKeys","createTeamKeys","team","createTeamGsiKeys","apiKey","keys","err","WebinyError","response","queryParams","result","sort","items","sortItems","item","id_in","slug_in","ddbItems","Array","ddbRecords"],"mappings":";;;AAWO,MAAMA,0BAA0B,CACnCC;IAEA,MAAM,EAAE,OAAOC,SAAS,EAAEC,cAAc,EAAE,GAAGF;IAE7C,MAAMG,QAAQC,YAAY;QACtB,MAAMH,aAAcI,QAAQ,GAAG,CAAC,QAAQ;QACxCH;IACJ;IAEA,MAAMI,WAAW;QACb,SAASC,mBAAmBJ,MAAM,KAAK;QACvC,OAAOK,iBAAiBL,MAAM,KAAK;QACnC,OAAOM,iBAAiBN,MAAM,KAAK;IACvC;IAEA,MAAMO,mBAAmB,CAAC,EAAEC,EAAE,EAAEC,MAAM,EAAwC,GAAM;YAChF,IAAI,CAAC,EAAE,EAAEA,OAAO,SAAS,EAAED,IAAI;YAC/B,IAAI;YACJ,YAAYC;YACZ,MAAM;QACV;IAEA,MAAMC,sBAAsB,CAAC,EACzBC,IAAI,EACJC,KAAK,EACLH,MAAM,EACyC,GAAM;YACrD,SAAS,CAAC,EAAE,EAAEA,OAAO,SAAS,CAAC;YAC/B,SAASG;YACT,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gB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMN;oBAAK;gBACvB;YACJ;QACJ;QACA,MAAM,YAAW,EAAEG,IAAI,EAAE;YACrB,MAAMG,OAAOJ,eAAeC;YAE5B,IAAI;gBACA,MAAMd,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,MAAMc;oBACN,GAAGG,IAAI;oBACP,GAAGF,kBAAkBD,KAAK;gBAC9B;YACJ,EAAE,OAAOI,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMH;oBAAK;gBACvB;YACJ;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"security/index.js","sources":["../../src/security/index.ts"],"sourcesContent":["import type { SecurityStorageParams } from \"./types.js\";\nimport type {\n StorageApiKey,\n StorageRole,\n SecurityStorageOperations,\n StorageTeam\n} from \"@webiny/api-core/types/security.js\";\nimport WebinyError from \"@webiny/error\";\nimport { createApiKeyEntity, createRoleEntity, createTeamEntity } from \"./definitions/entities.js\";\nimport { createTable, type IEntityQueryOneParams, sortItems } from \"@webiny/db-dynamodb\";\n\nexport const createStorageOperations = (\n params: SecurityStorageParams\n): SecurityStorageOperations => {\n const { table: tableName, documentClient, scopeTenant } = params;\n\n /** The record with its scope's tenant, whatever tenant it carries. */\n const inScope = <T extends { tenant?: string | null }>(record: T): T & { tenant: string } => {\n return { ...record, tenant: scopeTenant.getId() };\n };\n\n const table = createTable({\n name: tableName || (process.env.DB_TABLE as string),\n documentClient\n });\n\n const entities = {\n apiKeys: createApiKeyEntity(table.table),\n roles: createRoleEntity(table.table),\n teams: createTeamEntity(table.table)\n };\n\n const createApiKeyKeys = ({ id, tenant }: Pick<StorageApiKey, \"id\" | \"tenant\">) => ({\n PK: `T#${tenant}#API_KEY#${id}`,\n SK: `A`,\n GSI_TENANT: tenant,\n TYPE: \"security.apiKey\"\n });\n\n const createApiKeyGsiKeys = ({\n slug,\n token,\n tenant\n }: Pick<StorageApiKey, \"slug\" | \"tenant\" | \"token\">) => ({\n GSI1_PK: `T#${tenant}#API_KEYS`,\n GSI1_SK: token,\n GSI2_PK: `T#${tenant}#API_KEYS`,\n GSI2_SK: slug\n });\n\n const createRoleKeys = (role: Pick<StorageRole, \"tenant\" | \"id\">) => ({\n PK: `T#${role.tenant}#ROLE#${role.id}`,\n SK: `A`\n });\n\n const createRoleGsiKeys = (role: Pick<StorageRole, \"tenant\" | \"slug\">) => ({\n GSI1_PK: `T#${role.tenant}#ROLES`,\n GSI1_SK: role.slug,\n GSI_TENANT: role.tenant as string,\n TYPE: \"security.role\"\n });\n\n const createTeamKeys = (team: Pick<StorageTeam, \"tenant\" | \"id\">) => ({\n PK: `T#${team.tenant}#TEAM#${team.id}`,\n SK: `A`\n });\n\n const createTeamGsiKeys = (team: Pick<StorageTeam, \"tenant\" | \"slug\">) => ({\n GSI1_PK: `T#${team.tenant}#TEAMS`,\n GSI1_SK: team.slug,\n GSI_TENANT: team.tenant as string,\n TYPE: \"security.team\"\n });\n\n return {\n async createApiKey(params): Promise<void> {\n const apiKey = inScope(params.apiKey);\n const keys = {\n ...createApiKeyKeys(apiKey),\n ...createApiKeyGsiKeys(apiKey)\n };\n\n try {\n await entities.apiKeys.put({\n data: apiKey,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create api key.\",\n code: \"CREATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async createRole(params): Promise<void> {\n const role = inScope(params.role);\n const keys = {\n ...createRoleKeys(role),\n ...createRoleGsiKeys(role)\n };\n\n try {\n await entities.roles.put({\n data: role,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create role.\",\n code: \"CREATE_ROLE_ERROR\",\n data: { keys }\n });\n }\n },\n async createTeam(params): Promise<void> {\n const team = inScope(params.team);\n const keys = {\n ...createTeamKeys(team),\n ...createTeamGsiKeys(team)\n };\n\n try {\n await entities.teams.put({\n data: team,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create team.\",\n code: \"CREATE_TEAM_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteApiKey(params) {\n const keys = createApiKeyKeys(inScope(params.apiKey));\n\n try {\n await entities.apiKeys.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteRole(params) {\n const role = inScope(params.role);\n const keys = createRoleKeys(role);\n\n try {\n await entities.roles.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete role.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, role }\n });\n }\n },\n async deleteTeam(params) {\n const team = inScope(params.team);\n const keys = createTeamKeys(team);\n\n try {\n await entities.teams.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete team.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, team }\n });\n }\n },\n async getApiKey(params) {\n const { id } = params;\n const tenant = scopeTenant.getId();\n const keys = createApiKeyKeys({ id, tenant });\n\n try {\n const response = await entities.apiKeys.get(keys);\n\n return response?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key.\",\n code: \"GET_API_KEY_ERROR\",\n data: { id, keys }\n });\n }\n },\n async getApiKeyByToken(params) {\n const { token } = params;\n const tenant = scopeTenant.getId();\n const queryParams: IEntityQueryOneParams = {\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n eq: token,\n index: \"GSI1\"\n }\n };\n\n try {\n const result = await entities.apiKeys.queryOne(queryParams);\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by token.\",\n code: \"GET_BY_TOKEN_API_KEY_ERROR\",\n data: { partitionKey: queryParams.partitionKey, options: queryParams.options }\n });\n }\n },\n async getApiKeyBySlug(params) {\n const { slug } = params;\n const tenant = scopeTenant.getId();\n const queryParams: IEntityQueryOneParams = {\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n eq: slug,\n index: \"GSI2\"\n }\n };\n\n try {\n const result = await entities.apiKeys.queryOne(queryParams);\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by slug.\",\n code: \"GET_BY_SLUG_API_KEY_ERROR\",\n data: { partitionKey: queryParams.partitionKey, options: queryParams.options }\n });\n }\n },\n async getRole({ where }) {\n const { id, slug } = where;\n const tenant = scopeTenant.getId();\n try {\n if (id) {\n const result = await entities.roles.get(createRoleKeys({ tenant, id }));\n return result?.data || null;\n }\n const result = await entities.roles.queryOne({\n partitionKey: `T#${tenant}#ROLES`,\n options: {\n index: \"GSI1\",\n eq: slug\n }\n });\n\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load role.\",\n code: \"GET_ROLE_ERROR\",\n data: { id, slug }\n });\n }\n },\n async getTeam({ where }) {\n const { id, slug } = where;\n const tenant = scopeTenant.getId();\n try {\n if (id) {\n const result = await entities.teams.get(createTeamKeys({ tenant, id }));\n\n return result?.data || null;\n }\n\n const result = await entities.teams.queryOne({\n partitionKey: `T#${tenant}#TEAMS`,\n options: {\n index: \"GSI1\",\n eq: slug\n }\n });\n\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load team.\",\n code: \"GET_TEAM_ERROR\",\n data: { id, slug }\n });\n }\n },\n async listApiKeys({ sort }): Promise<StorageApiKey[]> {\n const tenant = scopeTenant.getId();\n let items;\n try {\n items = await entities.apiKeys.queryAll({\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n index: \"GSI1\"\n }\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list api keys.\",\n code: \"LIST_API_KEY_ERROR\"\n });\n }\n\n return sortItems({ items, sort }).map(item => item.data);\n },\n async listRoles({ where, sort }): Promise<StorageRole[]> {\n const { id_in, slug_in } = where;\n const tenant = scopeTenant.getId();\n let items: StorageRole[];\n try {\n const ddbItems = await entities.roles.queryAll({\n partitionKey: `T#${tenant}#ROLES`,\n options: {\n index: \"GSI1\"\n }\n });\n items = ddbItems.map(item => item.data);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list roles.\",\n code: \"LIST_ROLE_ERROR\"\n });\n }\n\n items = sortItems({ items, sort });\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n if (Array.isArray(slug_in)) {\n return items.filter(item => slug_in.includes(item.slug));\n }\n\n return items;\n },\n async listTeams({ where, sort }): Promise<StorageTeam[]> {\n const { id_in, slug_in } = where;\n const tenant = scopeTenant.getId();\n let items: StorageTeam[];\n try {\n const ddbRecords = await entities.teams.queryAll({\n partitionKey: `T#${tenant}#TEAMS`,\n options: {\n index: \"GSI1\"\n }\n });\n\n items = ddbRecords.map(item => item.data);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list teams.\",\n code: \"LIST_TEAM_ERROR\"\n });\n }\n\n items = sortItems({ items, sort });\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n if (Array.isArray(slug_in)) {\n return items.filter(item => slug_in.includes(item.slug));\n }\n return items;\n },\n async updateApiKey(params): Promise<void> {\n const apiKey = inScope(params.apiKey);\n const keys = {\n ...createApiKeyKeys(apiKey),\n ...createApiKeyGsiKeys(apiKey)\n };\n\n try {\n await entities.apiKeys.put({\n data: apiKey,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async updateRole(params): Promise<void> {\n const role = inScope(params.role);\n const keys = createRoleKeys(role);\n\n try {\n await entities.roles.put({\n data: role,\n ...keys,\n ...createRoleGsiKeys(role)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update role.\",\n code: \"UPDATE_ROLE_ERROR\",\n data: { keys, role }\n });\n }\n },\n async updateTeam(params): Promise<void> {\n const team = inScope(params.team);\n const keys = createTeamKeys(team);\n\n try {\n await entities.teams.put({\n data: team,\n ...keys,\n ...createTeamGsiKeys(team)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update team.\",\n code: \"UPDATE_TEAM_ERROR\",\n data: { keys, team }\n });\n }\n }\n };\n};\n"],"names":["createStorageOperations","params","tableName","documentClient","scopeTenant","inScope","record","table","createTable","process","entities","createApiKeyEntity","createRoleEntity","createTeamEntity","createApiKeyKeys","id","tenant","createApiKeyGsiKeys","slug","token","createRoleKeys","role","createRoleGsiKeys","createTeamKeys","team","createTeamGsiKeys","apiKey","keys","err","WebinyError","response","queryParams","result","where","sort","items","sortItems","item","id_in","slug_in","ddbItems","Array","ddbRecords"],"mappings":";;;AAWO,MAAMA,0BAA0B,CACnCC;IAEA,MAAM,EAAE,OAAOC,SAAS,EAAEC,cAAc,EAAEC,WAAW,EAAE,GAAGH;IAG1D,MAAMI,UAAU,CAAuCC,SAC5C;YAAE,GAAGA,MAAM;YAAE,QAAQF,YAAY,KAAK;QAAG;IAGpD,MAAMG,QAAQC,YAAY;QACtB,MAAMN,aAAcO,QAAQ,GAAG,CAAC,QAAQ;QACxCN;IACJ;IAEA,MAAMO,WAAW;QACb,SAASC,mBAAmBJ,MAAM,KAAK;QACvC,OAAOK,iBAAiBL,MAAM,KAAK;QACnC,OAAOM,iBAAiBN,MAAM,KAAK;IACvC;IAEA,MAAMO,mBAAmB,CAAC,EAAEC,EAAE,EAAEC,MAAM,EAAwC,GAAM;YAChF,IAAI,CAAC,EAAE,EAAEA,OAAO,SAAS,EAAED,IAAI;YAC/B,IAAI;YACJ,YAAYC;YACZ,MAAM;QACV;IAEA,MAAMC,sBAAsB,CAAC,EACzBC,IAAI,EACJC,KAAK,EACLH,MAAM,EACyC,GAAM;YACrD,SAAS,CAAC,EAAE,EAAEA,OAAO,SAAS,CAAC;YAC/B,SAASG;YACT,SAAS,CAAC,EAAE,EAAEH,OAAO,SAAS,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oBAAoBS,OAAO;YAClC;YAEA,IAAI;gBACA,MAAMhB,SAAS,OAAO,CAAC,GAAG,CAAC;oBACvB,MAAMgB;oBACN,GAAGC,IAAI;gBACX;YACJ,EAAE,OAAOC,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;oBAAK;gBACjB;YACJ;QACJ;QACA,MAAM,YAAW1B,MAAM;YACnB,MAAMoB,OAAOhB,QAAQJ,OAAO,IAAI;YAChC,MAAM0B,OAAOP,eAAeC;YAE5B,IAAI;gBACA,MAAMX,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,MAAMW;oBACN,GAAGM,IAAI;oBACP,GAAGL,kBAAkBD,KAAK;gBAC9B;YACJ,EAAE,OAAOO,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMN;oBAAK;gBACvB;YACJ;QACJ;QACA,MAAM,YAAWpB,MAAM;YACnB,MAAMuB,OAAOnB,QAAQJ,OAAO,IAAI;YAChC,MAAM0B,OAAOJ,eAAeC;YAE5B,IAAI;gBACA,MAAMd,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,MAAMc;oBACN,GAAGG,IAAI;oBACP,GAAGF,kBAAkBD,KAAK;gBAC9B;YACJ,EAAE,OAAOI,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMH;oBAAK;gBACvB;YACJ;QACJ;IACJ;AACJ"}
@@ -1,4 +1,5 @@
1
1
  import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
2
+ import type { ScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
2
3
  export declare enum ENTITIES {
3
4
  API_KEY = "SecurityApiKey",
4
5
  ROLE = "SecurityRole",
@@ -6,5 +7,7 @@ export declare enum ENTITIES {
6
7
  }
7
8
  export interface SecurityStorageParams {
8
9
  documentClient: DynamoDBDocument;
10
+ /** The tenant the storage acts on: its scope's. */
11
+ scopeTenant: ScopeTenant.Interface;
9
12
  table?: string;
10
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"security/types.js","sources":["../../src/security/types.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\n\nexport enum ENTITIES {\n API_KEY = \"SecurityApiKey\",\n ROLE = \"SecurityRole\",\n TEAM = \"SecurityTeam\"\n}\n\nexport interface SecurityStorageParams {\n documentClient: DynamoDBDocument;\n table?: string;\n}\n"],"names":["ENTITIES"],"mappings":"AAEO,IAAKA,iBAAQA,WAAAA,GAAAA,SAARA,QAAQ;;;;WAARA"}
1
+ {"version":3,"file":"security/types.js","sources":["../../src/security/types.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport type { ScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.js\";\n\nexport enum ENTITIES {\n API_KEY = \"SecurityApiKey\",\n ROLE = \"SecurityRole\",\n TEAM = \"SecurityTeam\"\n}\n\nexport interface SecurityStorageParams {\n documentClient: DynamoDBDocument;\n /** The tenant the storage acts on: its scope's. */\n scopeTenant: ScopeTenant.Interface;\n table?: string;\n}\n"],"names":["ENTITIES"],"mappings":"AAGO,IAAKA,iBAAQA,WAAAA,GAAAA,SAAAA,QAAAA"}
package/tenancy/index.js CHANGED
@@ -2,9 +2,18 @@ import { createTable } from "@webiny/db-dynamodb";
2
2
  import error from "@webiny/error";
3
3
  import { createTenantEntity } from "./definitions/tenantEntity.js";
4
4
  import { ENTITIES } from "./types.js";
5
+ import { TenantPath } from "@webiny/api-core/features/tenancy/shared/TenantPath.js";
6
+ const MAX_SORT_KEY_BYTES = 1024;
7
+ const createGsi1Sk = (tenant)=>{
8
+ const parentPath = TenantPath.fromStored(tenant).parent();
9
+ return `T#${parentPath ? parentPath.toString() : "null"}#${tenant.createdOn}`;
10
+ };
11
+ const childrenKeyPrefix = (path)=>`T#${path.toString()}#`;
12
+ const grandchildrenKeyPrefix = (path)=>`T#${path.descendantsPrefix()}`;
5
13
  const setTenantDefaults = (item)=>{
6
14
  if (!item.tags) item.tags = [];
7
15
  if (!item.description) item.description = "";
16
+ item.path = TenantPath.fromStored(item).toString();
8
17
  return item;
9
18
  };
10
19
  const createStorageOperations = (params)=>{
@@ -37,26 +46,48 @@ const createStorageOperations = (params)=>{
37
46
  return tenants.map((item)=>item.data).map((item)=>setTenantDefaults(item));
38
47
  },
39
48
  async listTenants (params = {}) {
40
- const { parent } = params;
41
- const options = {
42
- index: "GSI1"
49
+ const { parent, descendants } = params;
50
+ const query = async (options)=>{
51
+ const items = await entities.tenants.queryAll({
52
+ partitionKey: "TENANTS",
53
+ options: {
54
+ index: "GSI1",
55
+ ...options
56
+ }
57
+ });
58
+ return items.map((item)=>setTenantDefaults(item.data));
43
59
  };
44
- if (parent) options.beginsWith = `T#${parent}#`;
45
- else options.gt = " ";
46
- const tenants = await entities.tenants.queryAll({
47
- partitionKey: "TENANTS",
48
- options
60
+ if (!parent) return query({
61
+ gt: " "
49
62
  });
50
- return tenants.map((item)=>item.data).map((item)=>setTenantDefaults(item));
63
+ const children = await query({
64
+ beginsWith: childrenKeyPrefix(parent.path)
65
+ });
66
+ if (!descendants) return children;
67
+ const deeper = await query({
68
+ beginsWith: grandchildrenKeyPrefix(parent.path)
69
+ });
70
+ return [
71
+ ...children,
72
+ ...deeper
73
+ ];
51
74
  },
52
75
  async createTenant (data) {
53
76
  const keys = {
54
77
  PK: `T#${data.id}`,
55
78
  SK: "A",
56
79
  GSI1_PK: "TENANTS",
57
- GSI1_SK: `T#${data.parent}#${data.createdOn}`,
80
+ GSI1_SK: createGsi1Sk(data),
58
81
  GSI_TENANT: data.id
59
82
  };
83
+ if (Buffer.byteLength(keys.GSI1_SK, "utf8") > MAX_SORT_KEY_BYTES) throw new error({
84
+ message: `Tenant "${data.id}" is nested too deeply: its path "${data.path}" is too long to be stored.`,
85
+ code: "TENANT_PATH_TOO_LONG",
86
+ data: {
87
+ id: data.id,
88
+ path: data.path
89
+ }
90
+ });
60
91
  try {
61
92
  await entities.tenants.put({
62
93
  TYPE: "tenancy.tenant",
@@ -81,7 +112,7 @@ const createStorageOperations = (params)=>{
81
112
  PK: tenantPK,
82
113
  SK: "A",
83
114
  GSI1_PK: "TENANTS",
84
- GSI1_SK: `T#${data.parent}#${data.createdOn}`,
115
+ GSI1_SK: createGsi1Sk(data),
85
116
  GSI_TENANT: data.id,
86
117
  TYPE: "tenancy.tenant"
87
118
  };
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy/index.js","sources":["../../src/tenancy/index.ts"],"sourcesContent":["import { createTable, type IEntityQueryAllParams } from \"@webiny/db-dynamodb\";\nimport WebinyError from \"@webiny/error\";\nimport { createTenantEntity } from \"./definitions/tenantEntity.js\";\nimport type { CreateTenancyStorageOperations } from \"./types.js\";\nimport { ENTITIES } from \"./types.js\";\nimport type { ListTenantsParams, Tenant } from \"@webiny/api-core/types/tenancy.js\";\n\nconst setTenantDefaults = (item: Tenant) => {\n if (!item.tags) {\n item.tags = [];\n }\n\n if (!item.description) {\n item.description = \"\";\n }\n\n return item;\n};\n\nexport const createStorageOperations: CreateTenancyStorageOperations = params => {\n const { documentClient } = params;\n\n const tableInstance = createTable({\n name: (process.env.DB_TABLE_TENANCY || process.env.DB_TABLE) as string,\n documentClient\n });\n\n const entities = {\n tenants: createTenantEntity({\n entityName: ENTITIES.TENANT,\n table: tableInstance.table\n })\n };\n\n return {\n getTable() {\n return tableInstance;\n },\n getEntities() {\n return entities;\n },\n\n async getTenantsByIds(ids: string[]): Promise<Tenant[]> {\n const batchReader = entities.tenants.createEntityReader({\n read: ids.map(id => {\n return {\n PK: `T#${id}`,\n SK: \"A\"\n };\n })\n });\n const tenants = await batchReader.execute();\n\n return tenants\n .map(item => {\n return item.data;\n })\n .map(item => {\n return setTenantDefaults(item);\n });\n },\n\n async listTenants(params: ListTenantsParams = {}): Promise<Tenant[]> {\n const { parent } = params;\n\n const options: IEntityQueryAllParams[\"options\"] = {\n index: \"GSI1\"\n };\n\n if (parent) {\n options.beginsWith = `T#${parent}#`;\n } else {\n options.gt = \" \";\n }\n\n const tenants = await entities.tenants.queryAll({\n partitionKey: `TENANTS`,\n options\n });\n\n return tenants\n .map(item => {\n return item.data;\n })\n .map(item => {\n return setTenantDefaults(item);\n });\n },\n\n async createTenant(data: Tenant): Promise<Tenant> {\n const keys = {\n PK: `T#${data.id}`,\n SK: \"A\",\n GSI1_PK: \"TENANTS\",\n GSI1_SK: `T#${data.parent}#${data.createdOn}`,\n GSI_TENANT: data.id\n };\n\n try {\n await entities.tenants.put({\n TYPE: \"tenancy.tenant\",\n ...keys,\n data\n });\n\n return data;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create tenant record.\",\n code: \"CREATE_TENANT_ERROR\",\n data: {\n keys,\n data\n }\n });\n }\n },\n\n async updateTenant(data: Tenant): Promise<Tenant> {\n const tenantPK = `T#${data.id}`;\n\n const keys = {\n PK: tenantPK,\n SK: \"A\",\n GSI1_PK: \"TENANTS\",\n GSI1_SK: `T#${data.parent}#${data.createdOn}`,\n GSI_TENANT: data.id,\n TYPE: \"tenancy.tenant\"\n };\n\n try {\n await entities.tenants.put({\n ...keys,\n data\n });\n return data;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update tenant record.\",\n code: \"CREATE_TENANT_ERROR\",\n data: { keys, data }\n });\n }\n },\n\n async deleteTenant(id: string): Promise<void> {\n await entities.tenants.delete({\n PK: `T#${id}`,\n SK: \"A\"\n });\n }\n };\n};\n"],"names":["setTenantDefaults","item","createStorageOperations","params","documentClient","tableInstance","createTable","process","entities","createTenantEntity","ENTITIES","ids","batchReader","id","tenants","parent","options","data","keys","err","WebinyError","tenantPK"],"mappings":";;;;AAOA,MAAMA,oBAAoB,CAACC;IACvB,IAAI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B,IAAY;YAC3B,MAAMC,OAAO;gBACT,IAAI,CAAC,EAAE,EAAED,KAAK,EAAE,EAAE;gBAClB,IAAI;gBACJ,SAAS;gBACT,SAAS,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,CAAC,EAAEA,KAAK,SAAS,EAAE;gBAC7C,YAAYA,KAAK,EAAE;YACvB;YAEA,IAAI;gBACA,MAAMT,SAAS,OAAO,CAAC,GAAG,CAAC;oBACvB,MAAM;oBACN,GAAGU,IAAI;oBACPD;gBACJ;gBAEA,OAAOA;YACX,EAAE,OAAOE,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBACFD;wBACAD;oBACJ;gBACJ;YACJ;QACJ;QAEA,MAAM,cAAaA,IAAY;YAC3B,MAAMI,WAAW,CAAC,EAAE,EAAEJ,KAAK,EAAE,EAAE;YAE/B,MAAMC,OAAO;gBACT,IAAIG;gBACJ,IAAI;gBACJ,SAAS;gBACT,SAAS,CAAC,EAAE,EAAEJ,KAAK,MAAM,CAAC,CAAC,EAAEA,KAAK,SAAS,EAAE;gBAC7C,YAAYA,KAAK,EAAE;gBACnB,MAAM;YACV;YAEA,IAAI;gBACA,MAAMT,SAAS,OAAO,CAAC,GAAG,CAAC;oBACvB,GAAGU,IAAI;oBACPD;gBACJ;gBACA,OAAOA;YACX,EAAE,OAAOE,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMD;oBAAK;gBACvB;YACJ;QACJ;QAEA,MAAM,cAAaJ,EAAU;YACzB,MAAML,SAAS,OAAO,CAAC,MAAM,CAAC;gBAC1B,IAAI,CAAC,EAAE,EAAEK,IAAI;gBACb,IAAI;YACR;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"tenancy/index.js","sources":["../../src/tenancy/index.ts"],"sourcesContent":["import { createTable, type IEntityQueryAllParams } from \"@webiny/db-dynamodb\";\nimport WebinyError from \"@webiny/error\";\nimport { createTenantEntity } from \"./definitions/tenantEntity.js\";\nimport type { CreateTenancyStorageOperations } from \"./types.js\";\nimport { ENTITIES } from \"./types.js\";\nimport type { ListTenantsStorageParams, Tenant } from \"@webiny/api-core/types/tenancy.js\";\nimport { TenantPath } from \"@webiny/api-core/features/tenancy/shared/TenantPath.js\";\n\n/* DynamoDB's limit for a sort key, in bytes. */\nconst MAX_SORT_KEY_BYTES = 1024;\n\n/*\n * The catalog's sort key: `T#` + the parent's path + `#` + createdOn. Root's is `T#null#…` and a\n * first-level tenant's `T#root#…`, exactly the keys written before paths existed, so those records\n * need no backfill. A deeper tenant's is `T#root/A#…`. Ids contain neither `/` nor `#`, so the\n * character after a path tells its children (`T#root/A#…`) from the rest of its subtree\n * (`T#root/A/…`): each is one exact `begins_with`, and a sibling `AB` (`T#root/AB…`) is in neither.\n */\nconst createGsi1Sk = (tenant: Tenant) => {\n const parentPath = TenantPath.fromStored(tenant).parent();\n return `T#${parentPath ? parentPath.toString() : \"null\"}#${tenant.createdOn}`;\n};\n\n/* The key prefix of the tenant's direct children. */\nconst childrenKeyPrefix = (path: TenantPath) => `T#${path.toString()}#`;\n\n/* The key prefix of every tenant below the tenant's children (`T#` + its descendants prefix). */\nconst grandchildrenKeyPrefix = (path: TenantPath) => `T#${path.descendantsPrefix()}`;\n\nconst setTenantDefaults = (item: Tenant) => {\n if (!item.tags) {\n item.tags = [];\n }\n\n if (!item.description) {\n item.description = \"\";\n }\n\n item.path = TenantPath.fromStored(item).toString();\n return item;\n};\n\nexport const createStorageOperations: CreateTenancyStorageOperations = params => {\n const { documentClient } = params;\n\n const tableInstance = createTable({\n name: (process.env.DB_TABLE_TENANCY || process.env.DB_TABLE) as string,\n documentClient\n });\n\n const entities = {\n tenants: createTenantEntity({\n entityName: ENTITIES.TENANT,\n table: tableInstance.table\n })\n };\n\n return {\n getTable() {\n return tableInstance;\n },\n getEntities() {\n return entities;\n },\n\n async getTenantsByIds(ids: string[]): Promise<Tenant[]> {\n const batchReader = entities.tenants.createEntityReader({\n read: ids.map(id => {\n return {\n PK: `T#${id}`,\n SK: \"A\"\n };\n })\n });\n const tenants = await batchReader.execute();\n\n return tenants\n .map(item => {\n return item.data;\n })\n .map(item => {\n return setTenantDefaults(item);\n });\n },\n\n async listTenants(params: ListTenantsStorageParams = {}): Promise<Tenant[]> {\n const { parent, descendants } = params;\n\n const query = async (options: IEntityQueryAllParams[\"options\"]) => {\n const items = await entities.tenants.queryAll({\n partitionKey: `TENANTS`,\n options: { index: \"GSI1\", ...options }\n });\n return items.map(item => setTenantDefaults(item.data));\n };\n\n if (!parent) {\n return query({ gt: \" \" });\n }\n\n const children = await query({ beginsWith: childrenKeyPrefix(parent.path) });\n if (!descendants) {\n return children;\n }\n const deeper = await query({ beginsWith: grandchildrenKeyPrefix(parent.path) });\n return [...children, ...deeper];\n },\n\n async createTenant(data: Tenant): Promise<Tenant> {\n const keys = {\n PK: `T#${data.id}`,\n SK: \"A\",\n GSI1_PK: \"TENANTS\",\n GSI1_SK: createGsi1Sk(data),\n GSI_TENANT: data.id\n };\n\n /* The deeper the tenant, the longer its key: refuse one DynamoDB can't index. */\n if (Buffer.byteLength(keys.GSI1_SK, \"utf8\") > MAX_SORT_KEY_BYTES) {\n throw new WebinyError({\n message: `Tenant \"${data.id}\" is nested too deeply: its path \"${data.path}\" is too long to be stored.`,\n code: \"TENANT_PATH_TOO_LONG\",\n data: { id: data.id, path: data.path }\n });\n }\n\n try {\n await entities.tenants.put({\n TYPE: \"tenancy.tenant\",\n ...keys,\n data\n });\n\n return data;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create tenant record.\",\n code: \"CREATE_TENANT_ERROR\",\n data: {\n keys,\n data\n }\n });\n }\n },\n\n async updateTenant(data: Tenant): Promise<Tenant> {\n const tenantPK = `T#${data.id}`;\n\n const keys = {\n PK: tenantPK,\n SK: \"A\",\n GSI1_PK: \"TENANTS\",\n GSI1_SK: createGsi1Sk(data),\n GSI_TENANT: data.id,\n TYPE: \"tenancy.tenant\"\n };\n\n try {\n await entities.tenants.put({\n ...keys,\n data\n });\n return data;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update tenant record.\",\n code: \"CREATE_TENANT_ERROR\",\n data: { keys, data }\n });\n }\n },\n\n async deleteTenant(id: string): Promise<void> {\n await entities.tenants.delete({\n PK: `T#${id}`,\n SK: \"A\"\n });\n }\n };\n};\n"],"names":["MAX_SORT_KEY_BYTES","createGsi1Sk","tenant","parentPath","TenantPath","childrenKeyPrefix","path","grandchildrenKeyPrefix","setTenantDefaults","item","createStorageOperations","params","documentClient","tableInstance","createTable","process","entities","createTenantEntity","ENTITIES","ids","batchReader","id","tenants","parent","descendants","query","options","items","children","deeper","data","keys","Buffer","WebinyError","err","tenantPK"],"mappings":";;;;;AASA,MAAMA,qBAAqB;AAS3B,MAAMC,eAAe,CAACC;IAClB,MAAMC,aAAaC,WAAW,UAAU,CAACF,QAAQ,MAAM;IACvD,OAAO,CAAC,EAAE,EAAEC,aAAaA,WAAW,QAAQ,KAAK,OAAO,CAAC,EAAED,OAAO,SAAS,EAAE;AACjF;AAGA,MAAMG,oBAAoB,CAACC,OAAqB,CAAC,EAAE,EAAEA,KAAK,QAAQ,GAAG,CAAC,CAAC;AAGvE,MAAMC,yBAAyB,CAACD,OAAqB,CAAC,EAAE,EAAEA,KAAK,iBAAiB,IAAI;AAEpF,MAAME,oBAAoB,CAACC;IACvB,IAAI,CAACA,KAAK,IAAI,EACVA,KAAK,IAAI,GAAG,EAAE;IAGlB,IAAI,CAACA,KAAK,WAAW,EACjBA,KAAK,WAAW,GAAG;IAGvBA,KAAK,IAAI,GAAGL,WAAW,UAAU,CAACK,MAAM,QAAQ;IAChD,OAAOA;AACX;AAEO,MAAMC,0BAA0DC,CAAAA;IACnE,MAAM,EAAEC,cAAc,EAAE,GAAGD;IAE3B,MAAME,gBAAgBC,YAAY;QAC9B,MAAOC,QAAQ,GAAG,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;IACJ;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy/types.js","sources":["../../src/tenancy/types.ts"],"sourcesContent":["import type { TenancyStorageOperations } from \"@webiny/api-core/types/tenancy.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\n\nexport enum ENTITIES {\n TENANT = \"TenancyTenant\"\n}\n\nexport interface CreateTenancyStorageOperations {\n (params: { documentClient: DynamoDBDocument }): TenancyStorageOperations;\n}\n"],"names":["ENTITIES"],"mappings":"AAGO,IAAKA,iBAAQA,WAAAA,GAAAA,SAARA,QAAQ;;WAARA"}
1
+ {"version":3,"file":"tenancy/types.js","sources":["../../src/tenancy/types.ts"],"sourcesContent":["import type { TenancyStorageOperations } from \"@webiny/api-core/types/tenancy.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\n\nexport enum ENTITIES {\n TENANT = \"TenancyTenant\"\n}\n\nexport interface CreateTenancyStorageOperations {\n (params: { documentClient: DynamoDBDocument }): TenancyStorageOperations;\n}\n"],"names":["ENTITIES"],"mappings":"AAGO,IAAKA,iBAAQA,WAAAA,GAAAA,SAAAA,QAAAA"}