@chevre/domain 22.11.0-alpha.9 → 22.12.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/example/src/chevre/aggregation/aggregateOrderOfCustomer.ts +25 -11
  2. package/example/src/chevre/aggregation/aggregateOrderOfCustomerGlobally.ts +34 -0
  3. package/example/src/chevre/aggregation/aggregateTasks.ts +41 -0
  4. package/example/src/chevre/checkCustomerAttributesLength.ts +109 -0
  5. package/example/src/chevre/notifyAbortedTasksByEmail.ts +1 -1
  6. package/example/src/chevre/reIndex.ts +1 -1
  7. package/example/src/chevre/roles/addEventOfferPermissionIfNotExists.ts +27 -0
  8. package/example/src/chevre/roles/{addAdminInventoryManagerRole.ts → addProjectCreatorRole.ts} +6 -8
  9. package/example/src/chevre/roles/assignGlobalRoles.ts +72 -0
  10. package/example/src/chevre/roles/findPermissions.ts +84 -0
  11. package/example/src/chevre/roles/findRoleNames.ts +117 -0
  12. package/example/src/chevre/roles/removeConsolePermissionIfExists.ts +38 -0
  13. package/example/src/chevre/searchEventSeats.ts +1 -1
  14. package/example/src/chevre/searchProducts.ts +28 -0
  15. package/example/src/chevre/settings/addSettings.ts +31 -17
  16. package/example/src/chevre/task/countPotentiallyRunning.ts +41 -0
  17. package/example/src/chevre/task/countTasks.ts +51 -0
  18. package/example/src/chevre/{deleteRunsAtPassedCertainPeriod.ts → task/deleteRunsAtPassedCertainPeriod.ts} +4 -3
  19. package/example/src/chevre/task/deleteUnexpectedTasks.ts +23 -0
  20. package/example/src/chevre/task/emitRunning.ts +89 -0
  21. package/example/src/idaas/auth0/adminApplications.ts +183 -0
  22. package/example/src/idaas/auth0/getToken.ts +55 -0
  23. package/example/src/idaas/auth0/getTokenByPrivateKeyJWT.ts +84 -0
  24. package/example/src/regex.ts +31 -0
  25. package/lib/chevre/eventEmitter/task.d.ts +29 -6
  26. package/lib/chevre/factory/event.d.ts +1 -1
  27. package/lib/chevre/index.d.ts +0 -2
  28. package/lib/chevre/index.js +0 -10
  29. package/lib/chevre/repo/event.js +1 -1
  30. package/lib/chevre/repo/member.d.ts +22 -4
  31. package/lib/chevre/repo/member.js +81 -27
  32. package/lib/chevre/repo/mongoose/schemas/aggregateOrder.js +9 -0
  33. package/lib/chevre/repo/mongoose/schemas/event.js +1 -0
  34. package/lib/chevre/repo/mongoose/schemas/member/global.d.ts +14 -0
  35. package/lib/chevre/repo/mongoose/schemas/member/global.js +82 -0
  36. package/lib/chevre/repo/mongoose/schemas/product.js +9 -0
  37. package/lib/chevre/repo/mongoose/schemas/setting.d.ts +15 -0
  38. package/lib/chevre/repo/mongoose/schemas/setting.js +1 -0
  39. package/lib/chevre/repo/mongoose/schemas/task.js +9 -0
  40. package/lib/chevre/repo/order.d.ts +23 -2
  41. package/lib/chevre/repo/order.js +70 -8
  42. package/lib/chevre/repo/pendingReservation.js +1 -0
  43. package/lib/chevre/repo/product.js +12 -17
  44. package/lib/chevre/repo/role.d.ts +5 -4
  45. package/lib/chevre/repo/role.js +35 -32
  46. package/lib/chevre/repo/setting.d.ts +1 -10
  47. package/lib/chevre/repo/setting.js +2 -11
  48. package/lib/chevre/repo/stockHolder.d.ts +4 -27
  49. package/lib/chevre/repo/stockHolder.js +163 -175
  50. package/lib/chevre/repo/task.d.ts +58 -38
  51. package/lib/chevre/repo/task.js +126 -296
  52. package/lib/chevre/repo/transaction.js +10 -10
  53. package/lib/chevre/service/aggregation/event/aggregateScreeningEvent.js +7 -4
  54. package/lib/chevre/service/assetTransaction/cancelReservation/start.d.ts +1 -1
  55. package/lib/chevre/service/assetTransaction/registerService.js +4 -0
  56. package/lib/chevre/service/assetTransaction/reserve/start/createSubReservations.js +19 -16
  57. package/lib/chevre/service/assetTransaction/reserve/start.js +5 -1
  58. package/lib/chevre/service/code.d.ts +5 -28
  59. package/lib/chevre/service/code.js +3 -79
  60. package/lib/chevre/service/iam.d.ts +17 -7
  61. package/lib/chevre/service/iam.js +26 -6
  62. package/lib/chevre/service/notification/notifyAbortedTasksByEmail.d.ts +15 -0
  63. package/lib/chevre/service/notification/notifyAbortedTasksByEmail.js +38 -0
  64. package/lib/chevre/service/notification.d.ts +2 -1
  65. package/lib/chevre/service/notification.js +3 -1
  66. package/lib/chevre/service/offer/product.js +4 -0
  67. package/lib/chevre/service/order/confirmPayTransaction.d.ts +6 -1
  68. package/lib/chevre/service/order/onOrderStatusChanged/onOrderProcessing/processOrder.js +3 -3
  69. package/lib/chevre/service/task/acceptCOAOffer.d.ts +1 -1
  70. package/lib/chevre/service/task/aggregateOffers.d.ts +1 -1
  71. package/lib/chevre/service/task/aggregateOffers.js +1 -1
  72. package/lib/chevre/service/task/aggregateOnSystem.d.ts +4 -2
  73. package/lib/chevre/service/task/aggregateScreeningEvent.d.ts +1 -1
  74. package/lib/chevre/service/task/aggregateScreeningEvent.js +1 -1
  75. package/lib/chevre/service/task/authorizePayment.d.ts +1 -1
  76. package/lib/chevre/service/task/cancelMoneyTransfer.d.ts +1 -1
  77. package/lib/chevre/service/task/cancelPendingReservation.d.ts +1 -1
  78. package/lib/chevre/service/task/cancelPendingReservation.js +1 -1
  79. package/lib/chevre/service/task/cancelReservation.d.ts +1 -1
  80. package/lib/chevre/service/task/cancelReservation.js +1 -1
  81. package/lib/chevre/service/task/checkMovieTicket.d.ts +1 -1
  82. package/lib/chevre/service/task/checkResource.d.ts +1 -1
  83. package/lib/chevre/service/task/checkResource.js +1 -1
  84. package/lib/chevre/service/task/confirmMoneyTransfer.d.ts +1 -1
  85. package/lib/chevre/service/task/confirmPayTransaction.d.ts +2 -2
  86. package/lib/chevre/service/task/confirmPayTransaction.js +3 -2
  87. package/lib/chevre/service/task/confirmRegisterService.d.ts +1 -1
  88. package/lib/chevre/service/task/confirmRegisterServiceTransaction.d.ts +1 -1
  89. package/lib/chevre/service/task/confirmReserveTransaction.d.ts +6 -2
  90. package/lib/chevre/service/task/confirmReserveTransaction.js +3 -3
  91. package/lib/chevre/service/task/createAccountingReport.d.ts +1 -1
  92. package/lib/chevre/service/task/createEvent.d.ts +1 -1
  93. package/lib/chevre/service/task/deletePerson.d.ts +1 -1
  94. package/lib/chevre/service/task/deleteTransaction.d.ts +1 -1
  95. package/lib/chevre/service/task/givePointAward.d.ts +1 -1
  96. package/lib/chevre/service/task/handleNotification.d.ts +4 -2
  97. package/lib/chevre/service/task/importEventCapacitiesFromCOA.d.ts +1 -1
  98. package/lib/chevre/service/task/importEventsFromCOA.d.ts +1 -1
  99. package/lib/chevre/service/task/importOffersFromCOA.d.ts +1 -1
  100. package/lib/chevre/service/task/invalidatePaymentUrl.d.ts +1 -1
  101. package/lib/chevre/service/task/moneyTransfer.d.ts +1 -1
  102. package/lib/chevre/service/task/onAssetTransactionStatusChanged.d.ts +1 -1
  103. package/lib/chevre/service/task/onAuthorizationCreated.d.ts +1 -1
  104. package/lib/chevre/service/task/onEventChanged.d.ts +1 -1
  105. package/lib/chevre/service/task/onOrderPaymentCompleted.d.ts +1 -1
  106. package/lib/chevre/service/task/onResourceUpdated.d.ts +1 -1
  107. package/lib/chevre/service/task/pay.d.ts +1 -1
  108. package/lib/chevre/service/task/placeOrder.d.ts +1 -1
  109. package/lib/chevre/service/task/publishPaymentUrl.d.ts +1 -1
  110. package/lib/chevre/service/task/refund.d.ts +1 -1
  111. package/lib/chevre/service/task/registerService.d.ts +1 -1
  112. package/lib/chevre/service/task/reserve.d.ts +1 -1
  113. package/lib/chevre/service/task/returnMoneyTransfer.d.ts +1 -1
  114. package/lib/chevre/service/task/returnOrder.d.ts +1 -1
  115. package/lib/chevre/service/task/returnPayTransaction.d.ts +1 -1
  116. package/lib/chevre/service/task/returnPointAward.d.ts +1 -1
  117. package/lib/chevre/service/task/returnReserveTransaction.d.ts +1 -1
  118. package/lib/chevre/service/task/sendEmailMessage.d.ts +1 -1
  119. package/lib/chevre/service/task/sendOrder.d.ts +1 -1
  120. package/lib/chevre/service/task/triggerWebhook.d.ts +1 -1
  121. package/lib/chevre/service/task/useReservation.d.ts +1 -1
  122. package/lib/chevre/service/task/voidMoneyTransferTransaction.d.ts +1 -1
  123. package/lib/chevre/service/task/voidPayTransaction.d.ts +1 -1
  124. package/lib/chevre/service/task/voidPayment.d.ts +1 -1
  125. package/lib/chevre/service/task/voidRegisterServiceTransaction.d.ts +1 -1
  126. package/lib/chevre/service/task/voidReserveTransaction.d.ts +1 -1
  127. package/lib/chevre/service/task/voidReserveTransaction.js +1 -1
  128. package/lib/chevre/service/task.d.ts +7 -29
  129. package/lib/chevre/service/task.js +9 -114
  130. package/lib/chevre/service/taskHandler/onOperationFailed/informTaskIfNeeded.d.ts +11 -0
  131. package/lib/chevre/service/taskHandler/onOperationFailed/informTaskIfNeeded.js +105 -0
  132. package/lib/chevre/service/taskHandler/onOperationFailed.d.ts +17 -0
  133. package/lib/chevre/service/taskHandler/onOperationFailed.js +70 -0
  134. package/lib/chevre/service/taskHandler.d.ts +26 -0
  135. package/lib/chevre/service/taskHandler.js +97 -0
  136. package/lib/chevre/service/validation/validateEvent.d.ts +2 -2
  137. package/lib/chevre/service/validation/validateEvent.js +16 -10
  138. package/lib/chevre/service.d.ts +0 -4
  139. package/lib/chevre/service.js +10 -14
  140. package/lib/chevre/settings/aggregation.d.ts +6 -1
  141. package/lib/chevre/settings/aggregation.js +2 -1
  142. package/package.json +6 -4
  143. package/example/src/chevre/adminAuth/adminIdentity.ts +0 -38
  144. package/example/src/chevre/executeOneTask.ts +0 -41
  145. package/example/src/chevre/executeTaskIfExists.ts +0 -80
  146. package/example/src/chevre/findExecutableTask.ts +0 -50
  147. package/example/src/chevre/findSetting.ts +0 -79
  148. package/example/src/chevre/searchPermissions.ts +0 -46
  149. package/example/src/chevre/searchProductOffers.ts +0 -29
  150. package/example/src/chevre/stockHolder/checkIfConflicted.ts +0 -76
  151. package/example/src/chevre/stockHolder/checkRedisKeyCount.ts +0 -186
  152. package/example/src/chevre/stockHolder/migratePendingReservations.ts +0 -96
  153. package/example/src/chevre/stockHolder/playAroundStockHolder.ts +0 -256
  154. package/example/src/chevre/upsertProductsByProductId.ts +0 -100
  155. package/lib/chevre/adminAuth.d.ts +0 -2
  156. package/lib/chevre/adminAuth.js +0 -6
