@chevre/domain 22.11.0-alpha.10 → 22.11.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,13 +9,11 @@ async function main() {
9
9
  const roleRepo = await chevre.repository.Role.createInstance(mongoose.connection);
10
10
 
11
11
  const roleNames = [
12
- chevre.factory.role.organizationRole.RoleName.AdminInventoryManager
12
+ 'projectCreator'
13
13
  ];
14
14
  const permissions = [
15
- 'iam.members.me.read',
16
- 'admin.creativeWorks.*',
17
- 'admin.sellers.eventSeries.*',
18
- 'admin.sellers.read'
15
+ 'aggregations.read',
16
+ 'projects.create'
19
17
  ];
20
18
  for (const roleName of roleNames) {
21
19
  const existingRoles = await roleRepo.projectFields(
@@ -26,8 +24,8 @@ async function main() {
26
24
  );
27
25
  if (existingRoles.length === 0) {
28
26
  const createResult = await roleRepo.create({
29
- roleName: roleName,
30
- member: { typeOf: chevre.factory.creativeWorkType.SoftwareApplication },
27
+ roleName: <any>roleName,
28
+ member: { typeOf: chevre.factory.personType.Person },
31
29
  memberOf: { typeOf: chevre.factory.organizationType.Project },
32
30
  permissions: []
33
31
  });
@@ -35,7 +33,7 @@ async function main() {
35
33
  }
36
34
  for (const permission of permissions) {
37
35
  const result = await roleRepo.addPermissionIfNotExists({
38
- roleName: { $eq: roleName },
36
+ roleName: { $eq: <any>roleName },
39
37
  permission
40
38
  });
41
39
  console.log('permission added.', result, roleName);
@@ -0,0 +1,71 @@
1
+ // tslint:disable:no-console
2
+ import type { CognitoIdentityProvider as CognitoIdentityServiceProvider } from '@aws-sdk/client-cognito-identity-provider';
3
+ import * as mongoose from 'mongoose';
4
+
5
+ import { chevre } from '../../../../lib/index';
6
+
7
+ const { PROJECT_CREATOR_SUB } = process.env;
8
+ const project = { id: '*' };
9
+
10
+ let cognitoIdentityServiceProvider: CognitoIdentityServiceProvider | undefined;
11
+
12
+ async function main() {
13
+ if (typeof PROJECT_CREATOR_SUB !== 'string') {
14
+ throw new Error('PROJECT_CREATOR_SUB setting required');
15
+ }
16
+
17
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
18
+
19
+ const memberRepo = await chevre.repository.Member.createInstance(mongoose.connection);
20
+ const settingRepo = await chevre.repository.Setting.createInstance(mongoose.connection);
21
+ const setting = await settingRepo.findOne({ project: { id: { $eq: '*' } } }, ['userPoolIdNew']);
22
+ if (typeof setting?.userPoolIdNew !== 'string') {
23
+ throw new chevre.factory.errors.NotFound('setting.userPoolIdNew');
24
+ }
25
+
26
+ let member: chevre.factory.iam.IMemberOfRole;
27
+
28
+ if (cognitoIdentityServiceProvider === undefined) {
29
+ const { CognitoIdentityProvider } = await import('@aws-sdk/client-cognito-identity-provider');
30
+ const { fromEnv } = await import('@aws-sdk/credential-providers');
31
+ cognitoIdentityServiceProvider = new CognitoIdentityProvider({
32
+ apiVersion: 'latest',
33
+ region: 'ap-northeast-1',
34
+ credentials: fromEnv()
35
+ });
36
+ }
37
+ const personRepo = await chevre.repository.Person.createInstance({
38
+ userPoolId: setting.userPoolIdNew,
39
+ cognitoIdentityServiceProvider
40
+ });
41
+ const profile = await personRepo.findById({ userId: PROJECT_CREATOR_SUB });
42
+ const memberName = (typeof profile.givenName === 'string' && typeof profile.familyName === 'string')
43
+ ? `${profile.givenName} ${profile.familyName}`
44
+ : profile.memberOf?.membershipNumber;
45
+
46
+ member = {
47
+ typeOf: chevre.factory.personType.Person,
48
+ id: profile.id,
49
+ memberOf: { id: project.id, typeOf: chevre.factory.organizationType.Project },
50
+ name: memberName,
51
+ username: profile.memberOf?.membershipNumber,
52
+ hasRole: [{
53
+ typeOf: chevre.factory.role.RoleType.OrganizationRole,
54
+ roleName: <any>'projectCreator'
55
+ }]
56
+ };
57
+ console.log(profile, member);
58
+
59
+ // 権限作成
60
+ await memberRepo.create([{
61
+ project: { typeOf: chevre.factory.organizationType.Project, id: project.id },
62
+ typeOf: chevre.factory.role.RoleType.OrganizationRole,
63
+ member: member
64
+ }]);
65
+ }
66
+
67
+ main()
68
+ .then(() => {
69
+ console.log('success!');
70
+ })
71
+ .catch(console.error);
@@ -0,0 +1,183 @@
1
+ // tslint:disable:no-implicit-dependencies no-console no-magic-numbers
2
+ import { ManagementClient } from 'auth0';
3
+ import { readFileSync } from 'fs';
4
+ import * as moment from 'moment';
5
+ // import * as crypto from 'crypto'; // client_secret 生成用 (PKJWTなしの場合)
6
+ // import { JWK, importPKCS8, generateKeyPair, SignJWT } from 'jose'; // Private Key JWT 用
7
+
8
+ const PUBLIC_KEY_FILE_PATH = `${__dirname}/../../samplePublicKey.pem`;
9
+ const { AUTH0_DOMAIN, AUTH0_MGMT_CLIENT_ID, AUTH0_MGMT_CLIENT_SECRET, AUTH0_MGMT_API_AUDIENCE, AUTH0_AUDIENCE } = process.env;
10
+
11
+ if (typeof AUTH0_DOMAIN !== 'string'
12
+ || typeof AUTH0_MGMT_CLIENT_ID !== 'string'
13
+ || typeof AUTH0_MGMT_CLIENT_SECRET !== 'string'
14
+ || typeof AUTH0_MGMT_API_AUDIENCE !== 'string'
15
+ || typeof AUTH0_AUDIENCE !== 'string'
16
+ ) {
17
+ throw new Error('set envs!');
18
+ }
19
+
20
+ // --- Auth0 ManagementClient の初期化 ---
21
+ const management = new ManagementClient({
22
+ domain: AUTH0_DOMAIN,
23
+ clientId: AUTH0_MGMT_CLIENT_ID,
24
+ clientSecret: AUTH0_MGMT_CLIENT_SECRET,
25
+ audience: AUTH0_MGMT_API_AUDIENCE
26
+ // scope: 'read:clients create:clients' // 必要なスコープを明示
27
+ });
28
+
29
+ async function sleep(waitInSeconds: number) {
30
+ await new Promise<void>((resolve) => {
31
+ setTimeout(
32
+ () => {
33
+ resolve();
34
+ },
35
+ waitInSeconds
36
+ );
37
+ });
38
+ }
39
+
40
+ /**
41
+ * アプリケーションを検索し、存在しなければ作成します。
42
+ * Private Key JWT 認証を使用する前提。
43
+ */
44
+ async function findOrCreateServiceAccount(
45
+ appName: string,
46
+ projectId: string,
47
+ roles: string[],
48
+ audience: string
49
+ ) {
50
+ try {
51
+ console.log('getting organization...');
52
+ const getOrganizationResponse = await management.organizations.getByName({
53
+ name: projectId
54
+ });
55
+ const organization = getOrganizationResponse.data;
56
+ console.log('organization exists.', organization);
57
+
58
+ const newClient = (await management.clients.create({
59
+ name: appName,
60
+ app_type: 'non_interactive', // Machine to Machine アプリケーション
61
+ jwt_configuration: { // Private Key JWT の設定
62
+ alg: 'RS256' // 署名アルゴリズム
63
+ },
64
+ // token_endpoint_auth_method: 'client_secret_post',
65
+ client_authentication_methods: {
66
+ private_key_jwt: {
67
+ credentials: [{
68
+ alg: 'RS256',
69
+ /**
70
+ * Credential type. Supported types: public_key.
71
+ *
72
+ */
73
+ credential_type: 'public_key',
74
+ // name?: string;
75
+ pem: readFileSync(PUBLIC_KEY_FILE_PATH, 'utf8')
76
+
77
+ }]
78
+ }
79
+ },
80
+ grant_types: ['client_credentials'],
81
+ organization_usage: 'require', // 組織での利用を許可
82
+ default_organization: {
83
+ organization_id: organization.id,
84
+ flows: ['client_credentials']
85
+ },
86
+ oidc_conformant: true,
87
+ client_metadata: {
88
+ roles: JSON.stringify(roles)
89
+ }
90
+ })).data;
91
+ console.log(`Successfully created new application: ${newClient.client_id} (${newClient.name})`);
92
+
93
+ console.log(`checking clientGrant... ${newClient.client_id} (${newClient.name})`);
94
+ await sleep(3000);
95
+
96
+ let clientGrant = (await management.clientGrants.getAll({
97
+ audience,
98
+ client_id: newClient.client_id
99
+ })).data.shift();
100
+ if (clientGrant === undefined) {
101
+ clientGrant = (await management.clientGrants.create({
102
+ client_id: newClient.client_id,
103
+ audience,
104
+ organization_usage: 'require',
105
+ allow_any_organization: false,
106
+ scope: ['iam.members.me.read']
107
+ })).data;
108
+ console.log(`clientGrant created. ${newClient.client_id} (${newClient.name})`);
109
+ } else {
110
+ console.log(`clientGrant already exists. ${newClient.client_id} (${newClient.name})`);
111
+ }
112
+
113
+ console.log(`checking organizationClientGrant... ${newClient.client_id} (${newClient.name})`);
114
+ await sleep(3000);
115
+ const organizationClientGrant = (await management.organizations.getOrganizationClientGrants({
116
+ id: organization.id,
117
+ audience: 'https://development.apis.smart-theater.com',
118
+ client_id: newClient.client_id
119
+ })).data.shift();
120
+ if (organizationClientGrant === undefined) {
121
+ await management.organizations.postOrganizationClientGrants(
122
+ {
123
+ id: organization.id
124
+ },
125
+ {
126
+ grant_id: clientGrant.id
127
+ }
128
+ );
129
+ console.log(`organizationClientGrant created. ${newClient.client_id} (${newClient.name})`);
130
+ } else {
131
+ console.log(`organizationClientGrant already exists. ${newClient.client_id} (${newClient.name})`);
132
+ }
133
+
134
+ // 1. アプリケーションを検索 (名前で検索するのが一般的)
135
+ console.log('searching for applications...');
136
+ await sleep(3000);
137
+
138
+ await searchClients({ organization });
139
+ } catch (error) {
140
+ console.error(`Error finding or creating application: ${error.message}`);
141
+ throw error;
142
+ }
143
+ }
144
+
145
+ async function searchClients(params: {
146
+ organization: { id: string };
147
+ }) {
148
+ const existingApps = await management.clients.getAll({
149
+ include_totals: true,
150
+ // app_type: 'non_interactive',
151
+ // is_global: false,
152
+ // page: 0,
153
+ // per_page: 50,
154
+ // q: `name:"${appName}"`, // 名前で検索
155
+ q: `client_grant.organization_id:"${params.organization.id}"`,
156
+ // from: undefined,
157
+ take: 50
158
+ // is_client_credentials: true // Machine to Machine アプリケーションに絞る
159
+ });
160
+ const clients = existingApps.data.clients;
161
+ console.log(clients.length, 'existingApps exist.', clients);
162
+ console.log(clients.length, 'clients found.');
163
+ }
164
+
165
+ export async function run() {
166
+ if (typeof AUTH0_AUDIENCE !== 'string') {
167
+ throw new Error('set envs!');
168
+ }
169
+
170
+ try {
171
+ await findOrCreateServiceAccount(
172
+ `sampleServiceAccount-${moment()
173
+ .format('YYYY-MM-DDTHH:mm:ss')}`,
174
+ 'cinerino',
175
+ ['inventoryManager', 'user'],
176
+ AUTH0_AUDIENCE
177
+ );
178
+ } catch (error) {
179
+ console.error('Failed to run provisioning script:', error);
180
+ }
181
+ }
182
+
183
+ run();
@@ -0,0 +1,55 @@
1
+ // tslint:disable:no-implicit-dependencies no-console
2
+ interface IAuth0Config {
3
+ auth0Domain: string;
4
+ clientId: string;
5
+ clientSecret: string;
6
+ audience: string;
7
+ }
8
+
9
+ // 環境変数から機密情報を取得することを強く推奨します
10
+ const config: IAuth0Config = {
11
+ auth0Domain: String(process.env.AUTH0_DOMAIN),
12
+ clientId: String(process.env.AUTH0_CLIENT_ID),
13
+ clientSecret: String(process.env.AUTH0_CLIENT_SECRET),
14
+ audience: String(process.env.AUTH0_AUDIENCE)
15
+ // scopes: process.env.OKTA_SCOPES || 'api_access_scope openid', // 必要なスコープを指定
16
+ // authServerId: 'aussd9v86wlIar3cX697', // デフォルト承認サーバーを使用する場合はコメントアウトまたは指定しない
17
+ };
18
+
19
+ async function getToken() {
20
+ try {
21
+ const response = await fetch(
22
+ `https://${config.auth0Domain}/oauth/token`,
23
+ {
24
+ method: 'POST',
25
+ headers: { 'content-type': 'application/json' },
26
+ body: JSON.stringify({
27
+ client_id: config.clientId,
28
+ client_secret: config.clientSecret,
29
+ audience: config.audience,
30
+ grant_type: 'client_credentials'
31
+ // organization: 'org_zuMP9ng42QSgZ5Kn'
32
+ })
33
+ });
34
+
35
+ if (!response.ok) {
36
+ console.log(await response.json());
37
+ throw new Error('Network response was not ok');
38
+ }
39
+
40
+ const data = await response.json();
41
+ console.log(data);
42
+
43
+ return data;
44
+ } catch (error) {
45
+ console.error('Error fetching token:', error);
46
+ }
47
+ }
48
+
49
+ export async function main() {
50
+ const token = await getToken();
51
+ console.log(token);
52
+ }
53
+
54
+ main()
55
+ .catch(console.error);
@@ -0,0 +1,84 @@
1
+ // tslint:disable:no-implicit-dependencies no-console
2
+ import * as crypto from 'crypto';
3
+ import { readFileSync } from 'fs';
4
+ import { SignJWT } from 'jose';
5
+ import * as uuid from 'uuid';
6
+
7
+ const PRIVATE_KEY_FILE_PATH = `${__dirname}/../../samplePrivateKey.pem`;
8
+
9
+ interface IAuth0Config {
10
+ auth0Domain: string;
11
+ clientId: string;
12
+ privateKeyContent: string; // PEM形式の秘密鍵の内容 (例: fs.readFileSync('private_key.pem', 'utf8'))
13
+ audience: string;
14
+ }
15
+
16
+ // 環境変数から機密情報を取得することを強く推奨します
17
+ const auth0config: IAuth0Config = {
18
+ auth0Domain: String(process.env.AUTH0_DOMAIN),
19
+ clientId: String(process.env.AUTH0_CLIENT_ID),
20
+ // keyId: 'xxx',
21
+ privateKeyContent: readFileSync(PRIVATE_KEY_FILE_PATH, 'utf8'), // 秘密鍵の内容を読み込む
22
+ audience: String(process.env.AUTH0_AUDIENCE)
23
+ // scopes: process.env.OKTA_SCOPES || 'api_access_scope openid', // 必要なスコープを指定
24
+ // authServerId: 'aussd9v86wlIar3cX697', // デフォルト承認サーバーを使用する場合はコメントアウトまたは指定しない
25
+ };
26
+
27
+ async function generateJwtAssertion(config: IAuth0Config) {
28
+ const privateKeyPEM = crypto.createPrivateKey(readFileSync(PRIVATE_KEY_FILE_PATH, 'utf8'));
29
+
30
+ return new SignJWT({})
31
+ .setProtectedHeader({
32
+ alg: 'RS256' // or RS384 or PS256
33
+ // kid: '(OPTIONAL) KID_GENERATED_BY_AUTH0'
34
+ })
35
+ .setIssuedAt()
36
+ .setIssuer(config.clientId)
37
+ .setSubject(config.clientId)
38
+ .setAudience(`https://${config.auth0Domain}/`)
39
+ .setExpirationTime('1m')
40
+ .setJti(uuid.v4())
41
+ .sign(privateKeyPEM);
42
+ }
43
+
44
+ async function getToken() {
45
+ try {
46
+ const jwtAssertion = await generateJwtAssertion(auth0config);
47
+ console.log('jwtAssertion:', jwtAssertion);
48
+
49
+ const body = new URLSearchParams({
50
+ grant_type: 'client_credentials',
51
+ client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
52
+ client_assertion: jwtAssertion,
53
+ audience: auth0config.audience
54
+ // scope: config.scopes,
55
+ }).toString();
56
+ const response = await fetch(
57
+ `https://${auth0config.auth0Domain}/oauth/token`,
58
+ {
59
+ method: 'POST',
60
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
61
+ body: body
62
+ });
63
+
64
+ if (!response.ok) {
65
+ console.log(await response.json());
66
+ throw new Error('Network response was not ok');
67
+ }
68
+
69
+ const data = await response.json();
70
+ console.log(data);
71
+
72
+ return data;
73
+ } catch (error) {
74
+ console.error('Error fetching token:', error);
75
+ }
76
+ }
77
+
78
+ export async function main() {
79
+ const token = await getToken();
80
+ console.log(token);
81
+ }
82
+
83
+ main()
84
+ .catch(console.error);
@@ -125,6 +125,7 @@ export declare class MemberRepo {
125
125
  }): Promise<import("mongodb").DeleteResult>;
126
126
  /**
127
127
  * メンバーの権限を持つプロジェクト検索
128
+ * ANY_PROJECT_IDは除外
128
129
  */
129
130
  searchProjectIdsByMemberId(params: {
130
131
  member: {
@@ -18,6 +18,7 @@ const AVAILABLE_PROJECT_FIELDS = [
18
18
  'typeOf',
19
19
  'member'
20
20
  ];
21
+ const ANY_PROJECT_ID = '*';
21
22
  /**
22
23
  * IAMメンバーリポジトリ
23
24
  */
@@ -112,7 +113,7 @@ class MemberRepo {
112
113
  throw new factory.errors.ArgumentNull('project.id');
113
114
  }
114
115
  const filterQueries = MemberRepo.CREATE_MONGO_CONDITIONS({
115
- project: { id: { $in: [params.project.id, '*'] } }, // 全プロジェクトで利用可能なクライアントを考慮(2025-01-11~)
116
+ project: { id: { $in: [params.project.id, ANY_PROJECT_ID] } }, // 全プロジェクトで利用可能なクライアントを考慮(2025-01-11~)
116
117
  member: {
117
118
  typeOf: { $eq: factory.creativeWorkType.WebApplication },
118
119
  memberOf: { typeOf: { $eq: factory.organizationType.Project } }, // プロジェクトメンバーのはず
@@ -283,6 +284,7 @@ class MemberRepo {
283
284
  }
284
285
  /**
285
286
  * メンバーの権限を持つプロジェクト検索
287
+ * ANY_PROJECT_IDは除外
286
288
  */
287
289
  searchProjectIdsByMemberId(params) {
288
290
  return __awaiter(this, void 0, void 0, function* () {
@@ -293,7 +295,10 @@ class MemberRepo {
293
295
  if (typeof params.page !== 'number') {
294
296
  throw new factory.errors.ArgumentNull('page');
295
297
  }
296
- const matchStages = [{ $match: { 'member.id': { $eq: params.member.id } } }];
298
+ const matchStages = [
299
+ { $match: { 'member.id': { $eq: params.member.id } } },
300
+ { $match: { 'project.id': { $ne: ANY_PROJECT_ID } } }
301
+ ];
297
302
  if (typeof ((_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$eq) === 'string') {
298
303
  matchStages.push({ $match: { 'project.id': { $eq: params.project.id.$eq } } });
299
304
  }
package/package.json CHANGED
@@ -49,10 +49,12 @@
49
49
  "@types/sinon-mongoose": "^1.3.11",
50
50
  "@types/uniqid": "^4.1.3",
51
51
  "@types/uuid": "^3.4.10",
52
+ "auth0": "4.27.0",
52
53
  "coveralls": "^3.1.0",
53
54
  "csvtojson": "^2.0.10",
54
55
  "eslint": "9.16.0",
55
56
  "googleapis": "^85.0.0",
57
+ "jose": "6.0.12",
56
58
  "json2csv": "4.5.4",
57
59
  "mocha": "10.6.0",
58
60
  "mongoose": "8.0.4",
@@ -113,5 +115,5 @@
113
115
  "postversion": "git push origin --tags",
114
116
  "prepublishOnly": "npm run clean && npm run build && npm test && npm run doc"
115
117
  },
116
- "version": "22.11.0-alpha.10"
118
+ "version": "22.11.0-alpha.11"
117
119
  }