@stancer/stancer 1.0.2 → 1.1.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 (120) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/api-endpoint/http/fetch-http-client.d.ts.map +1 -1
  3. package/dist/api-endpoint/http/fetch-http-client.js +7 -1
  4. package/dist/api-endpoint/http/fetch-http-client.js.map +1 -1
  5. package/dist/core/common/handler/metadata-handler.d.ts +18 -0
  6. package/dist/core/common/handler/metadata-handler.d.ts.map +1 -0
  7. package/dist/core/common/handler/metadata-handler.js +19 -0
  8. package/dist/core/common/handler/metadata-handler.js.map +1 -0
  9. package/dist/event/model.d.ts +20 -0
  10. package/dist/event/model.d.ts.map +1 -0
  11. package/dist/event/model.js +30 -0
  12. package/dist/event/model.js.map +1 -0
  13. package/dist/payment-intent/api-endpoint.d.ts +16 -1
  14. package/dist/payment-intent/api-endpoint.d.ts.map +1 -1
  15. package/dist/payment-intent/api-endpoint.js +2 -1
  16. package/dist/payment-intent/api-endpoint.js.map +1 -1
  17. package/dist/payment-intent/model.d.ts +3 -2
  18. package/dist/payment-intent/model.d.ts.map +1 -1
  19. package/dist/payment-intent/model.js +6 -0
  20. package/dist/payment-intent/model.js.map +1 -1
  21. package/dist/webhook/api-endpoint.d.ts +16 -0
  22. package/dist/webhook/api-endpoint.d.ts.map +1 -0
  23. package/dist/webhook/api-endpoint.js +33 -0
  24. package/dist/webhook/api-endpoint.js.map +1 -0
  25. package/dist/webhook/model.d.ts +35 -0
  26. package/dist/webhook/model.d.ts.map +1 -0
  27. package/dist/webhook/model.js +110 -0
  28. package/dist/webhook/model.js.map +1 -0
  29. package/dist/webhook/repository.d.ts +7 -0
  30. package/dist/webhook/repository.d.ts.map +1 -0
  31. package/dist/webhook/repository.js +10 -0
  32. package/dist/webhook/repository.js.map +1 -0
  33. package/dist/webhook/validator.d.ts +4 -0
  34. package/dist/webhook/validator.d.ts.map +1 -0
  35. package/dist/webhook/validator.js +16 -0
  36. package/dist/webhook/validator.js.map +1 -0
  37. package/package.json +4 -2
  38. package/src/api-endpoint/http/fetch-http-client.ts +8 -1
  39. package/src/core/common/handler/metadata-handler.ts +19 -0
  40. package/src/event/model.ts +42 -0
  41. package/src/payment-intent/api-endpoint.ts +2 -1
  42. package/src/payment-intent/model.ts +8 -3
  43. package/src/webhook/api-endpoint.ts +36 -0
  44. package/src/webhook/model.ts +140 -0
  45. package/src/webhook/repository.ts +14 -0
  46. package/src/webhook/validator.ts +18 -0
  47. package/dist/main.d.ts +0 -2
  48. package/dist/main.d.ts.map +0 -1
  49. package/dist/main.js +0 -2
  50. package/dist/main.js.map +0 -1
  51. package/reports/base.css +0 -362
  52. package/reports/block-navigation.js +0 -75
  53. package/reports/cobertura-coverage.xml +0 -18
  54. package/reports/favicon.png +0 -0
  55. package/reports/index.html +0 -177
  56. package/reports/junit.xml +0 -25
  57. package/reports/prettify.css +0 -101
  58. package/reports/prettify.js +0 -955
  59. package/reports/sort-arrow-sprite.png +0 -0
  60. package/reports/sorter.js +0 -205
  61. package/test/fixtures/endpoint.stub.ts +0 -22
  62. package/test/fixtures/list-endpoint.stub.ts +0 -33
  63. package/test/fixtures/list-model.stub.ts +0 -24
  64. package/test/fixtures/model.stub.ts +0 -12
  65. package/test/functional/address.test.ts +0 -126
  66. package/test/functional/card.test.ts +0 -175
  67. package/test/functional/customer.test.ts +0 -174
  68. package/test/functional/payment-intent.test.ts +0 -215
  69. package/test/functional/payment.test.ts +0 -206
  70. package/test/functional/refund.test.ts +0 -112
  71. package/test/functional/sepa.test.ts +0 -136
  72. package/test/integration/stub-integration.test.ts +0 -88
  73. package/test/stub/stub-endpoint.ts +0 -42
  74. package/test/stub/stub-model.ts +0 -82
  75. package/test/stub/stub-repository.ts +0 -11
  76. package/test/test-helper.ts +0 -133
  77. package/test/unit/address/api-endpoint.test.ts +0 -134
  78. package/test/unit/address/fixtures.ts +0 -60
  79. package/test/unit/address/model.test.ts +0 -75
  80. package/test/unit/address/repository.test.ts +0 -148
  81. package/test/unit/address/validator.test.ts +0 -49
  82. package/test/unit/api-endpoint/http/fetch-http-client.test.ts +0 -44
  83. package/test/unit/api-endpoint/http/http.test.ts +0 -152
  84. package/test/unit/card/api-endpoint.test.ts +0 -170
  85. package/test/unit/card/card-helper.ts +0 -116
  86. package/test/unit/card/fixtures.ts +0 -87
  87. package/test/unit/card/model.test.ts +0 -167
  88. package/test/unit/card/repository.test.ts +0 -146
  89. package/test/unit/card/validator.test.ts +0 -96
  90. package/test/unit/core/common/mutation-tracked-object.test.ts +0 -24
  91. package/test/unit/customer/api-endpoint.test.ts +0 -143
  92. package/test/unit/customer/fixtures.ts +0 -73
  93. package/test/unit/customer/model.test.ts +0 -90
  94. package/test/unit/customer/repository.test.ts +0 -148
  95. package/test/unit/customer/validator.test.ts +0 -62
  96. package/test/unit/payment/api-endpoint.test.ts +0 -188
  97. package/test/unit/payment/fixtures.ts +0 -116
  98. package/test/unit/payment/model.test.ts +0 -240
  99. package/test/unit/payment/repository.test.ts +0 -270
  100. package/test/unit/payment/validator.test.ts +0 -137
  101. package/test/unit/payment-intent/api-endpoint.test.ts +0 -142
  102. package/test/unit/payment-intent/fixtures.ts +0 -94
  103. package/test/unit/payment-intent/model.test.ts +0 -157
  104. package/test/unit/payment-intent/repository.test.ts +0 -263
  105. package/test/unit/payment-intent/validator.test.ts +0 -136
  106. package/test/unit/refund/api-endpoint.test.ts +0 -129
  107. package/test/unit/refund/fixtures.ts +0 -58
  108. package/test/unit/refund/model.test.ts +0 -89
  109. package/test/unit/refund/repository.test.ts +0 -157
  110. package/test/unit/refund/validator.test.ts +0 -89
  111. package/test/unit/sepa/api-endpoint.test.ts +0 -170
  112. package/test/unit/sepa/fixture.ts +0 -62
  113. package/test/unit/sepa/model.test.ts +0 -86
  114. package/test/unit/sepa/repository.test.ts +0 -149
  115. package/test/unit/sepa/sepa-helper.ts +0 -71
  116. package/test/unit/sepa/validator.test.ts +0 -58
  117. package/test/unit/stub/stub-endpoint.test.ts +0 -236
  118. package/test/unit/stub/stub-list-endpoint.test.ts +0 -86
  119. package/test/unit/stub/stub-model.test.ts +0 -111
  120. package/test/unit/stub/stub-repository.test.ts +0 -144
