@miguelmorales13/nestkit 0.10.0 → 0.16.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.
- package/README.md +518 -12
- package/dist/audit/audit.module.d.ts +23 -0
- package/dist/audit/audit.options.d.ts +16 -0
- package/dist/audit/audit.port.d.ts +37 -0
- package/dist/audit/audit.service.d.ts +29 -0
- package/dist/audit/index.cjs +72 -0
- package/dist/audit/index.d.ts +7 -0
- package/dist/audit/index.js +72 -0
- package/dist/audit/sinks.d.ts +18 -0
- package/dist/auth/index.cjs +4 -3
- package/dist/auth/index.js +2 -1
- package/dist/auth/oauth/index.cjs +81 -13
- package/dist/auth/oauth/index.js +75 -7
- package/dist/auth/oauth/oauth-auth.service.d.ts +29 -1
- package/dist/auth/oauth/oauth.options.d.ts +11 -0
- package/dist/bootstrap/index.cjs +6 -5
- package/dist/bootstrap/index.js +5 -4
- package/dist/chunk-47FXU74G.cjs +205 -0
- package/dist/{chunk-54ZXIB5T.cjs → chunk-4GT66KQS.cjs} +4 -4
- package/dist/{chunk-J7TURDAL.cjs → chunk-67B7IYAV.cjs} +2 -2
- package/dist/{chunk-NVCI3CQI.cjs → chunk-C5DV4RAX.cjs} +6 -1
- package/dist/{chunk-KDAA6GFF.js → chunk-DABTRWA6.js} +12 -7
- package/dist/{chunk-ZA56XBCK.cjs → chunk-EBPEMVZU.cjs} +15 -0
- package/dist/{chunk-EYURGACO.js → chunk-JV4EAOF2.js} +1 -1
- package/dist/chunk-KP2ZHJSR.js +35 -0
- package/dist/{chunk-7I2Y7V52.js → chunk-KRC47OX6.js} +1 -1
- package/dist/chunk-LK3OINS7.js +205 -0
- package/dist/{chunk-A3B2EY4V.js → chunk-MLOQDUBN.js} +6 -1
- package/dist/chunk-TCAMLNUZ.js +27 -0
- package/dist/{chunk-V2M75FN3.cjs → chunk-U7QK24HL.cjs} +2 -2
- package/dist/{chunk-AOCF5QCZ.js → chunk-UIVBPNH4.js} +4 -4
- package/dist/{chunk-TJHRABML.cjs → chunk-UWDHAZVE.cjs} +12 -7
- package/dist/chunk-XHW4CTBS.js +57 -0
- package/dist/chunk-XX5ROVSC.cjs +57 -0
- package/dist/chunk-Y72D5L6I.cjs +27 -0
- package/dist/crud/crud.controller.d.ts +3 -1
- package/dist/crud/crud.service.d.ts +63 -4
- package/dist/crud/index.cjs +7 -2
- package/dist/crud/index.d.ts +2 -1
- package/dist/crud/index.js +6 -1
- package/dist/crud/list-query.dto.d.ts +23 -0
- package/dist/crud/repository.port.d.ts +33 -1
- package/dist/errors/index.cjs +4 -4
- package/dist/errors/index.js +4 -4
- package/dist/idempotency/idempotency.interceptor.d.ts +35 -0
- package/dist/idempotency/idempotency.module.d.ts +27 -0
- package/dist/idempotency/idempotency.options.d.ts +29 -0
- package/dist/idempotency/idempotency.port.d.ts +43 -0
- package/dist/idempotency/index.cjs +206 -0
- package/dist/idempotency/index.d.ts +7 -0
- package/dist/idempotency/index.js +206 -0
- package/dist/idempotency/memory.store.d.ts +24 -0
- package/dist/index.cjs +24 -13
- package/dist/index.js +29 -18
- package/dist/invoicing/adapters/facturama.invoicing.d.ts +50 -0
- package/dist/invoicing/adapters/facturapi.invoicing.d.ts +35 -0
- package/dist/invoicing/amounts.d.ts +52 -0
- package/dist/invoicing/index.cjs +577 -0
- package/dist/invoicing/index.d.ts +11 -0
- package/dist/invoicing/index.js +577 -0
- package/dist/invoicing/invoicing.module.d.ts +42 -0
- package/dist/invoicing/invoicing.options.d.ts +51 -0
- package/dist/invoicing/invoicing.port.d.ts +156 -0
- package/dist/invoicing/lines.d.ts +21 -0
- package/dist/invoicing/provider-http.d.ts +21 -0
- package/dist/media/index.cjs +57 -7
- package/dist/media/index.d.ts +2 -2
- package/dist/media/index.js +56 -6
- package/dist/media/media.options.d.ts +20 -0
- package/dist/media/media.service.d.ts +18 -1
- package/dist/payments/adapters/clip.terminal.d.ts +101 -0
- package/dist/payments/adapters/mercadopago.terminal.d.ts +74 -0
- package/dist/payments/index.cjs +795 -0
- package/dist/payments/index.d.ts +12 -0
- package/dist/payments/index.js +795 -0
- package/dist/payments/money.d.ts +20 -0
- package/dist/payments/payments-webhook.controller.d.ts +30 -0
- package/dist/payments/payments.module.d.ts +45 -0
- package/dist/payments/payments.options.d.ts +84 -0
- package/dist/payments/payments.port.d.ts +174 -0
- package/dist/payments/provider-http.d.ts +26 -0
- package/dist/response/api-response.d.ts +7 -0
- package/dist/response/index.cjs +12 -4
- package/dist/response/index.d.ts +2 -0
- package/dist/response/index.js +12 -4
- package/dist/response/paginated.d.ts +25 -0
- package/dist/response/response.interceptor.d.ts +4 -0
- package/dist/tracking/index.cjs +3 -3
- package/dist/tracking/index.d.ts +1 -1
- package/dist/tracking/index.js +2 -2
- package/dist/tracking/request-context.d.ts +22 -0
- package/package.json +25 -3
- package/dist/chunk-3CLYZC3T.cjs +0 -104
- package/dist/chunk-EBO6UKHL.js +0 -20
- package/dist/chunk-JOVBJDJ2.js +0 -104
- /package/dist/{chunk-MR2IFCZE.cjs → chunk-H2EHN366.cjs} +0 -0
- /package/dist/{chunk-NAK4WDKS.js → chunk-ODPSIFOB.js} +0 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DI token for the invoicing adapter. Inject with
|
|
3
|
+
* `@Inject(INVOICING) invoicing: InvoicingPort`.
|
|
4
|
+
*/
|
|
5
|
+
export declare const INVOICING: unique symbol;
|
|
6
|
+
/** `TipoDeComprobante`: income, egress, transfer, payroll, payment. */
|
|
7
|
+
export type CfdiType = 'I' | 'E' | 'T' | 'N' | 'P';
|
|
8
|
+
/**
|
|
9
|
+
* `MetodoPago`. `PUE` is paid in one go; `PPD` is paid later or in
|
|
10
|
+
* instalments, and **obliges you to issue a payment complement** (a `type: 'P'`
|
|
11
|
+
* CFDI) for every payment received afterwards. Choosing PPD and never issuing
|
|
12
|
+
* the complement is the most common way a business ends up with an invoice the
|
|
13
|
+
* SAT considers unfinished.
|
|
14
|
+
*/
|
|
15
|
+
export type PaymentMethod = 'PUE' | 'PPD';
|
|
16
|
+
/**
|
|
17
|
+
* Why an invoice is being cancelled. Mandatory since the 2022 rules — there is
|
|
18
|
+
* no cancellation without one:
|
|
19
|
+
*
|
|
20
|
+
* - `01` issued with errors, replaced by another invoice (needs `substitutionId`)
|
|
21
|
+
* - `02` issued with errors, not replaced
|
|
22
|
+
* - `03` the operation never happened
|
|
23
|
+
* - `04` nominative operation related to a global invoice
|
|
24
|
+
*/
|
|
25
|
+
export type CancelMotive = '01' | '02' | '03' | '04';
|
|
26
|
+
export type InvoiceStatus = 'draft' | 'stamped' | 'cancelled' | 'pending' | 'unknown';
|
|
27
|
+
/**
|
|
28
|
+
* The receiver.
|
|
29
|
+
*
|
|
30
|
+
* `legalName`, `taxSystem` and `zip` have to match what the SAT has on file for
|
|
31
|
+
* that RFC, character for character — CFDI 4.0 validates them against the
|
|
32
|
+
* padrón. A name with `S.A. de C.V.` when the SAT stored it without, or last
|
|
33
|
+
* year's postal code, is rejected at stamping time, and the message names the
|
|
34
|
+
* field but not the right value. Ask the customer for their *constancia de
|
|
35
|
+
* situación fiscal* instead of typing what is on the invoice they sent you.
|
|
36
|
+
*/
|
|
37
|
+
export interface InvoiceCustomer {
|
|
38
|
+
/** RFC. */
|
|
39
|
+
taxId: string;
|
|
40
|
+
/** Razón social exactly as the SAT holds it. */
|
|
41
|
+
legalName: string;
|
|
42
|
+
/** Régimen fiscal, e.g. `601` (general de ley), `626` (RESICO), `616` (sin obligaciones). */
|
|
43
|
+
taxSystem: string;
|
|
44
|
+
/** Código postal of the receiver's tax domicile. */
|
|
45
|
+
zip: string;
|
|
46
|
+
/** `UsoCFDI`, e.g. `G01` acquisition of goods, `G03` general expenses, `S01` no tax effect. */
|
|
47
|
+
use?: string;
|
|
48
|
+
email?: string;
|
|
49
|
+
}
|
|
50
|
+
export interface InvoiceTax {
|
|
51
|
+
type: 'IVA' | 'ISR' | 'IEPS';
|
|
52
|
+
/** Decimal rate as the SAT writes it: `0.16`, `0.08`, `0.106666`. */
|
|
53
|
+
rate: number;
|
|
54
|
+
/** A withholding (retención) rather than a transfer (traslado). */
|
|
55
|
+
withholding?: boolean;
|
|
56
|
+
}
|
|
57
|
+
export interface InvoiceItem {
|
|
58
|
+
description: string;
|
|
59
|
+
/** `ClaveProdServ` from the SAT catalogue. */
|
|
60
|
+
productKey: string;
|
|
61
|
+
/** `ClaveUnidad`. Defaults to `H87` (pieza). */
|
|
62
|
+
unitKey?: string;
|
|
63
|
+
/** Free-text unit name shown on the PDF. */
|
|
64
|
+
unitName?: string;
|
|
65
|
+
/** Defaults to 1. May be fractional — kilos, litres, hours. */
|
|
66
|
+
quantity?: number;
|
|
67
|
+
/** Unit price in integer cents. Use this unless you genuinely need more than two decimals. */
|
|
68
|
+
unitPriceCents?: number;
|
|
69
|
+
/**
|
|
70
|
+
* Unit price as an exact decimal string, up to six places — per-litre or
|
|
71
|
+
* per-kilo pricing. Passed through untouched; never parsed into a float and
|
|
72
|
+
* printed back.
|
|
73
|
+
*/
|
|
74
|
+
unitPrice?: string;
|
|
75
|
+
/** `NoIdentificacion`: your own SKU. */
|
|
76
|
+
sku?: string;
|
|
77
|
+
/** Defaults to a single 16% transferred IVA. Pass `[]` for something genuinely untaxed. */
|
|
78
|
+
taxes?: InvoiceTax[];
|
|
79
|
+
/** `ObjetoImp`. Defaults to `02` (subject to tax); `01` is not subject. */
|
|
80
|
+
taxObject?: string;
|
|
81
|
+
}
|
|
82
|
+
export interface InvoiceDraft {
|
|
83
|
+
/** The receiver, inline — or the id of one already stored at the provider. */
|
|
84
|
+
customer: InvoiceCustomer | string;
|
|
85
|
+
items: InvoiceItem[];
|
|
86
|
+
/** `FormaPago`: `01` cash, `03` transfer, `04` credit card, `28` debit card, `99` to be defined. */
|
|
87
|
+
paymentForm: string;
|
|
88
|
+
/** Defaults to `PUE`. */
|
|
89
|
+
paymentMethod?: PaymentMethod;
|
|
90
|
+
/** `UsoCFDI` for this invoice, when it differs from the customer's default. */
|
|
91
|
+
use?: string;
|
|
92
|
+
/** Defaults to `I` (ingreso). */
|
|
93
|
+
type?: CfdiType;
|
|
94
|
+
/** Defaults to `MXN`. */
|
|
95
|
+
currency?: string;
|
|
96
|
+
/** `TipoCambio`, required by the SAT whenever the currency is not MXN. */
|
|
97
|
+
exchangeRate?: number;
|
|
98
|
+
series?: string;
|
|
99
|
+
folioNumber?: number;
|
|
100
|
+
/** Your own id for this invoice, echoed back by the provider. */
|
|
101
|
+
externalId?: string;
|
|
102
|
+
}
|
|
103
|
+
export interface Invoice {
|
|
104
|
+
/** The provider's id — what every other method here takes. */
|
|
105
|
+
id: string;
|
|
106
|
+
provider: string;
|
|
107
|
+
status: InvoiceStatus;
|
|
108
|
+
/** Folio fiscal. Present once it is actually stamped. */
|
|
109
|
+
uuid?: string;
|
|
110
|
+
series?: string;
|
|
111
|
+
folioNumber?: number;
|
|
112
|
+
subtotalCents?: number;
|
|
113
|
+
totalCents: number;
|
|
114
|
+
currency: string;
|
|
115
|
+
customerTaxId?: string;
|
|
116
|
+
issuedAt?: Date;
|
|
117
|
+
raw: unknown;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* One port, several PACs. Nothing above this interface knows which one stamps.
|
|
121
|
+
*
|
|
122
|
+
* The port models the **invoice**, not the XML. Providers that build and sign
|
|
123
|
+
* the CFDI for you (Facturapi, Facturama) fit behind it; a PAC that only stamps
|
|
124
|
+
* an XML you sealed yourself with your own CSD is a different job — you would
|
|
125
|
+
* be generating the document, and this library does not do that.
|
|
126
|
+
*
|
|
127
|
+
* What it does do, before either adapter sees the draft, is the arithmetic:
|
|
128
|
+
* line amount, tax, total, in integer cents. Facturapi recomputes and would
|
|
129
|
+
* forgive a bad number; Facturama prints ours onto the document. One
|
|
130
|
+
* calculation, one answer, whichever is registered.
|
|
131
|
+
*/
|
|
132
|
+
export interface InvoicingPort {
|
|
133
|
+
/** Which PAC this is: `'facturapi'`, `'facturama'`. */
|
|
134
|
+
readonly provider: string;
|
|
135
|
+
/** Build, sign and stamp an invoice. In a test environment it is validated but not sent to the SAT. */
|
|
136
|
+
issue(draft: InvoiceDraft): Promise<Invoice>;
|
|
137
|
+
get(id: string): Promise<Invoice>;
|
|
138
|
+
/**
|
|
139
|
+
* Cancel a stamped invoice. `motive` is mandatory, and `01` also requires the
|
|
140
|
+
* id of the invoice that replaces this one.
|
|
141
|
+
*
|
|
142
|
+
* Cancelling is a request, not a command: outside the allowed window, or when
|
|
143
|
+
* the receiver has to authorise it, the SAT leaves it pending and the status
|
|
144
|
+
* only settles later. Read it back rather than assuming it worked.
|
|
145
|
+
*/
|
|
146
|
+
cancel(id: string, options: {
|
|
147
|
+
motive: CancelMotive;
|
|
148
|
+
substitutionId?: string;
|
|
149
|
+
}): Promise<Invoice>;
|
|
150
|
+
/** The printed representation, as bytes. */
|
|
151
|
+
pdf(id: string): Promise<Uint8Array>;
|
|
152
|
+
/** The stamped XML — the document that legally matters, the PDF is a courtesy. */
|
|
153
|
+
xml(id: string): Promise<string>;
|
|
154
|
+
/** Send it to the receiver. Defaults to the email on the customer record. */
|
|
155
|
+
sendByEmail(id: string, to?: string): Promise<void>;
|
|
156
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { centsToDecimal } from './amounts.js';
|
|
2
|
+
import type { InvoiceItem, InvoiceTax } from './invoicing.port.js';
|
|
3
|
+
/** Every number a line needs, computed once, in cents. */
|
|
4
|
+
export interface ComputedLine {
|
|
5
|
+
item: InvoiceItem;
|
|
6
|
+
quantity: number;
|
|
7
|
+
unitPriceDecimal: string;
|
|
8
|
+
amountCents: number;
|
|
9
|
+
taxes: {
|
|
10
|
+
tax: InvoiceTax;
|
|
11
|
+
baseCents: number;
|
|
12
|
+
amountCents: number;
|
|
13
|
+
}[];
|
|
14
|
+
/** Amount plus transfers minus withholdings. */
|
|
15
|
+
totalCents: number;
|
|
16
|
+
}
|
|
17
|
+
export declare function computeLine(item: InvoiceItem): ComputedLine;
|
|
18
|
+
export declare function computeLines(items: InvoiceItem[]): ComputedLine[];
|
|
19
|
+
export declare function sumCents(lines: ComputedLine[], field: 'amountCents' | 'totalCents'): number;
|
|
20
|
+
/** Convenience for adapters that print the numbers rather than recompute them. */
|
|
21
|
+
export declare const decimal: typeof centsToDecimal;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { AppException } from '../errors/app.exception.js';
|
|
2
|
+
/**
|
|
3
|
+
* A call to the PAC that came back wrong.
|
|
4
|
+
*
|
|
5
|
+
* 502, not the PAC's own status: a stamping rejection is not the caller's
|
|
6
|
+
* request being malformed, and turning a 400 from the SAT into a 400 for your
|
|
7
|
+
* client sends them to fix something they did not break. The original status
|
|
8
|
+
* and body stay in `details` — with a CFDI that matters more than usual,
|
|
9
|
+
* because the SAT's message names the field that failed validation.
|
|
10
|
+
*/
|
|
11
|
+
export declare class InvoicingProviderException extends AppException {
|
|
12
|
+
constructor(provider: string, status: number, body: unknown, message?: string);
|
|
13
|
+
}
|
|
14
|
+
/** Thrown when an adapter is asked for something its PAC does not do. */
|
|
15
|
+
export declare class UnsupportedByProviderException extends AppException {
|
|
16
|
+
constructor(provider: string, message: string);
|
|
17
|
+
}
|
|
18
|
+
/** JSON in, JSON out, with any non-2xx turned into {@link InvoicingProviderException}. */
|
|
19
|
+
export declare function requestJson<T>(provider: string, fetchImpl: typeof fetch, url: string, init: RequestInit): Promise<T>;
|
|
20
|
+
/** For endpoints that answer with the file itself rather than with JSON. */
|
|
21
|
+
export declare function requestBytes(provider: string, fetchImpl: typeof fetch, url: string, init: RequestInit): Promise<Uint8Array>;
|
package/dist/media/index.cjs
CHANGED
|
@@ -20,28 +20,60 @@ var _common = require('@nestjs/common');
|
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
|
|
23
|
+
var _crypto = require('crypto');
|
|
24
|
+
|
|
23
25
|
// src/media/media.service.ts
|
|
24
26
|
|
|
25
27
|
|
|
26
28
|
// src/media/media.options.ts
|
|
27
29
|
var MEDIA_OPTIONS = /* @__PURE__ */ Symbol("MEDIA_OPTIONS");
|
|
28
30
|
var MEDIA_TTL = /* @__PURE__ */ Symbol("MEDIA_TTL");
|
|
31
|
+
var MEDIA_LIMITS = /* @__PURE__ */ Symbol("MEDIA_LIMITS");
|
|
29
32
|
|
|
30
33
|
// src/media/media.service.ts
|
|
31
|
-
|
|
34
|
+
|
|
32
35
|
var MediaService = class {
|
|
33
|
-
constructor(ttlMs) {
|
|
36
|
+
constructor(ttlMs, limits) {
|
|
34
37
|
this.ttlMs = ttlMs;
|
|
38
|
+
this.limits = limits;
|
|
35
39
|
this.logger = new (0, _common.Logger)(MediaService.name);
|
|
36
40
|
this.store = /* @__PURE__ */ new Map();
|
|
37
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* Stores a file, or throws if the store is already full.
|
|
44
|
+
*
|
|
45
|
+
* The ceiling matters more than it looks. This map is the process's own
|
|
46
|
+
* heap, entries live for an hour, and nothing here bounded how many there
|
|
47
|
+
* could be: a loop against the upload endpoint — a bug in a publishing job
|
|
48
|
+
* as easily as someone with the secret — grows it until the process dies,
|
|
49
|
+
* and it takes the whole API down with it, not just uploads.
|
|
50
|
+
*
|
|
51
|
+
* Refusing is the right answer rather than evicting the oldest: an eviction
|
|
52
|
+
* would silently break a publication already in flight, and the caller
|
|
53
|
+
* cannot tell that its image vanished until the remote service reports a
|
|
54
|
+
* 404 it cannot explain.
|
|
55
|
+
*/
|
|
38
56
|
put(data, contentType) {
|
|
39
57
|
this.sweep();
|
|
58
|
+
if (this.store.size >= this.limits.maxFiles) {
|
|
59
|
+
throw new (0, _common.PayloadTooLargeException)(
|
|
60
|
+
`The media store is full (${this.limits.maxFiles} files). Try again shortly.`
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
const total = this.bytesHeld();
|
|
64
|
+
if (total + data.length > this.limits.maxTotalBytes) {
|
|
65
|
+
throw new (0, _common.PayloadTooLargeException)("The media store is out of room. Try again shortly.");
|
|
66
|
+
}
|
|
40
67
|
const id = _crypto.randomUUID.call(void 0, ).replace(/-/g, "");
|
|
41
68
|
this.store.set(id, { data, contentType, expiresAt: Date.now() + this.ttlMs });
|
|
42
69
|
this.logger.log(`Stored ${id} (${(data.length / 1024).toFixed(0)} KB)`);
|
|
43
70
|
return id;
|
|
44
71
|
}
|
|
72
|
+
bytesHeld() {
|
|
73
|
+
let total = 0;
|
|
74
|
+
for (const entry of this.store.values()) total += entry.data.length;
|
|
75
|
+
return total;
|
|
76
|
+
}
|
|
45
77
|
get(id) {
|
|
46
78
|
const found = this.store.get(id);
|
|
47
79
|
if (!found) return void 0;
|
|
@@ -61,10 +93,18 @@ var MediaService = class {
|
|
|
61
93
|
};
|
|
62
94
|
MediaService = exports.MediaService = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
|
63
95
|
_common.Injectable.call(void 0, ),
|
|
64
|
-
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, MEDIA_TTL))
|
|
96
|
+
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, MEDIA_TTL)),
|
|
97
|
+
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, MEDIA_LIMITS))
|
|
65
98
|
], MediaService);
|
|
66
99
|
|
|
67
100
|
// src/media/media.controller.ts
|
|
101
|
+
function secretMatches(received, expected) {
|
|
102
|
+
if (!received) return false;
|
|
103
|
+
const a = Buffer.from(received);
|
|
104
|
+
const b = Buffer.from(expected);
|
|
105
|
+
return a.length === b.length && _crypto.timingSafeEqual.call(void 0, a, b);
|
|
106
|
+
}
|
|
107
|
+
var DEFAULT_ALLOWED = ["image/png", "image/jpeg", "image/webp", "image/gif"];
|
|
68
108
|
var MediaController = class {
|
|
69
109
|
// Both dependencies are injected by explicit token, like the rest of this
|
|
70
110
|
// package. The bundler does not emit decorator metadata, so injecting by type
|
|
@@ -78,18 +118,25 @@ var MediaController = class {
|
|
|
78
118
|
if (!this.options.uploadSecret) {
|
|
79
119
|
throw new (0, _common.UnauthorizedException)("Media uploads are not configured.");
|
|
80
120
|
}
|
|
81
|
-
if (secret
|
|
121
|
+
if (!secretMatches(secret, this.options.uploadSecret)) {
|
|
82
122
|
throw new (0, _common.UnauthorizedException)("Invalid secret.");
|
|
83
123
|
}
|
|
84
124
|
const data = request.body;
|
|
85
125
|
if (!_optionalChain([data, 'optionalAccess', _ => _.length])) throw new (0, _common.UnauthorizedException)("Empty body.");
|
|
86
|
-
const
|
|
126
|
+
const allowed = _nullishCoalesce(this.options.allowedContentTypes, () => ( DEFAULT_ALLOWED));
|
|
127
|
+
const declared = _optionalChain([request, 'access', _2 => _2.headers, 'access', _3 => _3["content-type"], 'optionalAccess', _4 => _4.split, 'call', _5 => _5(";"), 'access', _6 => _6[0], 'optionalAccess', _7 => _7.trim, 'call', _8 => _8(), 'access', _9 => _9.toLowerCase, 'call', _10 => _10()]);
|
|
128
|
+
if (!declared || !allowed.includes(declared)) {
|
|
129
|
+
throw new (0, _common.BadRequestException)(
|
|
130
|
+
`Unsupported content type. Allowed: ${allowed.join(", ")}.`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
const id = this.media.put(Buffer.from(data), declared);
|
|
87
134
|
return { url: `${this.options.publicUrl}/media/${id}` };
|
|
88
135
|
}
|
|
89
136
|
serve(id, reply) {
|
|
90
137
|
const found = this.media.get(id);
|
|
91
138
|
if (!found) throw new (0, _common.NotFoundException)("That file is no longer available.");
|
|
92
|
-
reply.header("content-type", found.contentType).header("cache-control", "no-store").send(found.data);
|
|
139
|
+
reply.header("content-type", found.contentType).header("cache-control", "no-store").header("x-content-type-options", "nosniff").send(found.data);
|
|
93
140
|
}
|
|
94
141
|
};
|
|
95
142
|
_chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
|
@@ -110,6 +157,7 @@ MediaController = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
|
|
110
157
|
|
|
111
158
|
// src/media/media.module.ts
|
|
112
159
|
var ONE_HOUR = 60 * 60 * 1e3;
|
|
160
|
+
var DEFAULT_LIMITS = { maxFiles: 50, maxTotalBytes: 256 * 1024 * 1024 };
|
|
113
161
|
var MediaModule = class {
|
|
114
162
|
static forRoot(options) {
|
|
115
163
|
return {
|
|
@@ -118,6 +166,7 @@ var MediaModule = class {
|
|
|
118
166
|
providers: [
|
|
119
167
|
{ provide: MEDIA_OPTIONS, useValue: options },
|
|
120
168
|
{ provide: MEDIA_TTL, useValue: _nullishCoalesce(options.ttlMs, () => ( ONE_HOUR)) },
|
|
169
|
+
{ provide: MEDIA_LIMITS, useValue: { ...DEFAULT_LIMITS, ...options.limits } },
|
|
121
170
|
MediaService
|
|
122
171
|
],
|
|
123
172
|
exports: [MediaService]
|
|
@@ -132,4 +181,5 @@ MediaModule = exports.MediaModule = _chunk2REOCMUDcjs.__decorateClass.call(void
|
|
|
132
181
|
|
|
133
182
|
|
|
134
183
|
|
|
135
|
-
|
|
184
|
+
|
|
185
|
+
exports.MEDIA_LIMITS = MEDIA_LIMITS; exports.MEDIA_OPTIONS = MEDIA_OPTIONS; exports.MEDIA_TTL = MEDIA_TTL; exports.MediaModule = MediaModule; exports.MediaService = MediaService;
|
package/dist/media/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { MediaModule } from './media.module.js';
|
|
2
2
|
export { MediaService } from './media.service.js';
|
|
3
|
-
export { MEDIA_OPTIONS, MEDIA_TTL } from './media.options.js';
|
|
4
|
-
export type { MediaOptions } from './media.options.js';
|
|
3
|
+
export { MEDIA_OPTIONS, MEDIA_TTL, MEDIA_LIMITS } from './media.options.js';
|
|
4
|
+
export type { MediaOptions, MediaLimits } from './media.options.js';
|
|
5
5
|
export type { StoredMedia } from './media.service.js';
|
package/dist/media/index.js
CHANGED
|
@@ -8,6 +8,7 @@ import { Module } from "@nestjs/common";
|
|
|
8
8
|
|
|
9
9
|
// src/media/media.controller.ts
|
|
10
10
|
import {
|
|
11
|
+
BadRequestException,
|
|
11
12
|
Controller,
|
|
12
13
|
Get,
|
|
13
14
|
Headers,
|
|
@@ -19,29 +20,60 @@ import {
|
|
|
19
20
|
Res,
|
|
20
21
|
UnauthorizedException
|
|
21
22
|
} from "@nestjs/common";
|
|
23
|
+
import { timingSafeEqual } from "crypto";
|
|
22
24
|
|
|
23
25
|
// src/media/media.service.ts
|
|
24
|
-
import { Inject, Injectable, Logger } from "@nestjs/common";
|
|
26
|
+
import { Inject, Injectable, Logger, PayloadTooLargeException } from "@nestjs/common";
|
|
25
27
|
|
|
26
28
|
// src/media/media.options.ts
|
|
27
29
|
var MEDIA_OPTIONS = /* @__PURE__ */ Symbol("MEDIA_OPTIONS");
|
|
28
30
|
var MEDIA_TTL = /* @__PURE__ */ Symbol("MEDIA_TTL");
|
|
31
|
+
var MEDIA_LIMITS = /* @__PURE__ */ Symbol("MEDIA_LIMITS");
|
|
29
32
|
|
|
30
33
|
// src/media/media.service.ts
|
|
31
34
|
import { randomUUID } from "crypto";
|
|
32
35
|
var MediaService = class {
|
|
33
|
-
constructor(ttlMs) {
|
|
36
|
+
constructor(ttlMs, limits) {
|
|
34
37
|
this.ttlMs = ttlMs;
|
|
38
|
+
this.limits = limits;
|
|
35
39
|
this.logger = new Logger(MediaService.name);
|
|
36
40
|
this.store = /* @__PURE__ */ new Map();
|
|
37
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* Stores a file, or throws if the store is already full.
|
|
44
|
+
*
|
|
45
|
+
* The ceiling matters more than it looks. This map is the process's own
|
|
46
|
+
* heap, entries live for an hour, and nothing here bounded how many there
|
|
47
|
+
* could be: a loop against the upload endpoint — a bug in a publishing job
|
|
48
|
+
* as easily as someone with the secret — grows it until the process dies,
|
|
49
|
+
* and it takes the whole API down with it, not just uploads.
|
|
50
|
+
*
|
|
51
|
+
* Refusing is the right answer rather than evicting the oldest: an eviction
|
|
52
|
+
* would silently break a publication already in flight, and the caller
|
|
53
|
+
* cannot tell that its image vanished until the remote service reports a
|
|
54
|
+
* 404 it cannot explain.
|
|
55
|
+
*/
|
|
38
56
|
put(data, contentType) {
|
|
39
57
|
this.sweep();
|
|
58
|
+
if (this.store.size >= this.limits.maxFiles) {
|
|
59
|
+
throw new PayloadTooLargeException(
|
|
60
|
+
`The media store is full (${this.limits.maxFiles} files). Try again shortly.`
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
const total = this.bytesHeld();
|
|
64
|
+
if (total + data.length > this.limits.maxTotalBytes) {
|
|
65
|
+
throw new PayloadTooLargeException("The media store is out of room. Try again shortly.");
|
|
66
|
+
}
|
|
40
67
|
const id = randomUUID().replace(/-/g, "");
|
|
41
68
|
this.store.set(id, { data, contentType, expiresAt: Date.now() + this.ttlMs });
|
|
42
69
|
this.logger.log(`Stored ${id} (${(data.length / 1024).toFixed(0)} KB)`);
|
|
43
70
|
return id;
|
|
44
71
|
}
|
|
72
|
+
bytesHeld() {
|
|
73
|
+
let total = 0;
|
|
74
|
+
for (const entry of this.store.values()) total += entry.data.length;
|
|
75
|
+
return total;
|
|
76
|
+
}
|
|
45
77
|
get(id) {
|
|
46
78
|
const found = this.store.get(id);
|
|
47
79
|
if (!found) return void 0;
|
|
@@ -61,10 +93,18 @@ var MediaService = class {
|
|
|
61
93
|
};
|
|
62
94
|
MediaService = __decorateClass([
|
|
63
95
|
Injectable(),
|
|
64
|
-
__decorateParam(0, Inject(MEDIA_TTL))
|
|
96
|
+
__decorateParam(0, Inject(MEDIA_TTL)),
|
|
97
|
+
__decorateParam(1, Inject(MEDIA_LIMITS))
|
|
65
98
|
], MediaService);
|
|
66
99
|
|
|
67
100
|
// src/media/media.controller.ts
|
|
101
|
+
function secretMatches(received, expected) {
|
|
102
|
+
if (!received) return false;
|
|
103
|
+
const a = Buffer.from(received);
|
|
104
|
+
const b = Buffer.from(expected);
|
|
105
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
106
|
+
}
|
|
107
|
+
var DEFAULT_ALLOWED = ["image/png", "image/jpeg", "image/webp", "image/gif"];
|
|
68
108
|
var MediaController = class {
|
|
69
109
|
// Both dependencies are injected by explicit token, like the rest of this
|
|
70
110
|
// package. The bundler does not emit decorator metadata, so injecting by type
|
|
@@ -78,18 +118,25 @@ var MediaController = class {
|
|
|
78
118
|
if (!this.options.uploadSecret) {
|
|
79
119
|
throw new UnauthorizedException("Media uploads are not configured.");
|
|
80
120
|
}
|
|
81
|
-
if (secret
|
|
121
|
+
if (!secretMatches(secret, this.options.uploadSecret)) {
|
|
82
122
|
throw new UnauthorizedException("Invalid secret.");
|
|
83
123
|
}
|
|
84
124
|
const data = request.body;
|
|
85
125
|
if (!data?.length) throw new UnauthorizedException("Empty body.");
|
|
86
|
-
const
|
|
126
|
+
const allowed = this.options.allowedContentTypes ?? DEFAULT_ALLOWED;
|
|
127
|
+
const declared = request.headers["content-type"]?.split(";")[0]?.trim().toLowerCase();
|
|
128
|
+
if (!declared || !allowed.includes(declared)) {
|
|
129
|
+
throw new BadRequestException(
|
|
130
|
+
`Unsupported content type. Allowed: ${allowed.join(", ")}.`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
const id = this.media.put(Buffer.from(data), declared);
|
|
87
134
|
return { url: `${this.options.publicUrl}/media/${id}` };
|
|
88
135
|
}
|
|
89
136
|
serve(id, reply) {
|
|
90
137
|
const found = this.media.get(id);
|
|
91
138
|
if (!found) throw new NotFoundException("That file is no longer available.");
|
|
92
|
-
reply.header("content-type", found.contentType).header("cache-control", "no-store").send(found.data);
|
|
139
|
+
reply.header("content-type", found.contentType).header("cache-control", "no-store").header("x-content-type-options", "nosniff").send(found.data);
|
|
93
140
|
}
|
|
94
141
|
};
|
|
95
142
|
__decorateClass([
|
|
@@ -110,6 +157,7 @@ MediaController = __decorateClass([
|
|
|
110
157
|
|
|
111
158
|
// src/media/media.module.ts
|
|
112
159
|
var ONE_HOUR = 60 * 60 * 1e3;
|
|
160
|
+
var DEFAULT_LIMITS = { maxFiles: 50, maxTotalBytes: 256 * 1024 * 1024 };
|
|
113
161
|
var MediaModule = class {
|
|
114
162
|
static forRoot(options) {
|
|
115
163
|
return {
|
|
@@ -118,6 +166,7 @@ var MediaModule = class {
|
|
|
118
166
|
providers: [
|
|
119
167
|
{ provide: MEDIA_OPTIONS, useValue: options },
|
|
120
168
|
{ provide: MEDIA_TTL, useValue: options.ttlMs ?? ONE_HOUR },
|
|
169
|
+
{ provide: MEDIA_LIMITS, useValue: { ...DEFAULT_LIMITS, ...options.limits } },
|
|
121
170
|
MediaService
|
|
122
171
|
],
|
|
123
172
|
exports: [MediaService]
|
|
@@ -128,6 +177,7 @@ MediaModule = __decorateClass([
|
|
|
128
177
|
Module({})
|
|
129
178
|
], MediaModule);
|
|
130
179
|
export {
|
|
180
|
+
MEDIA_LIMITS,
|
|
131
181
|
MEDIA_OPTIONS,
|
|
132
182
|
MEDIA_TTL,
|
|
133
183
|
MediaModule,
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
export declare const MEDIA_OPTIONS: unique symbol;
|
|
2
2
|
export declare const MEDIA_TTL: unique symbol;
|
|
3
|
+
export declare const MEDIA_LIMITS: unique symbol;
|
|
4
|
+
/** What the store refuses to exceed. See `MediaService` for why it has to. */
|
|
5
|
+
export interface MediaLimits {
|
|
6
|
+
maxFiles: number;
|
|
7
|
+
maxTotalBytes: number;
|
|
8
|
+
}
|
|
3
9
|
export interface MediaOptions {
|
|
4
10
|
/**
|
|
5
11
|
* Base URL the generated links point to, **including the global prefix** if
|
|
@@ -9,6 +15,20 @@ export interface MediaOptions {
|
|
|
9
15
|
publicUrl: string;
|
|
10
16
|
/** Shared secret required to upload. Without it, uploads are refused. */
|
|
11
17
|
uploadSecret?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Content types accepted on upload and echoed back when serving.
|
|
20
|
+
*
|
|
21
|
+
* Defaults to PNG, JPEG, WebP and GIF — deliberately **not** SVG. An SVG is
|
|
22
|
+
* a document that can carry script, and serving one from your own domain
|
|
23
|
+
* runs that script in your application's origin: same cookies, same
|
|
24
|
+
* storage. Widen this only for formats that cannot execute.
|
|
25
|
+
*/
|
|
26
|
+
allowedContentTypes?: string[];
|
|
27
|
+
/**
|
|
28
|
+
* Ceiling on what the store may hold at once. Defaults to 50 files and
|
|
29
|
+
* 256 MB. Uploads beyond it are refused rather than queued.
|
|
30
|
+
*/
|
|
31
|
+
limits?: Partial<MediaLimits>;
|
|
12
32
|
/** How long a file stays available. Defaults to one hour. */
|
|
13
33
|
ttlMs?: number;
|
|
14
34
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type MediaLimits } from './media.options.js';
|
|
1
2
|
export interface StoredMedia {
|
|
2
3
|
data: Buffer;
|
|
3
4
|
contentType: string;
|
|
@@ -18,10 +19,26 @@ export interface StoredMedia {
|
|
|
18
19
|
*/
|
|
19
20
|
export declare class MediaService {
|
|
20
21
|
private readonly ttlMs;
|
|
22
|
+
private readonly limits;
|
|
21
23
|
private readonly logger;
|
|
22
24
|
private readonly store;
|
|
23
|
-
constructor(ttlMs: number);
|
|
25
|
+
constructor(ttlMs: number, limits: MediaLimits);
|
|
26
|
+
/**
|
|
27
|
+
* Stores a file, or throws if the store is already full.
|
|
28
|
+
*
|
|
29
|
+
* The ceiling matters more than it looks. This map is the process's own
|
|
30
|
+
* heap, entries live for an hour, and nothing here bounded how many there
|
|
31
|
+
* could be: a loop against the upload endpoint — a bug in a publishing job
|
|
32
|
+
* as easily as someone with the secret — grows it until the process dies,
|
|
33
|
+
* and it takes the whole API down with it, not just uploads.
|
|
34
|
+
*
|
|
35
|
+
* Refusing is the right answer rather than evicting the oldest: an eviction
|
|
36
|
+
* would silently break a publication already in flight, and the caller
|
|
37
|
+
* cannot tell that its image vanished until the remote service reports a
|
|
38
|
+
* 404 it cannot explain.
|
|
39
|
+
*/
|
|
24
40
|
put(data: Buffer, contentType: string): string;
|
|
41
|
+
private bytesHeld;
|
|
25
42
|
get(id: string): StoredMedia | undefined;
|
|
26
43
|
/** Swept on write, which is the only moment the map can have grown. */
|
|
27
44
|
private sweep;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { ClipPinpadOptions } from '../payments.options.js';
|
|
2
|
+
import type { ChargeInput, Terminal, TerminalPayment, TerminalPaymentsPort, TerminalWebhookEvent, WebhookRequestLike } from '../payments.port.js';
|
|
3
|
+
/** One settled card transaction behind a PinPad charge. Its id is what a refund takes. */
|
|
4
|
+
export interface ClipTransaction {
|
|
5
|
+
id?: string;
|
|
6
|
+
transaction_id?: string;
|
|
7
|
+
status?: string;
|
|
8
|
+
amount?: string | number;
|
|
9
|
+
paid_amount?: string | number;
|
|
10
|
+
amount_refunded?: string | number;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Clip card readers over the PinPad API.
|
|
14
|
+
*
|
|
15
|
+
* Two things to know before wiring this up, because neither is recoverable in
|
|
16
|
+
* code: the API has **no sandbox** (it runs against production and a physical
|
|
17
|
+
* reader only), and the reader's serial number must be **registered with Clip**
|
|
18
|
+
* beforehand. Until then every charge comes back "unable to connect to pinpad
|
|
19
|
+
* terminal", which reads like a network problem and is not one.
|
|
20
|
+
*
|
|
21
|
+
* Clip never reports an `at_terminal` state — a charge is `PENDING` from the
|
|
22
|
+
* moment it is queued until the customer finishes. Code that keys off
|
|
23
|
+
* `at_terminal` will simply never see it here; key off `pending` instead.
|
|
24
|
+
*/
|
|
25
|
+
export declare class ClipTerminalPayments implements TerminalPaymentsPort {
|
|
26
|
+
private readonly options;
|
|
27
|
+
readonly provider = "clip";
|
|
28
|
+
private readonly baseUrl;
|
|
29
|
+
private readonly apiBaseUrl;
|
|
30
|
+
private readonly fetchImpl;
|
|
31
|
+
private readonly token;
|
|
32
|
+
constructor(options: ClipPinpadOptions);
|
|
33
|
+
private headers;
|
|
34
|
+
private url;
|
|
35
|
+
/**
|
|
36
|
+
* Clip's device status, which is a heartbeat: a reader that has not checked
|
|
37
|
+
* in for 20 seconds turns `expired`, not `inactive`. Both mean "do not send
|
|
38
|
+
* a charge there right now", so both map to offline; `unknown` means the
|
|
39
|
+
* account does not have the feature on, which is not a statement about the
|
|
40
|
+
* device at all and stays `undefined`.
|
|
41
|
+
*/
|
|
42
|
+
listTerminals(): Promise<Terminal[]>;
|
|
43
|
+
charge(input: ChargeInput): Promise<TerminalPayment>;
|
|
44
|
+
get(id: string): Promise<TerminalPayment>;
|
|
45
|
+
/**
|
|
46
|
+
* Withdraws a queued charge — and only a queued one. Clip accepts this
|
|
47
|
+
* "if the payment attempt has not yet been picked up by the terminal"; after
|
|
48
|
+
* that the reader owns it and it has to be cancelled on the device.
|
|
49
|
+
*/
|
|
50
|
+
cancel(id: string): Promise<TerminalPayment>;
|
|
51
|
+
/**
|
|
52
|
+
* The charge plus the transactions behind it, which is where the ids that
|
|
53
|
+
* can be refunded live. Split payments produce more than one.
|
|
54
|
+
*/
|
|
55
|
+
getWithTransactions(id: string): Promise<{
|
|
56
|
+
payment: TerminalPayment;
|
|
57
|
+
transactions: ClipTransaction[];
|
|
58
|
+
}>;
|
|
59
|
+
/**
|
|
60
|
+
* Refunds a settled charge.
|
|
61
|
+
*
|
|
62
|
+
* Two calls, because Clip refunds a **transaction** and the id you hold is a
|
|
63
|
+
* PinPad request: the transaction id has to be read out of the charge's
|
|
64
|
+
* detail first. The refund itself lives on the other host
|
|
65
|
+
* (`api.payclip.com`), with the same Basic credentials.
|
|
66
|
+
*/
|
|
67
|
+
refund(id: string, options?: {
|
|
68
|
+
amountCents?: number;
|
|
69
|
+
reason?: string;
|
|
70
|
+
}): Promise<TerminalPayment>;
|
|
71
|
+
/**
|
|
72
|
+
* Cancels whatever is queued on a reader, when you do not have the request
|
|
73
|
+
* id — a terminal left waiting after a crash, typically. Same limit as
|
|
74
|
+
* {@link cancel}: only before the device picks it up.
|
|
75
|
+
*/
|
|
76
|
+
cancelByTerminal(serialNumber: string): Promise<TerminalPayment>;
|
|
77
|
+
/**
|
|
78
|
+
* Kiosk mode: the reader stays on the payment screen and nobody can walk out
|
|
79
|
+
* of it, for unattended terminals. `timeoutSeconds` auto-cancels an
|
|
80
|
+
* untouched charge; without it a kiosk waits forever.
|
|
81
|
+
*
|
|
82
|
+
* Up to 25 serial numbers per call, which is Clip's limit, not ours.
|
|
83
|
+
*/
|
|
84
|
+
setKioskMode(serialNumbers: string[], preferences: {
|
|
85
|
+
enabled: boolean;
|
|
86
|
+
timeoutSeconds?: number;
|
|
87
|
+
}): Promise<void>;
|
|
88
|
+
/**
|
|
89
|
+
* Clip signs nothing. The notification is `{ id, origin, event_type }` over
|
|
90
|
+
* plain POST, so there is no signature to check and no way to tell Clip's
|
|
91
|
+
* request from anyone else's.
|
|
92
|
+
*
|
|
93
|
+
* What is left is to make the URL itself the credential: register a
|
|
94
|
+
* `webhook_url` carrying a random token and require it back here. That does
|
|
95
|
+
* not authenticate Clip — it only keeps a stranger from making your service
|
|
96
|
+
* do lookups — which is precisely why the event carries an id and never a
|
|
97
|
+
* status. The status comes from `get()`, over an authenticated call, every
|
|
98
|
+
* time.
|
|
99
|
+
*/
|
|
100
|
+
verifyWebhook(request: WebhookRequestLike): TerminalWebhookEvent;
|
|
101
|
+
}
|