@stancer/stancer 1.1.0 → 1.1.1

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 (81) hide show
  1. package/CHANGELOG.md +4 -1
  2. package/dist/index.d.ts +60 -0
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/index.js +57 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/payment-intent/repository.d.ts +1 -1
  7. package/dist/payment-intent/repository.d.ts.map +1 -1
  8. package/package.json +33 -24
  9. package/src/address/api-endpoint.ts +0 -30
  10. package/src/address/model.ts +0 -79
  11. package/src/address/repository.ts +0 -18
  12. package/src/address/validator.ts +0 -34
  13. package/src/api-endpoint/abstract-api-endpoint.ts +0 -310
  14. package/src/api-endpoint/configuration.ts +0 -125
  15. package/src/api-endpoint/http/fetch-http-client.ts +0 -36
  16. package/src/api-endpoint/http/http.ts +0 -75
  17. package/src/api-endpoint/http/index.ts +0 -2
  18. package/src/api-endpoint/version.ts +0 -4
  19. package/src/card/api-endpoint.ts +0 -39
  20. package/src/card/enum/funding.ts +0 -11
  21. package/src/card/enum/nature.ts +0 -7
  22. package/src/card/enum/network.ts +0 -16
  23. package/src/card/model.ts +0 -139
  24. package/src/card/repository.ts +0 -11
  25. package/src/card/validator.ts +0 -79
  26. package/src/core/abstract-model.ts +0 -126
  27. package/src/core/abstract-repository.ts +0 -201
  28. package/src/core/common/branded-type.ts +0 -15
  29. package/src/core/common/handler/date-handler.ts +0 -31
  30. package/src/core/common/handler/enum-handler.ts +0 -18
  31. package/src/core/common/handler/handler.ts +0 -64
  32. package/src/core/common/handler/id-handler.ts +0 -27
  33. package/src/core/common/handler/metadata-handler.ts +0 -19
  34. package/src/core/common/id-validator.ts +0 -23
  35. package/src/core/common/mutation-tracked-object.ts +0 -49
  36. package/src/core/endpoint-interface.ts +0 -43
  37. package/src/core/error/base-error.ts +0 -1
  38. package/src/core/error/endpoint/api/api-conflict-error.ts +0 -7
  39. package/src/core/error/endpoint/api/api-error.ts +0 -10
  40. package/src/core/error/endpoint/api/api-not-found-error.ts +0 -7
  41. package/src/core/error/endpoint/api/api-unauthorized-error.ts +0 -7
  42. package/src/core/error/endpoint/api/api-unknown-error.ts +0 -7
  43. package/src/core/error/endpoint/api/api-validation-error.ts +0 -13
  44. package/src/core/error/endpoint/api/index.ts +0 -6
  45. package/src/core/error/endpoint/route-inaccessible-error.ts +0 -8
  46. package/src/core/error/unpopulated-error.ts +0 -3
  47. package/src/core/error/unsendable-error.ts +0 -3
  48. package/src/core/error/validation-error.ts +0 -3
  49. package/src/core/validator.ts +0 -129
  50. package/src/customer/api-endpoint.ts +0 -29
  51. package/src/customer/model.ts +0 -113
  52. package/src/customer/repository.ts +0 -14
  53. package/src/customer/validator.ts +0 -26
  54. package/src/event/model.ts +0 -42
  55. package/src/payment/api-endpoint.ts +0 -118
  56. package/src/payment/enum/currency.ts +0 -14
  57. package/src/payment/enum/method.ts +0 -2
  58. package/src/payment/enum/status.ts +0 -21
  59. package/src/payment/model.ts +0 -378
  60. package/src/payment/repository.ts +0 -73
  61. package/src/payment/validator.ts +0 -96
  62. package/src/payment-intent/api-endpoint.ts +0 -124
  63. package/src/payment-intent/enum/status.ts +0 -21
  64. package/src/payment-intent/enum/threeds.ts +0 -2
  65. package/src/payment-intent/model.ts +0 -271
  66. package/src/payment-intent/repository.ts +0 -85
  67. package/src/payment-intent/validator.ts +0 -45
  68. package/src/payout/model.ts +0 -8
  69. package/src/refund/api-endpoint.ts +0 -33
  70. package/src/refund/enum/refund-status.ts +0 -11
  71. package/src/refund/model.ts +0 -90
  72. package/src/refund/repository.ts +0 -14
  73. package/src/refund/validator.ts +0 -44
  74. package/src/sepa/api-endpoint.ts +0 -26
  75. package/src/sepa/model.ts +0 -80
  76. package/src/sepa/repository.ts +0 -11
  77. package/src/sepa/validator.ts +0 -56
  78. package/src/webhook/api-endpoint.ts +0 -36
  79. package/src/webhook/model.ts +0 -140
  80. package/src/webhook/repository.ts +0 -14
  81. package/src/webhook/validator.ts +0 -18