@@ -0,0 +1,28 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+
4
+ import { chevre } from '../../../lib/index';
5
+
6
+ const PROJECT_ID = String(process.env.PROJECT_ID);
7
+
8
+ async function main() {
9
+ await mongoose.connect(<string>process.env.MONGOLAB_URI);
10
+
11
+ const productRepo = await chevre.repository.Product.createInstance(mongoose.connection);
12
+
13
+ const products = await productRepo.projectFields(
14
+ {
15
+ limit: 10,
16
+ project: { id: { $eq: PROJECT_ID } },
17
+ additionalPropertyMatch: { nameEq: 'xxxxx' }
18
+ // seller: { id: { $eq: 'xxx' } }
19
+ },
20
+ ['additionalProperty', 'productID']
21
+ );
22
+ console.log(products);
23
+ console.log(products.length, 'products found');
24
+ }
25
+
26
+ main()
27
+ .then(console.log)
28
+ .catch(console.error);
@@ -3,28 +3,42 @@ import * as mongoose from 'mongoose';
3
3
 
4
4
  import { chevre } from '../../../../lib/index';
5
5
 
6
+ const { INFORM_TASK_AGG_URL } = process.env;
7
+ if (typeof INFORM_TASK_AGG_URL !== 'string') {
8
+ throw new Error('INFORM_TASK_AGG_URL required');
9
+ }
10
+
6
11
  async function main() {
7
12
  await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
8
13
 
9
14
  const settingRepo = await chevre.repository.Setting.createInstance(mongoose.connection);
10
-
11
- const setting = await settingRepo.findOne({ project: { id: { $eq: '*' } } }, ['onOrderStatusChanged']);
12
- const useInformReturnAction = (<any>setting)?.onOrderStatusChanged?.useInformReturnAction === true;
13
- if (useInformReturnAction) {
14
- console.log('already useInformReturnAction:true');
15
- } else {
16
- // update
17
- await settingRepo.updateByProject4migration(
18
- { project: { id: { $eq: '*' } } },
19
- {
20
- $set: {
21
- 'onOrderStatusChanged.useInformReturnAction': true
22
- }
15
+ // const setting = await settingRepo.findOne({ project: { id: { $eq: '*' } } }, ['onTaskStatusChanged']);
16
+ // update
17
+ await settingRepo.updateByProject(
18
+ { project: { id: { $eq: '*' } } },
19
+ {
20
+ onTaskStatusChanged: {
21
+ informTask: [{
22
+ recipient: {
23
+ name: 'Aggregation Service',
24
+ url: INFORM_TASK_AGG_URL
25
+ }
26
+ }],
27
+ informTaskNames: [
28
+ chevre.factory.taskName.Pay,
29
+ chevre.factory.taskName.InvalidatePaymentUrl,
30
+ chevre.factory.taskName.Refund,
31
+ chevre.factory.taskName.VoidPayment
32
+ // chevre.factory.taskName.ConfirmReserveTransaction
33
+ ],
34
+ informTaskStatuses: [
35
+ chevre.factory.taskStatus.Aborted
36
+ // chevre.factory.taskStatus.Running
37
+ ]
23
38
  }
24
- );
25
- console.log('updated.');
26
- }
27
-
39
+ }
40
+ );
41
+ console.log('updated.');
28
42
  }
29
43
 
30
44
  main()
@@ -0,0 +1,41 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+
4
+ import { chevre } from '../../../../lib/index';
5
+
6
+ // const project = { id: String(process.env.PROJECT_ID) };
7
+
8
+ mongoose.Model.on('index', (...args) => {
9
+ console.error('******** index event emitted. ********\n', args);
10
+ });
11
+
12
+ const excludedTaskNames = [
13
+ chevre.factory.taskName.DeleteTransaction,
14
+ chevre.factory.taskName.ImportEventCapacitiesFromCOA,
15
+ chevre.factory.taskName.ImportEventsFromCOA,
16
+ chevre.factory.taskName.AcceptCOAOffer,
17
+ chevre.factory.taskName.CheckMovieTicket,
18
+ chevre.factory.taskName.AuthorizePayment,
19
+ chevre.factory.taskName.PublishPaymentUrl
20
+ ];
21
+ async function main() {
22
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
23
+
24
+ let allTaskNames = Object.values(chevre.factory.taskName);
25
+ allTaskNames = allTaskNames.filter((taskName) => !excludedTaskNames.includes(taskName));
26
+ console.log('allTaskNames:', allTaskNames, allTaskNames.length);
27
+ const taskRepo = await chevre.repository.Task.createInstance(mongoose.connection);
28
+
29
+ const result = await taskRepo.countPotentiallyRunning({
30
+ name: {
31
+ $in: allTaskNames
32
+ },
33
+ runsAt: { $lt: new Date() },
34
+ limit: 100
35
+ });
36
+ console.log('result:', result);
37
+ }
38
+
39
+ main()
40
+ .then()
41
+ .catch(console.error);
@@ -0,0 +1,51 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+
4
+ import { chevre } from '../../../../lib/index';
5
+
6
+ // const project = { id: String(process.env.PROJECT_ID) };
7
+
8
+ mongoose.Model.on('index', (...args) => {
9
+ console.error('******** index event emitted. ********\n', args);
10
+ });
11
+
12
+ async function main() {
13
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
14
+
15
+ const taskRepo = await chevre.repository.Task.createInstance(mongoose.connection);
16
+
17
+ setInterval(
18
+ async () => {
19
+ const readyTasksCountResult = await taskRepo.count({
20
+ limit: 100,
21
+ status: { $eq: chevre.factory.taskStatus.Ready },
22
+ runsThrough: new Date()
23
+ });
24
+ console.log('readyTasksCountResult:', readyTasksCountResult);
25
+
26
+ const readyTasks = await taskRepo.projectFields(
27
+ {
28
+ limit: 10,
29
+ status: { $eq: chevre.factory.taskStatus.Ready },
30
+ runsThrough: new Date(),
31
+ name: { $nin: [chevre.factory.taskName.DeleteTransaction] }
32
+ },
33
+ ['name']
34
+ );
35
+ console.log('readyTasks:', readyTasks);
36
+
37
+ const runningTasksCountResult = await taskRepo.count({
38
+ limit: 100,
39
+ status: { $eq: chevre.factory.taskStatus.Running },
40
+ runsThrough: new Date()
41
+ });
42
+ console.log('runningTasksCountResult:', runningTasksCountResult);
43
+ },
44
+ // tslint:disable-next-line:no-magic-numbers
45
+ 10000
46
+ );
47
+ }
48
+
49
+ main()
50
+ .then()
51
+ .catch(console.error);
@@ -2,9 +2,10 @@
2
2
  import * as moment from 'moment';
3
3
  import * as mongoose from 'mongoose';
4
4
 
5
- import { chevre } from '../../../lib/index';
5
+ import { chevre } from '../../../../lib/index';
6
6
 
7
- const TASK_STORAGE_PERIOD_IN_MINUTES = 43200; // 30*24*60
7
+ // const TASK_STORAGE_PERIOD_IN_MINUTES = 43200; // 30*24*60
8
+ const TASK_STORAGE_PERIOD_IN_MINUTES = 20160; // 14*24*60
8
9
 
9
10
  async function main() {
10
11
  const now = new Date();
@@ -12,7 +13,7 @@ async function main() {
12
13
 
13
14
  const taskRepo = await chevre.repository.Task.createInstance(mongoose.connection);
14
15
 
15
- let taskInMinutes = 57600; // 40*24*60
16
+ let taskInMinutes = 21600; // 15*24*60
16
17
  // let taskInMinutes = 172800; // 120*24*60
17
18
  // tslint:disable-next-line:no-magic-numbers
18
19
  while (taskInMinutes > TASK_STORAGE_PERIOD_IN_MINUTES) {
@@ -0,0 +1,23 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+
4
+ import { chevre } from '../../../../lib/index';
5
+
6
+ async function main() {
7
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
8
+
9
+ const taskRepo = await chevre.repository.Task.createInstance(mongoose.connection);
10
+ const result = await taskRepo.taskModel.deleteMany({
11
+ $or: [
12
+ { name: { $exists: false } },
13
+ { status: { $exists: false } }
14
+ ]
15
+ })
16
+ .exec();
17
+
18
+ console.log('success!', result);
19
+ }
20
+
21
+ main()
22
+ .then()
23
+ .catch(console.error);
@@ -0,0 +1,89 @@
1
+ // tslint:disable:no-console no-magic-numbers
2
+ import * as moment from 'moment';
3
+ import * as mongoose from 'mongoose';
4
+
5
+ import { chevre } from '../../../../lib/index';
6
+
7
+ // const project = { id: String(process.env.PROJECT_ID) };
8
+
9
+ const delayInSeconds = 60;
10
+ const numExecuteByRequest = 50;
11
+ const selfName = 'sample';
12
+
13
+ const excludedTaskNames = [
14
+ chevre.factory.taskName.DeleteTransaction,
15
+ chevre.factory.taskName.ImportEventCapacitiesFromCOA,
16
+ chevre.factory.taskName.ImportEventsFromCOA,
17
+ chevre.factory.taskName.AcceptCOAOffer,
18
+ chevre.factory.taskName.CheckMovieTicket,
19
+ chevre.factory.taskName.AuthorizePayment,
20
+ chevre.factory.taskName.PublishPaymentUrl
21
+ ];
22
+
23
+ async function main() {
24
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false, appName: 'sample' });
25
+
26
+ const now = new Date();
27
+ const runsAtLt = moment(now)
28
+ .add(-delayInSeconds, 'seconds')
29
+ .toDate();
30
+
31
+ let allTaskNames = Object.values(chevre.factory.taskName);
32
+ allTaskNames = allTaskNames.filter((name) => !excludedTaskNames.includes(name));
33
+ console.log('allTaskNames:', allTaskNames, allTaskNames.length);
34
+
35
+ const taskRepo = await chevre.repository.Task.createInstance(mongoose.connection);
36
+
37
+ const delayedTask: Pick<chevre.factory.task.ITask<chevre.factory.taskName>, 'id' | 'name'>[] = [];
38
+
39
+ // const { count } = await taskRepo.countPotentiallyRunning({
40
+ // name: { $in: allTaskNames },
41
+ // runsAt: { $lt: runsAtLt },
42
+ // limit: numExecuteByRequest
43
+ // });
44
+ // console.log('countPotentiallyRunning:', count);
45
+ // const executeCount: number = Math.min(count, numExecuteByRequest);
46
+ const executeCount: number = numExecuteByRequest;
47
+ const sort: {
48
+ numberOfTried?: chevre.factory.sortType;
49
+ runsAt?: chevre.factory.sortType;
50
+ } = {
51
+ numberOfTried: chevre.factory.sortType.Ascending, // numberOfTriedソートを加えるとどうなるのか?
52
+ runsAt: chevre.factory.sortType.Ascending
53
+ };
54
+
55
+ for (let i = 0; i < executeCount; i += 1) {
56
+ const runningTask = await taskRepo.emitRunningIfExists(
57
+ {
58
+ name: { $in: allTaskNames },
59
+ runsAt: { $lt: runsAtLt },
60
+ sort,
61
+ executor: {
62
+ name: selfName
63
+ },
64
+ nameFilterBeforeRunsAt: false
65
+ }
66
+ );
67
+ console.log('runningTask found', JSON.stringify(runningTask), i, now);
68
+ if (runningTask !== null) {
69
+ delayedTask.push(runningTask);
70
+ }
71
+ }
72
+ }
73
+
74
+ const interval = setInterval(
75
+ () => {
76
+ main()
77
+ .then()
78
+ .catch(console.error);
79
+ },
80
+ 1000
81
+ );
82
+
83
+ setTimeout(
84
+ () => {
85
+ clearInterval(interval);
86
+ console.log('interval cleared');
87
+ },
88
+ 600000
89
+ );
@@ -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);
@@ -0,0 +1,31 @@
1
+ // tslint:disable:no-console
2
+ const projectIdMustBe = /^[0-9a-z-]+$/; // 記号はhyphenのみ許可
3
+
4
+ let projectId: string;
5
+
6
+ projectId = 'projectId';
7
+ console.log(projectId, ':', projectIdMustBe.test(projectId));
8
+
9
+ projectId = 'projectid';
10
+ console.log(projectId, ':', projectIdMustBe.test(projectId));
11
+
12
+ projectId = 'abcd1234-test';
13
+ console.log(projectId, ':', projectIdMustBe.test(projectId));
14
+
15
+ projectId = 'a-z';
16
+ console.log(projectId, ':', projectIdMustBe.test(projectId));
17
+
18
+ projectId = '0-9';
19
+ console.log(projectId, ':', projectIdMustBe.test(projectId));
20
+
21
+ projectId = '---';
22
+ console.log(projectId, ':', projectIdMustBe.test(projectId));
23
+
24
+ projectId = '-';
25
+ console.log(projectId, ':', projectIdMustBe.test(projectId));
26
+
27
+ projectId = '&';
28
+ console.log(projectId, ':', projectIdMustBe.test(projectId));
29
+
30
+ projectId = 'A';
31
+ console.log(projectId, ':', projectIdMustBe.test(projectId));