@@ -20,7 +20,14 @@ export const httpClient: Http.Client = {
20
20
 
21
21
  return {
22
22
  status: response.status,
23
- json: async <T>() => (await response.json()) as T,
23
+
24
+ json: async <T>() => {
25
+ if (!response.body) {
26
+ // If no body, json is an empty object. useful in 204 case.
27
+ return {} as T;
28
+ }
29
+ return (await response.json()) as T;
30
+ }, //,
24
31
  };
25
32
  } catch (e) {
26
33
  throw new StancerApiUnknownError(0, e instanceof Error ? e.message : 'Network error');
@@ -0,0 +1,19 @@
1
+ import pkg from '../../../../package.json' with { type: 'json' };
2
+ import { type AccessRight, setAccess } from './handler.js';
3
+
4
+ export const metadataHandler = (access?: Partial<AccessRight>) => {
5
+ return {
6
+ serialize: (metadata: object | string) => {
7
+ return {
8
+ SDK: {
9
+ type: 'TypeScript',
10
+ version: pkg.version,
11
+ 'NodeJS-version': process.version,
12
+ },
13
+ 'custom-metadata': metadata,
14
+ };
15
+ },
16
+ deserialize: (value: unknown) => value as object,
17
+ ...setAccess(access ?? {}),
18
+ };
19
+ };
@@ -0,0 +1,42 @@
1
+ import type { IdValue } from '#core/common/branded-type.js';
2
+ import { validateID } from '#core/common/id-validator.js';
3
+ import { StancerValidationError } from '#core/error/validation-error.js';
4
+
5
+ type IdEvent = IdValue<`evt_${string}`>;
6
+ export const idEvent = (id: string) => validateID<IdEvent>(id, EventModel.regex);
7
+
8
+ export type EventData = {
9
+ id: IdEvent;
10
+ data: Record<string, unknown>;
11
+ type: `${string}.${string}`;
12
+ };
13
+
14
+ export class EventModel {
15
+ //#region static
16
+ static regex = /^evt_[a-zA-Z0-9]{24}$/;
17
+ //#endregion
18
+
19
+ //#region fields
20
+ public readonly id: IdEvent;
21
+ public readonly action: string;
22
+ public readonly data: Record<string, unknown>;
23
+ public readonly modelId: string;
24
+ public readonly modelName: string;
25
+ public readonly type: string;
26
+ //#endregion
27
+
28
+ //#region constructor
29
+ public constructor(data: EventData) {
30
+ this.id = data.id;
31
+ this.type = data.type;
32
+ this.data = data.data;
33
+ const [modelName, action] = data.type.split('.');
34
+ this.modelName = modelName as string;
35
+ this.action = action as string;
36
+ if (!Object.hasOwn(data.data, 'id') || typeof data.data['id'] !== 'string') {
37
+ throw new StancerValidationError('Event is malformed (missing data id)');
38
+ }
39
+ this.modelId = data.data['id'];
40
+ }
41
+ //#endregion
42
+ }
@@ -4,6 +4,7 @@ import { RFC9557Handler } from '#core/common/handler/date-handler.js';
4
4
  import { enumHandler } from '#core/common/handler/enum-handler.js';
5
5
  import { defaultHandler } from '#core/common/handler/handler.js';
6
6
  import { IdHandler } from '#core/common/handler/id-handler.js';
7
+ import { metadataHandler } from '#core/common/handler/metadata-handler.js';
7
8
  import { PaymentApiEndpoint, methodsAllowedHandler } from '#payment/api-endpoint.js';
8
9
  import { CurrencyEnum } from '#payment/enum/currency.js';
9
10
  import { type IdPayment, type PaymentAmount, PaymentModel } from '#payment/model.js';
@@ -40,7 +41,7 @@ export class PaymentIntentApiEndpoint extends ApiEndpoint<PaymentIntentData> {
40
41
  dateBank: RFC9557Handler({ postable: false, patchable: false }),
41
42
  dateSettlement: RFC9557Handler({}),
42
43
  description: defaultHandler<PaymentIntentData['description']>('string'),
43
- metadata: defaultHandler<PaymentIntentData['metadata']>('string'),
44
+ metadata: metadataHandler(),
44
45
  methodsAllowed: methodsAllowedHandler,
45
46
  orderId: defaultHandler<PaymentIntentData['orderId']>('string'),
46
47
  origin: defaultHandler<PaymentIntentData['origin']>('string', { postable: false, patchable: false }),
@@ -28,7 +28,7 @@ export interface PaymentIntentData extends ModelData {
28
28
  dateSettlement: Temporal.PlainDate;
29
29
  description: string;
30
30
  payment: IdPayment;
31
- metadata: string;
31
+ metadata: object | string;
32
32
  methodsAllowed: Method[];
33
33
  orderId: string;
34
34
  origin: string;
@@ -118,7 +118,12 @@ export class PaymentIntentModel extends AbstractModel<PaymentIntentData> {
118
118
  get description() {
119
119
  return this._data.description;
120
120
  }
121
-
121
+ get metadata() {
122
+ if (typeof this._data.metadata === 'object' && Object.hasOwn(this._data.metadata, 'SDK')) {
123
+ return this._data.metadata ? ['custom-metadata'] : null;
124
+ }
125
+ return this._data.metadata;
126
+ }
122
127
  get methodsAllowed() {
123
128
  return this._data.methodsAllowed;
124
129
  }
@@ -232,7 +237,7 @@ export class PaymentIntentModel extends AbstractModel<PaymentIntentData> {
232
237
  return this;
233
238
  }
234
239
 
235
- setMetadata(metadata: string) {
240
+ setMetadata(metadata: object | string) {
236
241
  this._data.metadata = metadata;
237
242
  return this;
238
243
  }
@@ -0,0 +1,36 @@
1
+ import { ApiEndpoint, baseHandler } from '#api/abstract-api-endpoint.js';
2
+ import { type AccessRight, type Handler, defaultHandler, setAccess } from '#core/common/handler/handler.js';
3
+ import { IdHandler } from '#core/common/handler/id-handler.js';
4
+
5
+ import { type IdWebhook, type WebhookData, WebhookModel } from './model.js';
6
+
7
+ export const booleanHandler = (access: Partial<AccessRight>, name?: string): Handler<boolean | undefined> => {
8
+ const payloadName = name ? { payloadName: name } : {};
9
+ return {
10
+ serialize: (arg0: boolean | undefined) => arg0,
11
+ deserialize: (arg0: unknown) => {
12
+ if (typeof arg0 === 'boolean') {
13
+ return arg0;
14
+ }
15
+ return undefined;
16
+ },
17
+ ...setAccess(access),
18
+ ...payloadName,
19
+ };
20
+ };
21
+
22
+ export class WebhookApiEndpoint extends ApiEndpoint<WebhookData> {
23
+ public override _handler = {
24
+ ...baseHandler('created'),
25
+ id: IdHandler<IdWebhook>(WebhookModel.regex, { postable: false, patchable: false }),
26
+ enabled: booleanHandler({}),
27
+ secret: defaultHandler<WebhookData['secret']>('string', { postable: false, patchable: false }),
28
+ url: defaultHandler<WebhookData['url']>('string', { postRequired: true }),
29
+ };
30
+
31
+ constructor() {
32
+ super({
33
+ name: 'webhooks',
34
+ });
35
+ }
36
+ }
@@ -0,0 +1,140 @@
1
+ import { createHmac, timingSafeEqual } from 'crypto';
2
+ import { Temporal } from 'temporal-polyfill';
3
+
4
+ import { AbstractModel, type ModelData } from '#core/abstract-model.js';
5
+ import type { IdValue } from '#core/common/branded-type.js';
6
+ import { validateID } from '#core/common/id-validator.js';
7
+ import { StancerValidationError } from '#core/error/validation-error.js';
8
+ import { type EventData, EventModel, idEvent } from '#event/model.js';
9
+
10
+ export type IdWebhook = IdValue<`we_${string}`>;
11
+ export const idWebhook = (id: string) => validateID<IdWebhook>(id, WebhookModel.regex);
12
+
13
+ export interface WebhookData extends ModelData {
14
+ id: IdWebhook;
15
+ enabled: boolean;
16
+ secret: string;
17
+ url: string;
18
+ }
19
+
20
+ const isEventData = (data: unknown): data is EventData => {
21
+ if (!data || typeof data !== 'object') {
22
+ return false;
23
+ }
24
+ const properties = Object.getOwnPropertyNames(data);
25
+ if (!properties.includes('id') || !idEvent((data as { id: string }).id)) {
26
+ return false;
27
+ }
28
+ if (
29
+ !properties.includes('type') ||
30
+ typeof (data as { type: unknown }).type !== 'string' ||
31
+ (data as { type: string }).type.indexOf('.') < 0
32
+ ) {
33
+ return false;
34
+ }
35
+ if (!properties.includes('data') || typeof (data as { data: unknown }).data !== 'object') {
36
+ return false;
37
+ }
38
+ return true;
39
+ };
40
+
41
+ export class WebhookModel extends AbstractModel<WebhookData> {
42
+ //#region static
43
+ static regex = /^we_[a-zA-Z0-9]{24}$/;
44
+ //#endregion
45
+
46
+ //#region getters
47
+ get enabled() {
48
+ return this._data.enabled;
49
+ }
50
+
51
+ get secret() {
52
+ return this._data.secret;
53
+ }
54
+
55
+ get url() {
56
+ return this._data.url;
57
+ }
58
+ //#endregion
59
+
60
+ //#region methods
61
+ checkHmac(data: string, hmac: string): boolean {
62
+ if (!this.secret) {
63
+ return false;
64
+ }
65
+ const generatedHmac = createHmac('sha256', Buffer.from(this.secret, 'hex')).update(data).digest('hex');
66
+ return timingSafeEqual(Buffer.from(hmac), Buffer.from(generatedHmac));
67
+ }
68
+
69
+ checkPayload(
70
+ signature: string,
71
+ payload: string | ReadableStream<unknown>,
72
+ time: { now: Temporal.Instant; delta: Temporal.Duration } = {
73
+ now: Temporal.Now.instant(),
74
+ delta: new Temporal.Duration(0, 0, 0, 0, 0, 1),
75
+ },
76
+ ) {
77
+ const parsedSignature = this.parseSignature(signature);
78
+ const signatureTime = Temporal.Instant.fromEpochMilliseconds(Number(parsedSignature.timestamp) * 1000);
79
+ const deltaNow = time.now.subtract(time.delta);
80
+ if (Temporal.Instant.compare(deltaNow, signatureTime) > 0) {
81
+ throw new StancerValidationError('Expired signature');
82
+ }
83
+
84
+ const ok = this.checkHmac(`${parsedSignature.timestamp}.${payload}`, parsedSignature.expected);
85
+ if (!ok) {
86
+ throw new StancerValidationError('Invalid signature');
87
+ }
88
+ }
89
+
90
+ checkRequest(request: Request, time?: { now: Temporal.Instant; delta: Temporal.Duration }) {
91
+ const signature: string | null = request.headers.get('stancer-signature');
92
+ if (!signature) {
93
+ throw new StancerValidationError('Invalid signature');
94
+ }
95
+ if (!request.body) {
96
+ throw new StancerValidationError('Invalid signature');
97
+ }
98
+ this.checkPayload(signature, request.body, time);
99
+ }
100
+
101
+ async getEvent(request: Request, time: { now: Temporal.Instant; delta: Temporal.Duration }) {
102
+ this.checkRequest(request, time);
103
+ const data = await request.json();
104
+ if (!isEventData(data)) {
105
+ throw new StancerValidationError('Event is malformed');
106
+ }
107
+ return new EventModel(data);
108
+ }
109
+
110
+ private parseSignature(signature: string, version = 'v1'): { timestamp: number; expected: string } {
111
+ const tmp = signature.split(',');
112
+ const parts: Record<string, string> = {};
113
+ let timestamp = undefined;
114
+ for (const part of tmp) {
115
+ const subPart = part.split('=');
116
+ if (!subPart[0] || typeof subPart[0] !== 'string' || !subPart[1] || typeof subPart[1] !== 'string') {
117
+ throw new StancerValidationError('Invalid signature');
118
+ }
119
+ if (subPart[0] === 't') {
120
+ timestamp = Number(subPart[1]);
121
+ }
122
+ parts[subPart[0]] = subPart[1];
123
+ }
124
+ if (!timestamp || !parts[version]) {
125
+ throw new StancerValidationError('Invalid signature');
126
+ }
127
+ return { timestamp: timestamp, expected: parts[version] };
128
+ }
129
+
130
+ setEnabled(enabled: boolean) {
131
+ this._data.enabled = enabled;
132
+ return this;
133
+ }
134
+
135
+ setUrl(url: string) {
136
+ this._data.url = url;
137
+ return this;
138
+ }
139
+ //#endregion
140
+ }
@@ -0,0 +1,14 @@
1
+ import { AbstractRepository, type Repository } from '#core/abstract-repository.js';
2
+ import type { EndpointInterface } from '#core/endpoint-interface.js';
3
+ import { WebhookApiEndpoint } from '#webhook/api-endpoint.js';
4
+ import { type WebhookData, WebhookModel } from '#webhook/model.js';
5
+ import { webhookValidator } from '#webhook/validator.js';
6
+
7
+ export class WebhookRepository
8
+ extends AbstractRepository<WebhookData, WebhookModel>
9
+ implements Repository<WebhookData, WebhookModel>
10
+ {
11
+ constructor(endpoint?: EndpointInterface<WebhookData>) {
12
+ super({ endpoint: endpoint ?? new WebhookApiEndpoint(), validator: webhookValidator, model: WebhookModel });
13
+ }
14
+ }
@@ -0,0 +1,18 @@
1
+ import { IdValidator } from '#core/common/id-validator.js';
2
+ import { type Validator, goldilocksValidator } from '#core/validator.js';
3
+
4
+ import { type IdWebhook, type WebhookData, WebhookModel } from './model.js';
5
+
6
+ const booleanValidator = (name: string) => ({
7
+ errorMessage: (value: unknown) => `${name} must be a boolean, ${value} given`,
8
+ validate: (value: boolean) => typeof value === 'boolean',
9
+ });
10
+
11
+ export const webhookValidator: Validator<WebhookData> = {
12
+ id: IdValidator<IdWebhook>(WebhookModel.regex),
13
+ createdAt: true,
14
+ deleted: true,
15
+ enabled: booleanValidator('enabled'),
16
+ secret: true,
17
+ url: goldilocksValidator('url', { min: 1, max: 2048 }),
18
+ };
package/dist/main.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=main.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":""}
package/dist/main.js DELETED
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=main.js.map
package/dist/main.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":""}