@dskripchenko/printable-sdk 1.0.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/LICENSE +21 -0
- package/README.md +82 -0
- package/dist/canonical.d.ts +14 -0
- package/dist/canonical.js +117 -0
- package/dist/client.d.ts +48 -0
- package/dist/client.js +108 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/signer.d.ts +14 -0
- package/dist/signer.js +31 -0
- package/package.json +49 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Denis Skripchenko
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Printable SDK for Node.js
|
|
2
|
+
|
|
3
|
+
Official Node.js client for the Printable document-generation service
|
|
4
|
+
integration API: templates, print-forms, batch rendering, document drafts
|
|
5
|
+
and webhook verification — with HMAC request signing (simple and strict
|
|
6
|
+
canonical modes) built in and byte-compatible with the server implementation.
|
|
7
|
+
|
|
8
|
+
Zero runtime dependencies. Node.js 18+. **Server-side only** — the secret
|
|
9
|
+
key must never reach a browser.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @dskripchenko/printable-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { PrintableClient } from '@dskripchenko/printable-sdk';
|
|
21
|
+
|
|
22
|
+
const client = new PrintableClient({
|
|
23
|
+
baseUrl: 'https://printable.example.com',
|
|
24
|
+
token: 'erp-main-7f3a',
|
|
25
|
+
secretKey: process.env.PRINTABLE_SECRET!,
|
|
26
|
+
salt: process.env.PRINTABLE_SALT!,
|
|
27
|
+
strict: false, // true if the credential has "verify full payload hash" enabled
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// Render a document
|
|
31
|
+
const doc = await client.printFormCreate({
|
|
32
|
+
template: 'invoice',
|
|
33
|
+
variables: { company: { name: 'ACME Ltd' } },
|
|
34
|
+
format: 'link',
|
|
35
|
+
});
|
|
36
|
+
console.log(doc.link);
|
|
37
|
+
|
|
38
|
+
// Batch with archive + email delivery
|
|
39
|
+
const batch = await client.printFormBatch({
|
|
40
|
+
template: 'certificate',
|
|
41
|
+
items: [{ variables: { name: 'Alice' } }, { variables: { name: 'Bob' } }],
|
|
42
|
+
archive: true,
|
|
43
|
+
deliver: { email: 'hr@example.com' },
|
|
44
|
+
});
|
|
45
|
+
const status = await client.printFormBatchGet(batch.uuid as string);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## API surface
|
|
49
|
+
|
|
50
|
+
`templateList` · `templateContract` · `templateExport` · `templateImport` ·
|
|
51
|
+
`printFormCreate` · `printFormGet` · `printFormRules` · `printFormBatch` ·
|
|
52
|
+
`printFormBatchGet` · `documentDraftCreate` · `documentDraftGet` ·
|
|
53
|
+
`call(method, endpoint, params)` (escape hatch).
|
|
54
|
+
|
|
55
|
+
Every method resolves with the decoded `payload` of the response envelope.
|
|
56
|
+
Errors (non-2xx or `success: false`) reject with `PrintableError`
|
|
57
|
+
(`status`, `errorKey`, `payload`).
|
|
58
|
+
|
|
59
|
+
## Webhooks
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
const valid = client.verifyWebhook(
|
|
63
|
+
rawBody, // raw request body string
|
|
64
|
+
req.headers['x-printable-signature'],
|
|
65
|
+
req.headers['x-printable-timestamp'],
|
|
66
|
+
);
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Testing your integration
|
|
70
|
+
|
|
71
|
+
Inject a custom `fetch` to stub HTTP:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
const client = new PrintableClient({
|
|
75
|
+
/* … */
|
|
76
|
+
fetch: async () => new Response('{"success":true,"payload":{"ok":true}}'),
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## License
|
|
81
|
+
|
|
82
|
+
MIT
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PHP-compatible payload canonicalization — byte-identical to the Printable
|
|
3
|
+
* server (`App\Auth\HashSigner::canonicalize`):
|
|
4
|
+
*
|
|
5
|
+
* - recursive key sort for objects (arrays keep their order);
|
|
6
|
+
* - PHP `JSON_NUMERIC_CHECK` semantics: numeric strings become numbers
|
|
7
|
+
* ("42" → 42, "100.0" → 100, "1e3" → 1000, "007" → 7);
|
|
8
|
+
* - empty objects encode as `[]` (PHP array semantics);
|
|
9
|
+
* - objects with sequential "0".."n" keys encode as arrays;
|
|
10
|
+
* - unicode and slashes are not escaped.
|
|
11
|
+
*
|
|
12
|
+
* Known limitation (same as PHP): integers beyond 2^53 lose precision.
|
|
13
|
+
*/
|
|
14
|
+
export declare function canonicalize(payload: Record<string, unknown>): string;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PHP-compatible payload canonicalization — byte-identical to the Printable
|
|
3
|
+
* server (`App\Auth\HashSigner::canonicalize`):
|
|
4
|
+
*
|
|
5
|
+
* - recursive key sort for objects (arrays keep their order);
|
|
6
|
+
* - PHP `JSON_NUMERIC_CHECK` semantics: numeric strings become numbers
|
|
7
|
+
* ("42" → 42, "100.0" → 100, "1e3" → 1000, "007" → 7);
|
|
8
|
+
* - empty objects encode as `[]` (PHP array semantics);
|
|
9
|
+
* - objects with sequential "0".."n" keys encode as arrays;
|
|
10
|
+
* - unicode and slashes are not escaped.
|
|
11
|
+
*
|
|
12
|
+
* Known limitation (same as PHP): integers beyond 2^53 lose precision.
|
|
13
|
+
*/
|
|
14
|
+
/** PHP `is_numeric` for strings (PHP 8: leading/trailing whitespace allowed). */
|
|
15
|
+
const NUMERIC_RE = /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
|
|
16
|
+
function isNumericString(value) {
|
|
17
|
+
return NUMERIC_RE.test(value.trim()) && value.trim() !== '';
|
|
18
|
+
}
|
|
19
|
+
function isSequentialKeys(obj) {
|
|
20
|
+
const keys = Object.keys(obj);
|
|
21
|
+
if (keys.length === 0) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
return keys.every((key, index) => key === String(index));
|
|
25
|
+
}
|
|
26
|
+
function encode(value) {
|
|
27
|
+
if (value === null || value === undefined) {
|
|
28
|
+
return 'null';
|
|
29
|
+
}
|
|
30
|
+
if (typeof value === 'boolean') {
|
|
31
|
+
return value ? 'true' : 'false';
|
|
32
|
+
}
|
|
33
|
+
if (typeof value === 'number') {
|
|
34
|
+
return Number.isFinite(value) ? String(value) : '0';
|
|
35
|
+
}
|
|
36
|
+
if (typeof value === 'string') {
|
|
37
|
+
if (isNumericString(value)) {
|
|
38
|
+
return String(Number(value.trim()));
|
|
39
|
+
}
|
|
40
|
+
return encodeString(value);
|
|
41
|
+
}
|
|
42
|
+
if (Array.isArray(value)) {
|
|
43
|
+
return '[' + value.map(encode).join(',') + ']';
|
|
44
|
+
}
|
|
45
|
+
if (typeof value === 'object') {
|
|
46
|
+
const obj = value;
|
|
47
|
+
const keys = Object.keys(obj);
|
|
48
|
+
// PHP: пустой объект после json_decode(assoc) — пустой array → "[]".
|
|
49
|
+
if (keys.length === 0) {
|
|
50
|
+
return '[]';
|
|
51
|
+
}
|
|
52
|
+
// Объект с ключами "0".."n" PHP считает списком.
|
|
53
|
+
if (isSequentialKeys(obj)) {
|
|
54
|
+
return '[' + keys.map((k) => encode(obj[k])).join(',') + ']';
|
|
55
|
+
}
|
|
56
|
+
const sorted = phpKsort(keys);
|
|
57
|
+
return '{' + sorted.map((k) => encodeString(k) + ':' + encode(obj[k])).join(',') + '}';
|
|
58
|
+
}
|
|
59
|
+
return 'null';
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* PHP ksort (SORT_REGULAR): числовые ключи сравниваются как числа,
|
|
63
|
+
* прочие — как строки; числовые всегда раньше строковых при сравнении
|
|
64
|
+
* числа со строкой числовая семантика PHP8 — для API-payload'ов ключи
|
|
65
|
+
* практически всегда строковые, обычной сортировки достаточно.
|
|
66
|
+
*/
|
|
67
|
+
function phpKsort(keys) {
|
|
68
|
+
return [...keys].sort((a, b) => {
|
|
69
|
+
const an = isNumericString(a);
|
|
70
|
+
const bn = isNumericString(b);
|
|
71
|
+
if (an && bn) {
|
|
72
|
+
return Number(a) - Number(b);
|
|
73
|
+
}
|
|
74
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** JSON string escaping как в PHP с UNESCAPED_UNICODE|UNESCAPED_SLASHES. */
|
|
78
|
+
function encodeString(value) {
|
|
79
|
+
let out = '"';
|
|
80
|
+
for (const ch of value) {
|
|
81
|
+
const code = ch.codePointAt(0);
|
|
82
|
+
switch (ch) {
|
|
83
|
+
case '"':
|
|
84
|
+
out += '\\"';
|
|
85
|
+
break;
|
|
86
|
+
case '\\':
|
|
87
|
+
out += '\\\\';
|
|
88
|
+
break;
|
|
89
|
+
case '\b':
|
|
90
|
+
out += '\\b';
|
|
91
|
+
break;
|
|
92
|
+
case '\f':
|
|
93
|
+
out += '\\f';
|
|
94
|
+
break;
|
|
95
|
+
case '\n':
|
|
96
|
+
out += '\\n';
|
|
97
|
+
break;
|
|
98
|
+
case '\r':
|
|
99
|
+
out += '\\r';
|
|
100
|
+
break;
|
|
101
|
+
case '\t':
|
|
102
|
+
out += '\\t';
|
|
103
|
+
break;
|
|
104
|
+
default:
|
|
105
|
+
if (code < 0x20) {
|
|
106
|
+
out += '\\u' + code.toString(16).padStart(4, '0');
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
out += ch;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return out + '"';
|
|
114
|
+
}
|
|
115
|
+
export function canonicalize(payload) {
|
|
116
|
+
return encode(payload);
|
|
117
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export interface PrintableClientOptions {
|
|
2
|
+
/** Installation origin, e.g. `https://printable.example.com`. */
|
|
3
|
+
baseUrl: string;
|
|
4
|
+
token: string;
|
|
5
|
+
secretKey: string;
|
|
6
|
+
salt: string;
|
|
7
|
+
/** true when the credential requires full-payload HMAC verification. */
|
|
8
|
+
strict?: boolean;
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
/** Custom fetch implementation (testing / instrumentation). */
|
|
11
|
+
fetch?: typeof fetch;
|
|
12
|
+
}
|
|
13
|
+
export declare class PrintableError extends Error {
|
|
14
|
+
readonly status: number;
|
|
15
|
+
readonly errorKey: string | null;
|
|
16
|
+
readonly payload: Record<string, unknown>;
|
|
17
|
+
constructor(message: string, status: number, errorKey?: string | null, payload?: Record<string, unknown>);
|
|
18
|
+
}
|
|
19
|
+
type Payload = Record<string, unknown>;
|
|
20
|
+
/**
|
|
21
|
+
* Client for the Printable integration API (`/api/integration`).
|
|
22
|
+
* Server-side only: the secret key must never reach a browser.
|
|
23
|
+
*/
|
|
24
|
+
export declare class PrintableClient {
|
|
25
|
+
private readonly options;
|
|
26
|
+
private readonly signer;
|
|
27
|
+
private readonly fetchImpl;
|
|
28
|
+
constructor(options: PrintableClientOptions);
|
|
29
|
+
templateList(): Promise<Payload>;
|
|
30
|
+
templateContract(template: string, version?: string): Promise<Payload>;
|
|
31
|
+
templateExport(template: string, version?: string): Promise<Payload>;
|
|
32
|
+
templateImport(packageB64: string, groupId: number, options?: {
|
|
33
|
+
deps?: string;
|
|
34
|
+
on_conflict?: string;
|
|
35
|
+
}): Promise<Payload>;
|
|
36
|
+
printFormCreate(params: Payload): Promise<Payload>;
|
|
37
|
+
printFormGet(uuid: string, format?: 'link' | 'b64'): Promise<Payload>;
|
|
38
|
+
printFormRules(template: string, version?: string): Promise<Payload>;
|
|
39
|
+
printFormBatch(params: Payload): Promise<Payload>;
|
|
40
|
+
printFormBatchGet(uuid: string): Promise<Payload>;
|
|
41
|
+
documentDraftCreate(params: Payload): Promise<Payload>;
|
|
42
|
+
documentDraftGet(uuid: string): Promise<Payload>;
|
|
43
|
+
/** Verify an incoming Printable webhook against its signature headers. */
|
|
44
|
+
verifyWebhook(rawBody: string, signatureHeader: string, timestampHeader: string | number): boolean;
|
|
45
|
+
/** Generic escape hatch: signed call to any `{controller}/{action}`. */
|
|
46
|
+
call(method: 'GET' | 'POST', endpoint: string, params?: Payload): Promise<Payload>;
|
|
47
|
+
}
|
|
48
|
+
export {};
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { Signer } from './signer.js';
|
|
2
|
+
export class PrintableError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
errorKey;
|
|
5
|
+
payload;
|
|
6
|
+
constructor(message, status, errorKey = null, payload = {}) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.errorKey = errorKey;
|
|
10
|
+
this.payload = payload;
|
|
11
|
+
this.name = 'PrintableError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Client for the Printable integration API (`/api/integration`).
|
|
16
|
+
* Server-side only: the secret key must never reach a browser.
|
|
17
|
+
*/
|
|
18
|
+
export class PrintableClient {
|
|
19
|
+
options;
|
|
20
|
+
signer;
|
|
21
|
+
fetchImpl;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.options = options;
|
|
24
|
+
this.signer = new Signer(options.salt);
|
|
25
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
26
|
+
}
|
|
27
|
+
// ── Templates ──────────────────────────────────────────────────────
|
|
28
|
+
templateList() {
|
|
29
|
+
return this.call('GET', 'template/list');
|
|
30
|
+
}
|
|
31
|
+
templateContract(template, version) {
|
|
32
|
+
return this.call('GET', 'template/contract', version ? { template, version } : { template });
|
|
33
|
+
}
|
|
34
|
+
templateExport(template, version) {
|
|
35
|
+
return this.call('GET', 'template/export', version ? { template, version } : { template });
|
|
36
|
+
}
|
|
37
|
+
templateImport(packageB64, groupId, options = {}) {
|
|
38
|
+
return this.call('POST', 'template/import', { ...options, package_b64: packageB64, group_id: groupId });
|
|
39
|
+
}
|
|
40
|
+
// ── Print forms ────────────────────────────────────────────────────
|
|
41
|
+
printFormCreate(params) {
|
|
42
|
+
return this.call('POST', 'print-form/create', params);
|
|
43
|
+
}
|
|
44
|
+
printFormGet(uuid, format = 'link') {
|
|
45
|
+
return this.call('GET', 'print-form/get', { uuid, format });
|
|
46
|
+
}
|
|
47
|
+
printFormRules(template, version) {
|
|
48
|
+
return this.call('GET', 'print-form/rules', version ? { template, version } : { template });
|
|
49
|
+
}
|
|
50
|
+
printFormBatch(params) {
|
|
51
|
+
return this.call('POST', 'print-form/batch', params);
|
|
52
|
+
}
|
|
53
|
+
printFormBatchGet(uuid) {
|
|
54
|
+
return this.call('GET', 'print-form/batch-get', { uuid });
|
|
55
|
+
}
|
|
56
|
+
// ── Document drafts ────────────────────────────────────────────────
|
|
57
|
+
documentDraftCreate(params) {
|
|
58
|
+
return this.call('POST', 'document-draft/create', params);
|
|
59
|
+
}
|
|
60
|
+
documentDraftGet(uuid) {
|
|
61
|
+
return this.call('GET', 'document-draft/get', { uuid });
|
|
62
|
+
}
|
|
63
|
+
// ── Webhooks ───────────────────────────────────────────────────────
|
|
64
|
+
/** Verify an incoming Printable webhook against its signature headers. */
|
|
65
|
+
verifyWebhook(rawBody, signatureHeader, timestampHeader) {
|
|
66
|
+
const signature = signatureHeader.startsWith('sha256=') ? signatureHeader.slice(7) : signatureHeader;
|
|
67
|
+
return this.signer.verifyWebhook(signature, Number(timestampHeader), rawBody, this.options.secretKey);
|
|
68
|
+
}
|
|
69
|
+
// ── Core ───────────────────────────────────────────────────────────
|
|
70
|
+
/** Generic escape hatch: signed call to any `{controller}/{action}`. */
|
|
71
|
+
async call(method, endpoint, params = {}) {
|
|
72
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
73
|
+
const payload = { ...params, timestamp };
|
|
74
|
+
const hash = this.options.strict
|
|
75
|
+
? this.signer.signPayload(payload, this.options.secretKey)
|
|
76
|
+
: this.signer.signToken(this.options.token, timestamp, this.options.secretKey);
|
|
77
|
+
const body = { ...payload, token: this.options.token, hash };
|
|
78
|
+
let url = this.options.baseUrl.replace(/\/+$/, '') + '/api/integration/' + endpoint.replace(/^\/+/, '');
|
|
79
|
+
const init = {
|
|
80
|
+
method,
|
|
81
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
82
|
+
signal: AbortSignal.timeout(this.options.timeoutMs ?? 30_000),
|
|
83
|
+
};
|
|
84
|
+
if (method === 'GET') {
|
|
85
|
+
const query = new URLSearchParams();
|
|
86
|
+
for (const [key, value] of Object.entries(body)) {
|
|
87
|
+
query.set(key, String(value));
|
|
88
|
+
}
|
|
89
|
+
url += '?' + query.toString();
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
init.body = JSON.stringify(body);
|
|
93
|
+
}
|
|
94
|
+
const response = await this.fetchImpl(url, init);
|
|
95
|
+
let decoded;
|
|
96
|
+
try {
|
|
97
|
+
decoded = (await response.json());
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
throw new PrintableError(`Printable API returned a non-JSON response (HTTP ${response.status})`, response.status);
|
|
101
|
+
}
|
|
102
|
+
const payloadOut = decoded.payload ?? {};
|
|
103
|
+
if (response.status >= 400 || decoded.success !== true) {
|
|
104
|
+
throw new PrintableError(typeof payloadOut.message === 'string' ? payloadOut.message : `Printable API error (HTTP ${response.status})`, response.status, typeof payloadOut.errorKey === 'string' ? payloadOut.errorKey : null, payloadOut);
|
|
105
|
+
}
|
|
106
|
+
return payloadOut;
|
|
107
|
+
}
|
|
108
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/signer.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request/webhook signing, byte-compatible with the Printable server
|
|
3
|
+
* (`App\Auth\HashSigner`).
|
|
4
|
+
*/
|
|
5
|
+
export declare class Signer {
|
|
6
|
+
private readonly salt;
|
|
7
|
+
constructor(salt: string);
|
|
8
|
+
/** simple mode: sha256(token + timestamp + salt + secret). */
|
|
9
|
+
signToken(token: string, timestamp: number, secretKey: string): string;
|
|
10
|
+
/** strict mode: HMAC-SHA256(canonical(payload), secret + salt). */
|
|
11
|
+
signPayload(payload: Record<string, unknown>, secretKey: string): string;
|
|
12
|
+
/** Verify an incoming webhook signature (value without the "sha256=" prefix). */
|
|
13
|
+
verifyWebhook(signature: string, timestamp: number, rawBody: string, secretKey: string): boolean;
|
|
14
|
+
}
|
package/dist/signer.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { canonicalize } from './canonical.js';
|
|
3
|
+
/**
|
|
4
|
+
* Request/webhook signing, byte-compatible with the Printable server
|
|
5
|
+
* (`App\Auth\HashSigner`).
|
|
6
|
+
*/
|
|
7
|
+
export class Signer {
|
|
8
|
+
salt;
|
|
9
|
+
constructor(salt) {
|
|
10
|
+
this.salt = salt;
|
|
11
|
+
if (salt === '') {
|
|
12
|
+
throw new Error('Printable salt must not be empty.');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** simple mode: sha256(token + timestamp + salt + secret). */
|
|
16
|
+
signToken(token, timestamp, secretKey) {
|
|
17
|
+
return createHash('sha256').update(`${token}${timestamp}${this.salt}${secretKey}`).digest('hex');
|
|
18
|
+
}
|
|
19
|
+
/** strict mode: HMAC-SHA256(canonical(payload), secret + salt). */
|
|
20
|
+
signPayload(payload, secretKey) {
|
|
21
|
+
return createHmac('sha256', secretKey + this.salt).update(canonicalize(payload)).digest('hex');
|
|
22
|
+
}
|
|
23
|
+
/** Verify an incoming webhook signature (value without the "sha256=" prefix). */
|
|
24
|
+
verifyWebhook(signature, timestamp, rawBody, secretKey) {
|
|
25
|
+
const expected = createHmac('sha256', secretKey).update(`${timestamp}.${rawBody}`).digest('hex');
|
|
26
|
+
if (signature.length !== expected.length) {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
|
|
30
|
+
}
|
|
31
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dskripchenko/printable-sdk",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Official Node.js SDK for the Printable document-generation service: HMAC-signed integration API client (templates, print-forms, batches, drafts, webhooks).",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"printable",
|
|
7
|
+
"sdk",
|
|
8
|
+
"api-client",
|
|
9
|
+
"pdf",
|
|
10
|
+
"docx",
|
|
11
|
+
"document-generation",
|
|
12
|
+
"hmac"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/dskripchenko/printable-sdk-js",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/dskripchenko/printable-sdk-js.git"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"author": "Denis Skripchenko (https://github.com/dskripchenko)",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=18"
|
|
24
|
+
},
|
|
25
|
+
"main": "./dist/index.js",
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"import": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsc -p tsconfig.build.json",
|
|
38
|
+
"test": "vitest run",
|
|
39
|
+
"prepublishOnly": "npm run build && npm test"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/node": "^22.0.0",
|
|
43
|
+
"typescript": "^5.6.0",
|
|
44
|
+
"vitest": "^4.0.0"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
}
|
|
49
|
+
}
|