@@ -1,14 +0,0 @@
1
- import { AbstractRepository, type Repository } from '#core/abstract-repository.js';
2
- import type { EndpointInterface } from '#core/endpoint-interface.js';
3
- import { RefundApiEndpoint } from '#refund/api-endpoint.js';
4
- import { type RefundData, RefundModel } from '#refund/model.js';
5
- import { refundValidator } from '#refund/validator.js';
6
-
7
- export class RefundRepository
8
- extends AbstractRepository<RefundData, RefundModel>
9
- implements Repository<RefundData, RefundModel>
10
- {
11
- constructor(endpoint?: EndpointInterface<RefundData>) {
12
- super({ endpoint: endpoint ?? new RefundApiEndpoint(), validator: refundValidator, model: RefundModel });
13
- }
14
- }
@@ -1,44 +0,0 @@
1
- import { IdValidator, isValidID } from '#core/common/id-validator.js';
2
- import { type Validator, createdAtValidator, enumValidator, plainDateValidator } from '#core/validator.js';
3
- import { CurrencyEnum } from '#payment/enum/currency.js';
4
- import { type IdPayment, PaymentModel } from '#payment/model.js';
5
-
6
- import { type IdPaymentIntent, PaymentIntentModel } from '../payment-intent/model.js';
7
- import { type IdPayout, PayoutModel } from '../payout/model.js';
8
- import { RefundStatusEnum } from './enum/refund-status.js';
9
- import { type IdRefund, type RefundData, RefundModel, isRefundAmount } from './model.js';
10
-
11
- const amountValidator = {
12
- validate: (value: number) => typeof value === 'number' && isRefundAmount(value),
13
- errorMessage: (value: string) => `value (${value}) is not a valid amount (not a number or too low a number)`,
14
- };
15
-
16
- const paymentValidator = {
17
- validate: (arg0: PaymentModel | IdPayment) => {
18
- if (typeof arg0 === 'string') {
19
- return isValidID<IdPayment>(arg0, PaymentModel.regex);
20
- }
21
- if (!(arg0 instanceof PaymentModel)) {
22
- return false;
23
- }
24
- if (!arg0.id) {
25
- return false;
26
- }
27
- return true;
28
- },
29
- errorMessage: () => `payment must be a payment model and have an id to be refunded`,
30
- };
31
-
32
- export const refundValidator: Validator<RefundData> = {
33
- id: IdValidator<IdRefund>(RefundModel.regex),
34
- amount: amountValidator,
35
- currency: enumValidator(CurrencyEnum),
36
- createdAt: createdAtValidator,
37
- dateBank: plainDateValidator('dateBank'),
38
- dateRefund: plainDateValidator('dateRefund'),
39
- deleted: true,
40
- payment: paymentValidator,
41
- paymentIntent: IdValidator<IdPaymentIntent>(PaymentIntentModel.regex),
42
- payout: IdValidator<IdPayout>(PayoutModel.regex),
43
- status: enumValidator(RefundStatusEnum, false),
44
- };
@@ -1,26 +0,0 @@
1
- import { ApiEndpoint, baseHandler } from '#api/abstract-api-endpoint.js';
2
- import { RFC9557Handler } from '#core/common/handler/date-handler.js';
3
- import { defaultHandler } from '#core/common/handler/handler.js';
4
- import { IdHandler } from '#core/common/handler/id-handler.js';
5
-
6
- import { CustomerModel, type IdCustomer } from '../customer/model.js';
7
- import { type IdSepa, type SepaData, SepaModel } from './model.js';
8
-
9
- export class SepaApiEndpoint extends ApiEndpoint<SepaData> {
10
- public _handler = {
11
- ...baseHandler('created'),
12
- bic: defaultHandler<SepaData['bic']>('string', { patchable: false }),
13
- customer: IdHandler<IdCustomer>(CustomerModel.regex, { patchable: false }),
14
- dateMandate: RFC9557Handler({}),
15
- id: IdHandler<IdSepa>(SepaModel.regex, { postable: false, patchable: false }),
16
- last4: defaultHandler<SepaData['last4']>('string', { postable: false, patchable: false }),
17
- mandate: defaultHandler<SepaData['mandate']>('string'),
18
- name: defaultHandler<SepaData['name']>('string', { postRequired: true }),
19
- iban: defaultHandler<SepaData['iban']>('string', { postRequired: true, gettable: false, patchable: false }),
20
- };
21
- constructor() {
22
- super({
23
- name: 'sepa',
24
- });
25
- }
26
- }
package/src/sepa/model.ts DELETED
@@ -1,80 +0,0 @@
1
- import { AbstractModel, type ModelData } from '#core/abstract-model.js';
2
- import type { IdValue } from '#core/common/branded-type.js';
3
- import { validateID } from '#core/common/id-validator.js';
4
-
5
- import type { IdCustomer } from '../customer/model.js';
6
-
7
- export type IdSepa = IdValue<`sepa_${string}`>;
8
- export const IdSepa = (id: string) => validateID<IdSepa>(id, SepaModel.regex);
9
- export interface SepaData extends ModelData {
10
- bic: string;
11
- customer: IdCustomer;
12
- dateMandate: Temporal.PlainDate;
13
- deleted: boolean;
14
- id: IdSepa;
15
- last4: string;
16
- mandate: string;
17
- name: string;
18
- iban: string;
19
- }
20
- export class SepaModel extends AbstractModel<SepaData> {
21
- static regex = /^sepa_[a-zA-Z0-9]{24}$/;
22
-
23
- get bic() {
24
- return this._data.bic;
25
- }
26
-
27
- get customer() {
28
- return this._data.customer;
29
- }
30
-
31
- get last4() {
32
- if (this._data.iban && !this._data.last4) {
33
- return this._data.iban?.slice(-4);
34
- }
35
- return this._data.last4;
36
- }
37
-
38
- get mandate() {
39
- return this._data.mandate;
40
- }
41
-
42
- get dateMandate() {
43
- return this._data.dateMandate;
44
- }
45
-
46
- get name() {
47
- return this._data.name;
48
- }
49
-
50
- setMandate(value: string) {
51
- this._data.mandate = value;
52
- return this;
53
- }
54
-
55
- setName(value: string) {
56
- this._data.name = value;
57
- return this;
58
- }
59
-
60
- setDateMandate(value: Temporal.PlainDate) {
61
- this._data.dateMandate = value;
62
- return this;
63
- }
64
-
65
- setIban(value: string) {
66
- this._data.iban = value;
67
- this._data.last4 = value.slice(-4);
68
- return this;
69
- }
70
-
71
- setBic(value: string) {
72
- this._data.bic = value;
73
- return this;
74
- }
75
-
76
- setCustomer(value: IdCustomer) {
77
- this._data.customer = value;
78
- return this;
79
- }
80
- }
@@ -1,11 +0,0 @@
1
- import { AbstractRepository, type Repository } from '#core/abstract-repository.js';
2
- import type { EndpointInterface } from '#core/endpoint-interface.js';
3
- import { SepaApiEndpoint } from '#sepa/api-endpoint.js';
4
- import { type SepaData, SepaModel } from '#sepa/model.js';
5
- import { sepaValidator } from '#sepa/validator.js';
6
-
7
- export class SepaRepository extends AbstractRepository<SepaData, SepaModel> implements Repository<SepaData, SepaModel> {
8
- constructor(endpoint?: EndpointInterface<SepaData>) {
9
- super({ endpoint: endpoint ?? new SepaApiEndpoint(), validator: sepaValidator, model: SepaModel });
10
- }
11
- }
@@ -1,56 +0,0 @@
1
- import { Temporal } from 'temporal-polyfill';
2
-
3
- import { IdValidator } from '#core/common/id-validator.js';
4
- import { type Validator, createdAtValidator, goldilocksValidator } from '#core/validator.js';
5
-
6
- import { CustomerModel, type IdCustomer } from '../customer/model.js';
7
- import { type IdSepa, type SepaData, SepaModel } from './model.js';
8
-
9
- // IBAN validation using ISO/IEC 7064 MOD 97-10 algorithm
10
- // See: https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN
11
- export const ibanValidator = {
12
- validate: (arg0: string) => {
13
- const iban = arg0.replaceAll(' ', '');
14
- if (!/^[a-zA-Z0-9]+$/.test(iban)) {
15
- return false;
16
- }
17
- const start = iban.slice(0, 4);
18
- const bban = iban.slice(4);
19
- const codeWithLetters = (bban + start).toUpperCase();
20
-
21
- const letterToNumber = (character: string) => character.charCodeAt(0) - 55;
22
-
23
- const code = codeWithLetters
24
- .split('')
25
- .map((character) => (Number.isNaN(Number(character)) ? letterToNumber(character) : character))
26
- .join('');
27
-
28
- const check = code.slice(0, 2);
29
- const parts = code.slice(2).match(/.{1,7}/g) ?? [];
30
-
31
- const result = parts.reduce((prev, curr) => String(Number(prev + curr) % 97), check);
32
-
33
- if (result === '1') {
34
- return true;
35
- }
36
- return false;
37
- },
38
- errorMessage: (value: string) => `IBAN ending in ${value.slice(-4)} is not valid`,
39
- };
40
-
41
- export const sepaValidator: Validator<SepaData> = {
42
- id: IdValidator<IdSepa>(SepaModel.regex),
43
- bic: goldilocksValidator('bic', { min: 8, max: 11 }),
44
- customer: IdValidator<IdCustomer>(CustomerModel.regex),
45
- createdAt: createdAtValidator,
46
- deleted: true,
47
- dateMandate: {
48
- validate: (arg0: Temporal.PlainDate) =>
49
- arg0.year > 1970 && Temporal.PlainDate.compare(Temporal.Now.plainDateISO(), arg0) === 1,
50
- errorMessage: () => 'DateMandate must be a past date.',
51
- },
52
- iban: ibanValidator,
53
- last4: true,
54
- mandate: goldilocksValidator('mandate', { min: 1, max: 35 }),
55
- name: goldilocksValidator('name', { min: 3, max: 64 }),
56
- };
@@ -1,36 +0,0 @@
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
- }
@@ -1,140 +0,0 @@
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
- }
@@ -1,14 +0,0 @@
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
- }
@@ -1,18 +0,0 @@
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
- };