@signsealer/sdk 1.19.0 → 1.22.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/CHANGELOG.md +68 -0
- package/README.md +231 -0
- package/dist/cjs/index.cjs +311 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.d.ts +219 -0
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +306 -0
- package/dist/esm/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,73 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.22.0
|
|
4
|
+
|
|
5
|
+
Nothing that worked before changes.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `blank` on a template question (`Ask`, 00699): the answer fills the blank
|
|
10
|
+
of the same name in a written template's text, `{{plate}}` for `plate`.
|
|
11
|
+
A send may leave that blank out of `values`; the first signer answers it,
|
|
12
|
+
and their signature writes it into the text before it is fingerprinted.
|
|
13
|
+
- `recipient` on `Ask` (00685): the one signer a question is for, by their
|
|
14
|
+
`sign_order`. The engine already kept it; `POST /v1/templates` now does too.
|
|
15
|
+
|
|
16
|
+
## 1.21.0
|
|
17
|
+
|
|
18
|
+
Nothing that worked before changes.
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
|
|
22
|
+
- A partner's platform may text its businesses' signers itself (00692).
|
|
23
|
+
The partner decides on its dashboard: SignSealer texts them (as before,
|
|
24
|
+
and every partner's starting point), the partner does, or each business
|
|
25
|
+
chooses. For documents sent through the partner's app with a business's
|
|
26
|
+
access token, when the answer is the partner or nobody, SignSealer sends
|
|
27
|
+
no texts: no link, no reminder, no confirmation. Email and webhooks are
|
|
28
|
+
unchanged, and a one-time code a signer asks for is still sent.
|
|
29
|
+
- `setTextingSender(sender, clientId?)`: `PUT /v1/texting/sender`, the
|
|
30
|
+
business's choice where the partner leaves it to each business. With
|
|
31
|
+
the partner's own access token, `clientId` is left out. Type
|
|
32
|
+
`TextingSenderChoice`.
|
|
33
|
+
- `texting.sender` on `account()`: who texts the signers of what this key
|
|
34
|
+
sends. Type `TextingSender`.
|
|
35
|
+
- A partner client made from the partner form may now ask a business for
|
|
36
|
+
`signing:workflows` and `signing:webhooks` as well as `signing:read` and
|
|
37
|
+
`signing:write`.
|
|
38
|
+
|
|
39
|
+
## 1.20.0
|
|
40
|
+
|
|
41
|
+
Nothing that worked before changes.
|
|
42
|
+
|
|
43
|
+
### Added
|
|
44
|
+
|
|
45
|
+
- "Connect with SignSealer" for a partner's server (00090, 00207):
|
|
46
|
+
`SignSealerOAuth`, made with your OAuth client's `clientId` and
|
|
47
|
+
`clientSecret`.
|
|
48
|
+
- `createPkce()` makes a verifier and its S256 challenge, and
|
|
49
|
+
`pkceChallenge()` works out the challenge for a verifier, in WebCrypto
|
|
50
|
+
(Node 18 through `node:crypto`, every edge runtime).
|
|
51
|
+
- `authorizeUrl({ redirectUri, scopes, state, codeChallenge })` is where to
|
|
52
|
+
send the business's browser; `callback(query, state)` reads the answer,
|
|
53
|
+
checks `state` and gives the code.
|
|
54
|
+
- `exchangeCode({ code, redirectUri, codeVerifier })` and
|
|
55
|
+
`refresh(refreshToken)` post to `/oauth/token` as a form, the client by
|
|
56
|
+
HTTP Basic. The answer is the endpoint's, with `expires_at` (absolute)
|
|
57
|
+
and `scopes` (what the business actually gave) added. The access token
|
|
58
|
+
is an API key: `new SignSealer({ apiKey: tokens.access_token })`.
|
|
59
|
+
- **Neither is ever sent twice.** A refresh token or a code presented
|
|
60
|
+
again is treated as stolen and ends the connection, so these two calls
|
|
61
|
+
do not retry the way every other call in this package does. Serialise
|
|
62
|
+
refreshes per grant, and store the new refresh token before using the
|
|
63
|
+
access token.
|
|
64
|
+
- `SignSealerOAuthError`, a `SignSealerError` whose `error` and
|
|
65
|
+
`errorDescription` are RFC 6749's. `reconnect` is true for
|
|
66
|
+
`invalid_grant` (send the business through `authorizeUrl` again);
|
|
67
|
+
`transient` for the network, a `429` or a `5xx`, after which a
|
|
68
|
+
refresh token's state is unknown. `retryable` is always false.
|
|
69
|
+
- Types `OAuthOptions`, `OAuthScope`, `OAuthTokens` and `Pkce`.
|
|
70
|
+
|
|
3
71
|
## 1.19.0
|
|
4
72
|
|
|
5
73
|
Nothing that worked before changes.
|
package/README.md
CHANGED
|
@@ -573,6 +573,237 @@ changed since it was issued. That is reported and never corrected — a
|
|
|
573
573
|
verification service that quietly re-derived could not answer the one question
|
|
574
574
|
it exists for.
|
|
575
575
|
|
|
576
|
+
## Connecting a business with one click (OAuth)
|
|
577
|
+
|
|
578
|
+
When your product acts for *other* businesses' SignSealer accounts, they
|
|
579
|
+
connect it on SignSealer's consent screen rather than pasting you a key
|
|
580
|
+
(1.20.0). `SignSealerOAuth` is the partner's half: authorization code with
|
|
581
|
+
PKCE (S256, which SignSealer requires of every client), on your server,
|
|
582
|
+
with your OAuth client's id and secret. What comes back is an API key for
|
|
583
|
+
that one business, limited to what it agreed to.
|
|
584
|
+
|
|
585
|
+
**Send the business to SignSealer.** Make a PKCE pair and a `state` for each
|
|
586
|
+
attempt, keep both on your server, and redirect:
|
|
587
|
+
|
|
588
|
+
```ts
|
|
589
|
+
import { SignSealerOAuth, createPkce } from "@signsealer/sdk";
|
|
590
|
+
|
|
591
|
+
const oauth = new SignSealerOAuth({
|
|
592
|
+
clientId: process.env.SIGNSEALER_CLIENT_ID!, // ss_client_…
|
|
593
|
+
clientSecret: process.env.SIGNSEALER_CLIENT_SECRET!, // ss_secret_…, server only
|
|
594
|
+
});
|
|
595
|
+
const REDIRECT = "https://pos.example.com/oauth/signsealer"; // exactly as registered
|
|
596
|
+
|
|
597
|
+
app.get("/connect/signsealer", async (req, res) => {
|
|
598
|
+
const { verifier, challenge } = await createPkce();
|
|
599
|
+
const state = crypto.randomUUID();
|
|
600
|
+
await attempts.put(state, { verifier, tenantId: req.user.tenantId }, { ttlSeconds: 1800 });
|
|
601
|
+
res.redirect(oauth.authorizeUrl({
|
|
602
|
+
redirectUri: REDIRECT,
|
|
603
|
+
scopes: ["signing:read", "signing:write", "signing:workflows", "signing:webhooks"],
|
|
604
|
+
state,
|
|
605
|
+
codeChallenge: challenge,
|
|
606
|
+
}));
|
|
607
|
+
});
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
Keep the attempt for half an hour, not a minute: a business with no
|
|
611
|
+
SignSealer account can make one on the way, name its business and agree to
|
|
612
|
+
the terms, and SignSealer brings it back to the consent screen afterwards.
|
|
613
|
+
|
|
614
|
+
**The callback.** `callback` checks the `state` and gives you the code, or
|
|
615
|
+
throws the consent screen's error (`access_denied` when they pressed Not now).
|
|
616
|
+
Exchange the code at once: it lives sixty seconds and is good once.
|
|
617
|
+
|
|
618
|
+
```ts
|
|
619
|
+
import { SignSealer, SignSealerOAuthError } from "@signsealer/sdk";
|
|
620
|
+
|
|
621
|
+
app.get("/oauth/signsealer", async (req, res) => {
|
|
622
|
+
const attempt = await attempts.take(String(req.query.state ?? "")); // read once, then deleted
|
|
623
|
+
if (!attempt) return res.status(400).send("That connection has expired. Start again.");
|
|
624
|
+
try {
|
|
625
|
+
const { code } = oauth.callback(req.url, req.query.state as string);
|
|
626
|
+
const tokens = await oauth.exchangeCode({ code, redirectUri: REDIRECT, codeVerifier: attempt.verifier });
|
|
627
|
+
const account = await new SignSealer({ apiKey: tokens.access_token }).account();
|
|
628
|
+
await db.signsealer.upsert({
|
|
629
|
+
tenantId: attempt.tenantId,
|
|
630
|
+
businessId: account.tenant_id,
|
|
631
|
+
accessToken: seal(tokens.access_token), // encrypted at rest, never logged
|
|
632
|
+
refreshToken: seal(tokens.refresh_token!),
|
|
633
|
+
expiresAt: tokens.expires_at,
|
|
634
|
+
scopes: tokens.scopes, // what they gave, which can be less than you asked
|
|
635
|
+
needsReconnect: false,
|
|
636
|
+
});
|
|
637
|
+
res.redirect("/settings/signing?connected=1");
|
|
638
|
+
} catch (e) {
|
|
639
|
+
if (e instanceof SignSealerOAuthError) return res.redirect(`/settings/signing?error=${e.error}`);
|
|
640
|
+
throw e;
|
|
641
|
+
}
|
|
642
|
+
});
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
`tokens.scopes` is what the business actually granted. A grant never holds
|
|
646
|
+
more than the person who made it may do themselves, so check it before
|
|
647
|
+
offering a feature that needs a scope you asked for.
|
|
648
|
+
|
|
649
|
+
**Refresh, one at a time.** An access token lives an hour; refresh it a
|
|
650
|
+
little before `expires_at`. **The SDK never retries a refresh, and neither
|
|
651
|
+
should you.** Each refresh token is good once: the answer carries the next
|
|
652
|
+
one, and presenting a spent one revokes the whole connection, every token
|
|
653
|
+
under it, and the business has to connect again. So serialise refreshes per
|
|
654
|
+
business, and store the new refresh token before using the new access token,
|
|
655
|
+
inside the same lock:
|
|
656
|
+
|
|
657
|
+
```ts
|
|
658
|
+
async function clientFor(tenantId: string): Promise<SignSealer> {
|
|
659
|
+
return db.transaction(async (tx) => {
|
|
660
|
+
const row = await tx.signsealer.forUpdate(tenantId); // the lock: one refresh per grant
|
|
661
|
+
if (row.needsReconnect) throw new NeedsReconnect(tenantId);
|
|
662
|
+
if (Date.parse(row.expiresAt) - Date.now() > 5 * 60_000) {
|
|
663
|
+
return new SignSealer({ apiKey: unseal(row.accessToken) });
|
|
664
|
+
}
|
|
665
|
+
try {
|
|
666
|
+
const t = await oauth.refresh(unseal(row.refreshToken));
|
|
667
|
+
await tx.signsealer.update(tenantId, { // stored before it is used
|
|
668
|
+
accessToken: seal(t.access_token), refreshToken: seal(t.refresh_token!),
|
|
669
|
+
expiresAt: t.expires_at, scopes: t.scopes,
|
|
670
|
+
});
|
|
671
|
+
return new SignSealer({ apiKey: t.access_token });
|
|
672
|
+
} catch (e) {
|
|
673
|
+
if (e instanceof SignSealerOAuthError && e.reconnect) {
|
|
674
|
+
await tx.signsealer.update(tenantId, { needsReconnect: true });
|
|
675
|
+
throw new NeedsReconnect(tenantId);
|
|
676
|
+
}
|
|
677
|
+
throw e; // e.transient: see below. Never a loop.
|
|
678
|
+
}
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
`SignSealerOAuthError` carries RFC 6749's `error` and `errorDescription`, and
|
|
684
|
+
two flags that decide what happens next:
|
|
685
|
+
|
|
686
|
+
- **`reconnect`**: `invalid_grant`. The business disconnected you, the person
|
|
687
|
+
who connected you left or can no longer give what you hold, or a token was
|
|
688
|
+
used twice. Ask the business to connect again.
|
|
689
|
+
- **`transient`**: the network, a `429` or a `5xx`. The connection may well
|
|
690
|
+
be fine, but **whether the refresh token was spent is unknown**: if the
|
|
691
|
+
request arrived and the answer was lost, it is spent and its successor went
|
|
692
|
+
with the answer. Sending it once more, later and under the same lock,
|
|
693
|
+
either works or ends the connection, which losing the successor had
|
|
694
|
+
already made certain. That is a decision for your code to make knowingly,
|
|
695
|
+
not a retry loop.
|
|
696
|
+
|
|
697
|
+
`invalid_client` is neither: your client id or secret was refused, which is
|
|
698
|
+
your configuration and affects every business at once. `retryable` is
|
|
699
|
+
`false` on every OAuth error.
|
|
700
|
+
|
|
701
|
+
**A `401` from the API means reconnect.** A business can end the connection at
|
|
702
|
+
any moment, and its tokens stop working that minute, not at the end of the
|
|
703
|
+
hour. Refreshing ahead of `expires_at` means an unexpired token answered `401`
|
|
704
|
+
has been revoked:
|
|
705
|
+
|
|
706
|
+
```ts
|
|
707
|
+
try {
|
|
708
|
+
await (await clientFor(tenantId)).send(documentId, signers);
|
|
709
|
+
} catch (e) {
|
|
710
|
+
if (e instanceof SignSealerError && e.status === 401) {
|
|
711
|
+
await db.signsealer.update(tenantId, { needsReconnect: true }); // show "Reconnect SignSealer"
|
|
712
|
+
} else throw e;
|
|
713
|
+
}
|
|
714
|
+
```
|
|
715
|
+
|
|
716
|
+
The [OAuth reference](https://signsealer.com/docs/authentication) has the
|
|
717
|
+
endpoints themselves.
|
|
718
|
+
|
|
719
|
+
## Onboarding a business
|
|
720
|
+
|
|
721
|
+
What to ask for, and what a business needs in place before signing works
|
|
722
|
+
inside your product.
|
|
723
|
+
|
|
724
|
+
**Scopes.** Ask for the fewest that do the job; a consent screen that asks
|
|
725
|
+
for everything is one people decline. For e-signing and waivers:
|
|
726
|
+
|
|
727
|
+
| Scope | Why you need it |
|
|
728
|
+
| --- | --- |
|
|
729
|
+
| `signing:read` | `account()` (including `frame_origins`), documents, signers, PDFs and certificates, the list of workflows |
|
|
730
|
+
| `signing:write` | prepare and `send()` documents, `embedLink()`, remind, void. If your client was registered with its parts, `signing:send` and `signing:links` are the minimum |
|
|
731
|
+
| `signing:workflows` | `startWorkflow()`: a waiver from one of the business's forms |
|
|
732
|
+
| `signing:webhooks` | `ensureWebhook()` on the business, to hear `signing.completed` rather than poll |
|
|
733
|
+
|
|
734
|
+
Add `signing:subjects` only if you sync reservations and their packets
|
|
735
|
+
(`upsertReservation`, `startPacket`), and `signing:templates` only if you
|
|
736
|
+
make templates or use `documentFromPdf()`. Your client can ask only for the
|
|
737
|
+
scopes SignSealer registered it with, and anything else comes back as
|
|
738
|
+
`error=invalid_scope`. A client made from the partner form is registered with
|
|
739
|
+
`signing:read`, `signing:write`, `signing:workflows` and `signing:webhooks`
|
|
740
|
+
(1.21.0); write to partners@signsealer.com for the others. The person pressing Connect must be able to manage API keys on that
|
|
741
|
+
business (an owner or admin, unless given it), and a scope they could not
|
|
742
|
+
use themselves is left out of the grant.
|
|
743
|
+
|
|
744
|
+
**Where the signing page can be framed.** An embedded signing page
|
|
745
|
+
(`delivery: "embedded"`, then `embedLink()`) shows only inside a site the
|
|
746
|
+
business has proven is its own; anywhere else the browser leaves the frame
|
|
747
|
+
empty. `frame_origins` on `account()` and on each `embedLink()` lists them:
|
|
748
|
+
|
|
749
|
+
```ts
|
|
750
|
+
const { frame_origins } = await client.account();
|
|
751
|
+
// ["https://pos.example.com", "https://dockside.example", "https://*.dockside.example"]
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
There are three ways onto that list:
|
|
755
|
+
|
|
756
|
+
- **Your app, once connected.** The host of each of your redirect addresses
|
|
757
|
+
is added for every business that connects you, exactly that host and no
|
|
758
|
+
other. Register a redirect on the host your product frames the page on and
|
|
759
|
+
embedded signing there works with nothing for the business to do.
|
|
760
|
+
- **A company sign-in domain** the business proves in the dashboard under
|
|
761
|
+
[Settings → Single sign-on](https://app.signsealer.com/settings/sso): that
|
|
762
|
+
domain and every host under it, which is how a page on its own main site
|
|
763
|
+
qualifies.
|
|
764
|
+
- **A signing domain** it verifies under
|
|
765
|
+
[Settings → Your own domains](https://app.signsealer.com/settings#domains)
|
|
766
|
+
(with white label): that host and the hosts under it.
|
|
767
|
+
|
|
768
|
+
Check `frame_origins` before showing a frame, and open the link in a new tab
|
|
769
|
+
when the page's site is not on it. The owner-facing steps are in the help
|
|
770
|
+
pages, not here: [Signing inside your product](https://signsealer.com/docs/embedding),
|
|
771
|
+
[Branding and your own domains](https://signsealer.com/docs/branding), and
|
|
772
|
+
[Teams, roles and sign-in](https://signsealer.com/docs/teams) for who may
|
|
773
|
+
connect an app and where a business sees and ends it (Integrations →
|
|
774
|
+
Connected apps).
|
|
775
|
+
|
|
776
|
+
**Who texts the signers.** SignSealer texts a signer the link and one
|
|
777
|
+
reminder where it holds their consent. Your platform may do that instead
|
|
778
|
+
(1.21.0): on your partner dashboard choose SignSealer, your platform, or each
|
|
779
|
+
business. For documents sent with a business's access token, when the answer
|
|
780
|
+
is your platform or nobody, SignSealer sends those signers no texts at all,
|
|
781
|
+
reminders included; email goes as before, and the webhooks are how you hear
|
|
782
|
+
what to text. A one-time code a signer asks for is always sent by SignSealer.
|
|
783
|
+
|
|
784
|
+
```ts
|
|
785
|
+
const { texting } = await client.account();
|
|
786
|
+
texting?.sender; // "partner": text the links yourself; "signsealer": we do; "none": nobody does
|
|
787
|
+
|
|
788
|
+
// Where your dashboard leaves it to each business, record its answer with its token:
|
|
789
|
+
await client.setTextingSender("partner");
|
|
790
|
+
```
|
|
791
|
+
|
|
792
|
+
When `texting.sender` is `partner`, the business needs no texting number of
|
|
793
|
+
its own for these documents, so do not show it `textingNumberInvitation`.
|
|
794
|
+
|
|
795
|
+
**A business with no account yet.** It can make one from the consent screen
|
|
796
|
+
itself, as above, and the emailed link brings it back to your consent screen
|
|
797
|
+
even when it is opened on another device. To send one to SignSealer first, with the business counted
|
|
798
|
+
as yours, use your signup link:
|
|
799
|
+
|
|
800
|
+
```ts
|
|
801
|
+
import { SignSealerPartner } from "@signsealer/sdk";
|
|
802
|
+
|
|
803
|
+
SignSealerPartner.signupUrl("deckpos");
|
|
804
|
+
// "https://app.signsealer.com/signup?partner=deckpos"
|
|
805
|
+
```
|
|
806
|
+
|
|
576
807
|
## For partners: what you have earned
|
|
577
808
|
|
|
578
809
|
A platform SignSealer has enrolled as a partner shares in the revenue of every
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -49,7 +49,9 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
49
49
|
};
|
|
50
50
|
})();
|
|
51
51
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
52
|
-
exports.WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_SIGNATURE_HEADER = exports.WEBHOOK_TIMESTAMP_HEADER = exports.WEBHOOK_EVENT_HEADER = exports.SignSealerPartner = exports.SignSealerSigning = exports.SignSealer = exports.SignSealerError = void 0;
|
|
52
|
+
exports.WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_SIGNATURE_HEADER = exports.WEBHOOK_TIMESTAMP_HEADER = exports.WEBHOOK_EVENT_HEADER = exports.SignSealerOAuth = exports.SignSealerOAuthError = exports.SignSealerPartner = exports.SignSealerSigning = exports.SignSealer = exports.SignSealerError = void 0;
|
|
53
|
+
exports.createPkce = createPkce;
|
|
54
|
+
exports.pkceChallenge = pkceChallenge;
|
|
53
55
|
exports.verifyWebhook = verifyWebhook;
|
|
54
56
|
exports.verifyWebhookRequest = verifyWebhookRequest;
|
|
55
57
|
exports.sha256Hex = sha256Hex;
|
|
@@ -297,6 +299,21 @@ class SignSealer {
|
|
|
297
299
|
textingNumberInvitation(prefill = {}) {
|
|
298
300
|
return this.#call("POST", "/v1/texting/number/invitations", { prefill }, undefined, { once: true });
|
|
299
301
|
}
|
|
302
|
+
/**
|
|
303
|
+
* Who texts the signers of documents sent through a partner's app, for a
|
|
304
|
+
* partner whose dashboard leaves it to each business (1.21.0).
|
|
305
|
+
*
|
|
306
|
+
* As the partner, with the business's access token, leave `clientId` out:
|
|
307
|
+
* the choice is yours for that business. With the business's own key, name
|
|
308
|
+
* the app by its `ss_client_…` id (the key needs `signing:webhooks`). With
|
|
309
|
+
* `partner` or `none`, SignSealer sends no texts for those documents -- no
|
|
310
|
+
* link, no reminder, no confirmation -- while email and webhooks go on as
|
|
311
|
+
* before; a one-time code a signer asks for is still sent. A PUT, so a
|
|
312
|
+
* retry after a lost answer sets the same thing again.
|
|
313
|
+
*/
|
|
314
|
+
setTextingSender(sender, clientId) {
|
|
315
|
+
return this.#call("PUT", "/v1/texting/sender", clientId ? { sender, client_id: clientId } : { sender });
|
|
316
|
+
}
|
|
300
317
|
/* ----------------------------------------------------------- documents */
|
|
301
318
|
/**
|
|
302
319
|
* Documents, filtered and paged.
|
|
@@ -1230,6 +1247,299 @@ function safeJson(text) {
|
|
|
1230
1247
|
return {};
|
|
1231
1248
|
}
|
|
1232
1249
|
}
|
|
1250
|
+
/**
|
|
1251
|
+
* A refusal from the OAuth endpoints, or from the consent screen's answer.
|
|
1252
|
+
*
|
|
1253
|
+
* `code` is RFC 6749's `error` and `message` its `error_description` (both
|
|
1254
|
+
* also under their RFC names). Two questions decide what to do:
|
|
1255
|
+
*
|
|
1256
|
+
* - `reconnect`: the grant is over, or the code is spent. `invalid_grant`
|
|
1257
|
+
* -- the business disconnected you, the person who connected you can no
|
|
1258
|
+
* longer give what you hold, a token or code was used twice, or it
|
|
1259
|
+
* expired. Send the business through `authorizeUrl` again; nothing else
|
|
1260
|
+
* will bring it back.
|
|
1261
|
+
* - `transient`: the network or SignSealer, not your request. The grant may
|
|
1262
|
+
* well still be good. On a refresh, **whether the token was spent is
|
|
1263
|
+
* unknown**: read `refresh()` before deciding to send it again.
|
|
1264
|
+
*
|
|
1265
|
+
* `invalid_client` is neither: your client id or secret did not
|
|
1266
|
+
* authenticate, which is your configuration, for every business at once.
|
|
1267
|
+
*
|
|
1268
|
+
* `retryable` is always false. SignSealerError's "worth trying again
|
|
1269
|
+
* unchanged" is exactly the advice that turns a lost answer into a revoked
|
|
1270
|
+
* grant here.
|
|
1271
|
+
*/
|
|
1272
|
+
class SignSealerOAuthError extends SignSealerError {
|
|
1273
|
+
constructor(status, code, message, requestId, retryAfter) {
|
|
1274
|
+
super(status, code, message, undefined, requestId, retryAfter);
|
|
1275
|
+
this.name = "SignSealerOAuthError";
|
|
1276
|
+
}
|
|
1277
|
+
/** RFC 6749's name for `code`. */
|
|
1278
|
+
get error() {
|
|
1279
|
+
return this.code;
|
|
1280
|
+
}
|
|
1281
|
+
/** RFC 6749's name for `message`. */
|
|
1282
|
+
get errorDescription() {
|
|
1283
|
+
return this.message;
|
|
1284
|
+
}
|
|
1285
|
+
get retryable() {
|
|
1286
|
+
return false;
|
|
1287
|
+
}
|
|
1288
|
+
/** The grant is over or the code spent: send the business to connect again. */
|
|
1289
|
+
get reconnect() {
|
|
1290
|
+
return this.code === "invalid_grant";
|
|
1291
|
+
}
|
|
1292
|
+
/** The network or SignSealer failed, not the request. On a refresh, the token may or may not have been spent. */
|
|
1293
|
+
get transient() {
|
|
1294
|
+
return this.status === 0 || this.status === 429 || this.status >= 500;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
exports.SignSealerOAuthError = SignSealerOAuthError;
|
|
1298
|
+
/** The characters RFC 7636 allows in a verifier, 43 to 128 of them. */
|
|
1299
|
+
const VERIFIER = /^[A-Za-z0-9\-._~]{43,128}$/;
|
|
1300
|
+
/**
|
|
1301
|
+
* Random bytes from wherever this runtime keeps them: the global WebCrypto,
|
|
1302
|
+
* then `node:crypto` for Node 18, assembled at run time for the reason
|
|
1303
|
+
* `webCrypto()` gives.
|
|
1304
|
+
*/
|
|
1305
|
+
let randomPromise = null;
|
|
1306
|
+
async function randomBytes(n) {
|
|
1307
|
+
randomPromise ??= (async () => {
|
|
1308
|
+
const here = globalThis.crypto;
|
|
1309
|
+
if (typeof here?.getRandomValues === "function")
|
|
1310
|
+
return (k) => here.getRandomValues(new Uint8Array(k));
|
|
1311
|
+
try {
|
|
1312
|
+
const mod = await Promise.resolve(`${"node:" + "crypto"}`).then(s => __importStar(require(s)));
|
|
1313
|
+
const web = mod.webcrypto;
|
|
1314
|
+
if (typeof web?.getRandomValues === "function")
|
|
1315
|
+
return (k) => web.getRandomValues(new Uint8Array(k));
|
|
1316
|
+
}
|
|
1317
|
+
catch {
|
|
1318
|
+
/* Not Node. The error below is the honest answer. */
|
|
1319
|
+
}
|
|
1320
|
+
throw new Error("no crypto.getRandomValues in this runtime, so a PKCE verifier cannot be made"
|
|
1321
|
+
+ " — every current browser, edge runtime and Node 19 or later has it,"
|
|
1322
|
+
+ " and Node 18 reaches it through node:crypto");
|
|
1323
|
+
})();
|
|
1324
|
+
return (await randomPromise)(n);
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* A fresh PKCE pair, one per authorise request: 32 random bytes as a
|
|
1328
|
+
* 43-character verifier, and its S256 challenge.
|
|
1329
|
+
*
|
|
1330
|
+
* Keep the verifier on your server, against the `state` you send (a
|
|
1331
|
+
* session, or a short-lived row), and give it to `exchangeCode`. Never put
|
|
1332
|
+
* it in the authorise address: the challenge goes there, and the verifier
|
|
1333
|
+
* is what proves the code came back to the same party that asked.
|
|
1334
|
+
*/
|
|
1335
|
+
async function createPkce() {
|
|
1336
|
+
const verifier = base64url(await randomBytes(32));
|
|
1337
|
+
return { verifier, challenge: await pkceChallenge(verifier), method: "S256" };
|
|
1338
|
+
}
|
|
1339
|
+
/** The S256 challenge for a verifier: base64url of its SHA-256, without padding (RFC 7636, section 4.2). */
|
|
1340
|
+
async function pkceChallenge(verifier) {
|
|
1341
|
+
if (!VERIFIER.test(verifier)) {
|
|
1342
|
+
throw new Error("a PKCE verifier is 43 to 128 of A-Z, a-z, 0-9 and - . _ ~");
|
|
1343
|
+
}
|
|
1344
|
+
const digest = await (await webCrypto()).digest("SHA-256", new TextEncoder().encode(verifier));
|
|
1345
|
+
return base64url(new Uint8Array(digest));
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* "Connect with SignSealer", for a partner's server (1.20.0).
|
|
1349
|
+
*
|
|
1350
|
+
* ```ts
|
|
1351
|
+
* const oauth = new SignSealerOAuth({ clientId, clientSecret });
|
|
1352
|
+
* const { verifier, challenge } = await createPkce();
|
|
1353
|
+
* redirect(oauth.authorizeUrl({ redirectUri, scopes: ["signing:read", "signing:write"], state, codeChallenge: challenge }));
|
|
1354
|
+
* // …and on the way back:
|
|
1355
|
+
* const { code } = oauth.callback(request.url, savedState);
|
|
1356
|
+
* const tokens = await oauth.exchangeCode({ code, redirectUri, codeVerifier: verifier });
|
|
1357
|
+
* const client = new SignSealer({ apiKey: tokens.access_token });
|
|
1358
|
+
* ```
|
|
1359
|
+
*
|
|
1360
|
+
* The client is authenticated to `/oauth/token` by HTTP Basic, which RFC
|
|
1361
|
+
* 6749 prefers and the server reads first. Every token request is sent
|
|
1362
|
+
* exactly once: see `refresh()` for why that is the whole point.
|
|
1363
|
+
*/
|
|
1364
|
+
class SignSealerOAuth {
|
|
1365
|
+
#auth;
|
|
1366
|
+
#base;
|
|
1367
|
+
#clientId;
|
|
1368
|
+
#fetch;
|
|
1369
|
+
constructor(opts) {
|
|
1370
|
+
if (!opts?.clientId || !opts?.clientSecret) {
|
|
1371
|
+
throw new Error("an OAuth client needs its clientId and clientSecret");
|
|
1372
|
+
}
|
|
1373
|
+
if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
|
|
1374
|
+
throw new Error("that is a business's API key; OAuth takes your client id and secret");
|
|
1375
|
+
}
|
|
1376
|
+
this.#clientId = opts.clientId;
|
|
1377
|
+
/* Each half form-encoded before joining (RFC 6749, 2.3.1), which is how the server decodes them. */
|
|
1378
|
+
const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
|
|
1379
|
+
this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
|
|
1380
|
+
this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
|
|
1381
|
+
this.#fetch = opts.fetch ?? globalThis.fetch;
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Where to send the business's browser. SignSealer signs them in (or lets
|
|
1385
|
+
* them make an account and name their business on the way), shows your
|
|
1386
|
+
* registered name and what each scope allows, and sends them back to
|
|
1387
|
+
* `redirectUri` with `code` and your `state`, or with `error`.
|
|
1388
|
+
*
|
|
1389
|
+
* `redirectUri` must be one you registered, byte for byte, and the same
|
|
1390
|
+
* string you give `exchangeCode`. `state` is yours, returned untouched:
|
|
1391
|
+
* make it unguessable, keep it with the verifier, and check it in
|
|
1392
|
+
* `callback`. Ask for the fewest scopes that do the job; a scope your
|
|
1393
|
+
* client was not registered with is refused as `invalid_scope`.
|
|
1394
|
+
*/
|
|
1395
|
+
authorizeUrl(opts) {
|
|
1396
|
+
if (!opts?.redirectUri)
|
|
1397
|
+
throw new Error("authorizeUrl needs the redirectUri you registered");
|
|
1398
|
+
if (!opts.scopes?.length)
|
|
1399
|
+
throw new Error("authorizeUrl needs at least one scope");
|
|
1400
|
+
if (!opts.state)
|
|
1401
|
+
throw new Error("authorizeUrl needs a state, to check on the way back");
|
|
1402
|
+
if (!opts.codeChallenge || opts.codeChallenge.length < 43) {
|
|
1403
|
+
throw new Error("authorizeUrl needs the codeChallenge from createPkce(); PKCE is required");
|
|
1404
|
+
}
|
|
1405
|
+
const q = new URLSearchParams({
|
|
1406
|
+
response_type: "code",
|
|
1407
|
+
client_id: this.#clientId,
|
|
1408
|
+
redirect_uri: opts.redirectUri,
|
|
1409
|
+
scope: opts.scopes.join(" "),
|
|
1410
|
+
state: opts.state,
|
|
1411
|
+
code_challenge: opts.codeChallenge,
|
|
1412
|
+
code_challenge_method: "S256",
|
|
1413
|
+
});
|
|
1414
|
+
return `${this.#base}/oauth/authorize?${q}`;
|
|
1415
|
+
}
|
|
1416
|
+
/**
|
|
1417
|
+
* Read the consent screen's answer from your redirect's query: the code,
|
|
1418
|
+
* once `state` matches the one you kept. A business that pressed Not now
|
|
1419
|
+
* comes back as `access_denied`, and a request the screen could not
|
|
1420
|
+
* answer as its RFC 6749 error; both are thrown as SignSealerOAuthError,
|
|
1421
|
+
* with `status` 400. A `state` that does not match is `state_mismatch`:
|
|
1422
|
+
* do not exchange that code.
|
|
1423
|
+
*/
|
|
1424
|
+
callback(query, expectedState) {
|
|
1425
|
+
const q = query instanceof URLSearchParams ? query
|
|
1426
|
+
: query instanceof URL ? query.searchParams
|
|
1427
|
+
: new URLSearchParams(query.includes("?") ? query.slice(query.indexOf("?") + 1) : query);
|
|
1428
|
+
const state = q.get("state") ?? "";
|
|
1429
|
+
if (!expectedState || !sameBytes(new TextEncoder().encode(state), new TextEncoder().encode(expectedState))) {
|
|
1430
|
+
throw new SignSealerOAuthError(400, "state_mismatch", "the state that came back is not the one this browser was sent with");
|
|
1431
|
+
}
|
|
1432
|
+
const error = q.get("error");
|
|
1433
|
+
if (error)
|
|
1434
|
+
throw new SignSealerOAuthError(400, error, q.get("error_description") ?? error);
|
|
1435
|
+
const code = q.get("code");
|
|
1436
|
+
if (!code)
|
|
1437
|
+
throw new SignSealerOAuthError(400, "invalid_request", "the answer carried neither a code nor an error");
|
|
1438
|
+
return { code };
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* Exchange the code from `callback` for the business's tokens. Do it at
|
|
1442
|
+
* once: a code lives sixty seconds and is good once.
|
|
1443
|
+
*
|
|
1444
|
+
* Sent once and never again. A code presented twice is a replay, and the
|
|
1445
|
+
* server revokes the grant it made, so a retry after a lost answer would
|
|
1446
|
+
* disconnect the business it just connected. If this throws `transient`,
|
|
1447
|
+
* send the business through `authorizeUrl` again.
|
|
1448
|
+
*/
|
|
1449
|
+
exchangeCode(opts) {
|
|
1450
|
+
if (!opts?.code || !opts.redirectUri || !opts.codeVerifier) {
|
|
1451
|
+
throw new Error("exchangeCode needs the code, the same redirectUri and the PKCE codeVerifier");
|
|
1452
|
+
}
|
|
1453
|
+
return this.#token({
|
|
1454
|
+
grant_type: "authorization_code",
|
|
1455
|
+
code: opts.code,
|
|
1456
|
+
redirect_uri: opts.redirectUri,
|
|
1457
|
+
code_verifier: opts.codeVerifier,
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* Swap a refresh token for a new access token **and a new refresh token**.
|
|
1462
|
+
*
|
|
1463
|
+
* **THIS IS NEVER RETRIED, AND YOU MUST NOT RETRY IT EITHER WITHOUT
|
|
1464
|
+
* THINKING.** The refresh token you send is spent the moment SignSealer
|
|
1465
|
+
* reads it. Presenting a spent one is treated as theft: the whole family
|
|
1466
|
+
* is revoked -- every refresh token from that connection, the grant, and
|
|
1467
|
+
* every access token issued under it -- and the business has to connect
|
|
1468
|
+
* again. From the server's side a buggy retry and a stolen token look the
|
|
1469
|
+
* same.
|
|
1470
|
+
*
|
|
1471
|
+
* So:
|
|
1472
|
+
*
|
|
1473
|
+
* 1. **Serialise refreshes per grant.** One at a time for each business
|
|
1474
|
+
* (a row lock, an advisory lock, a queue). Two workers refreshing the
|
|
1475
|
+
* same grant at once will end it.
|
|
1476
|
+
* 2. **Store the new refresh token before you use the access token**,
|
|
1477
|
+
* atomically, while still holding the lock. A new refresh token you
|
|
1478
|
+
* lose cannot be got back.
|
|
1479
|
+
* 3. **A `transient` failure leaves the token's state unknown.** If the
|
|
1480
|
+
* request reached SignSealer and the answer was lost, the token you
|
|
1481
|
+
* hold is spent and its successor lost with the answer; if it never
|
|
1482
|
+
* arrived, it is still good. Sending it again either works or ends
|
|
1483
|
+
* the connection (`reconnect`), which losing the successor had
|
|
1484
|
+
* already made inevitable. That is your decision, made under the
|
|
1485
|
+
* lock, never a loop.
|
|
1486
|
+
* 4. **`reconnect` means reconnect.** Mark the business disconnected and
|
|
1487
|
+
* ask them to connect again; do not try the token again.
|
|
1488
|
+
*/
|
|
1489
|
+
refresh(refreshToken) {
|
|
1490
|
+
if (!refreshToken)
|
|
1491
|
+
throw new Error("refresh needs the refresh token you stored last");
|
|
1492
|
+
return this.#token({ grant_type: "refresh_token", refresh_token: refreshToken });
|
|
1493
|
+
}
|
|
1494
|
+
/*
|
|
1495
|
+
One request, one answer, no loop. Every other call in this package
|
|
1496
|
+
retries what is worth retrying; this one has nothing worth retrying,
|
|
1497
|
+
because both of its grants are spent by being read.
|
|
1498
|
+
*/
|
|
1499
|
+
async #token(form) {
|
|
1500
|
+
const sentAt = Date.now();
|
|
1501
|
+
let res;
|
|
1502
|
+
try {
|
|
1503
|
+
res = await this.#fetch(`${this.#base}/oauth/token`, {
|
|
1504
|
+
method: "POST",
|
|
1505
|
+
headers: {
|
|
1506
|
+
authorization: this.#auth,
|
|
1507
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
1508
|
+
accept: "application/json",
|
|
1509
|
+
},
|
|
1510
|
+
body: new URLSearchParams(form).toString(),
|
|
1511
|
+
});
|
|
1512
|
+
}
|
|
1513
|
+
catch (cause) {
|
|
1514
|
+
throw new SignSealerOAuthError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer");
|
|
1515
|
+
}
|
|
1516
|
+
const requestId = res.headers.get("x-request-id") ?? undefined;
|
|
1517
|
+
const text = await res.text();
|
|
1518
|
+
const parsed = (text ? safeJson(text) : {});
|
|
1519
|
+
if (res.ok && typeof parsed.access_token === "string") {
|
|
1520
|
+
const expiresIn = typeof parsed.expires_in === "number" ? parsed.expires_in : 3600;
|
|
1521
|
+
const scope = typeof parsed.scope === "string" ? parsed.scope : "";
|
|
1522
|
+
return {
|
|
1523
|
+
access_token: parsed.access_token,
|
|
1524
|
+
token_type: "Bearer",
|
|
1525
|
+
expires_in: expiresIn,
|
|
1526
|
+
expires_at: new Date(sentAt + expiresIn * 1000).toISOString(),
|
|
1527
|
+
scope,
|
|
1528
|
+
scopes: scope.split(" ").filter(Boolean),
|
|
1529
|
+
refresh_token: typeof parsed.refresh_token === "string" ? parsed.refresh_token : null,
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
const code = typeof parsed.error === "string" ? parsed.error
|
|
1533
|
+
: res.status >= 500 ? "server_error"
|
|
1534
|
+
: res.status === 429 ? "temporarily_unavailable"
|
|
1535
|
+
: res.ok ? "server_error" : "invalid_request";
|
|
1536
|
+
const description = typeof parsed.error_description === "string" ? parsed.error_description
|
|
1537
|
+
: res.ok ? "SignSealer answered without an access token" : `SignSealer returned ${res.status}`;
|
|
1538
|
+
/* A 200 with no token is SignSealer's fault, and as unknown in its outcome as a 500. */
|
|
1539
|
+
throw new SignSealerOAuthError(res.ok ? 502 : res.status, code, description, requestId, waitAsked(res.headers.get("retry-after")));
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
exports.SignSealerOAuth = SignSealerOAuth;
|
|
1233
1543
|
/* ------------------------------------------------------- verifying a webhook
|
|
1234
1544
|
|
|
1235
1545
|
The SDK could create a webhook endpoint and could not check a delivery from
|