sign-in-with-stacks 0.1.0 → 0.1.2

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.
@@ -33,6 +33,9 @@ jobs:
33
33
  - name: Install dependencies
34
34
  run: pnpm install
35
35
 
36
+ - name: Build
37
+ run: pnpm build
38
+
36
39
  - name: Create and publish versions
37
40
  uses: changesets/action@v1
38
41
  with:
@@ -28,6 +28,9 @@ jobs:
28
28
  - name: Install dependencies
29
29
  run: pnpm install
30
30
 
31
+ - name: Typecheck
32
+ run: pnpm typecheck
33
+
31
34
  - name: Build
32
35
  run: pnpm build
33
36
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # sign-in-with-stacks
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 2e1912e: Isolated declarations in build.
8
+
9
+ ## 0.1.1
10
+
11
+ ### Patch Changes
12
+
13
+ - 76b4cf2: Fix release files.
14
+
3
15
  ## 0.1.0
4
16
 
5
17
  ### Minor Changes
@@ -0,0 +1,212 @@
1
+ //#region src/errors/base.d.ts
2
+
3
+ type BaseErrorParameters = {
4
+ cause?: BaseError | Error | undefined;
5
+ details?: string | undefined;
6
+ docsBaseUrl?: string | undefined;
7
+ docsPath?: string | undefined;
8
+ docsSlug?: string | undefined;
9
+ metaMessages?: string[] | undefined;
10
+ name?: string | undefined;
11
+ };
12
+ declare class BaseError extends Error {
13
+ details: string;
14
+ docsPath?: string | undefined;
15
+ metaMessages?: string[] | undefined;
16
+ shortMessage: string;
17
+ name: string;
18
+ constructor(shortMessage: string, args?: BaseErrorParameters);
19
+ walk(): Error;
20
+ walk(fn: (err: unknown) => boolean): Error | null;
21
+ }
22
+ //#endregion
23
+ //#region src/errors/address.d.ts
24
+ type InvalidAddressErrorType = InvalidAddressError & {
25
+ name: "InvalidAddressError";
26
+ };
27
+ declare class InvalidAddressError extends BaseError {
28
+ constructor({
29
+ address
30
+ }: {
31
+ address: string;
32
+ });
33
+ }
34
+ //#endregion
35
+ //#region src/errors/siws.d.ts
36
+ type SiwsInvalidMessageFieldErrorType = SiwsInvalidMessageFieldError & {
37
+ name: "SiwsInvalidMessageFieldError";
38
+ };
39
+ declare class SiwsInvalidMessageFieldError extends BaseError {
40
+ constructor({
41
+ field,
42
+ metaMessages
43
+ }: {
44
+ field: string;
45
+ metaMessages?: string[] | undefined;
46
+ });
47
+ }
48
+ //#endregion
49
+ //#region src/types.d.ts
50
+ /**
51
+ * @description Combines members of an intersection into a readable type.
52
+ *
53
+ * @see {@link https://twitter.com/mattpocockuk/status/1622730173446557697?s=20&t=NdpAcmEFXY01xkqU3KO0Mg}
54
+ * @example
55
+ * Prettify<{ a: string } & { b: string } & { c: number, d: bigint }>
56
+ * => { a: string, b: string, c: number, d: bigint }
57
+ */
58
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
59
+ type ExactPartial<type> = { [key in keyof type]?: type[key] | undefined };
60
+ /**
61
+ * @description SIP-X message fields
62
+ *
63
+ * @see https://github.com/stacksgov/sips/pull/70
64
+ */
65
+ type SiwsMessage = {
66
+ /**
67
+ * The Stacks address performing the signing.
68
+ */
69
+ address: string;
70
+ /**
71
+ * The [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) Chain ID to which the session is bound,
72
+ */
73
+ chainId: number;
74
+ /**
75
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
76
+ */
77
+ domain: string;
78
+ /**
79
+ * Time when the signed authentication message is no longer valid.
80
+ */
81
+ expirationTime?: Date | undefined;
82
+ /**
83
+ * Time when the message was generated, typically the current time.
84
+ */
85
+ issuedAt?: Date | undefined;
86
+ /**
87
+ * A random string typically chosen by the relying party and used to prevent replay attacks.
88
+ */
89
+ nonce: string;
90
+ /**
91
+ * Time when the signed authentication message will become valid.
92
+ */
93
+ notBefore?: Date | undefined;
94
+ /**
95
+ * A system-specific identifier that may be used to uniquely refer to the sign-in request.
96
+ */
97
+ requestId?: string | undefined;
98
+ /**
99
+ * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party.
100
+ */
101
+ resources?: string[] | undefined;
102
+ /**
103
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
104
+ */
105
+ scheme?: string | undefined;
106
+ /**
107
+ * A human-readable ASCII assertion that the user will sign.
108
+ */
109
+ statement?: string | undefined;
110
+ /**
111
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI referring to the resource that is the subject of the signing (as in the subject of a claim).
112
+ */
113
+ uri: string;
114
+ /**
115
+ * The current version of the SIWS Message.
116
+ */
117
+ version: "1";
118
+ };
119
+ //#endregion
120
+ //#region src/createSiwsMessage.d.ts
121
+ type CreateSiwsMessageParameters = SiwsMessage;
122
+ type CreateSiwsMessageReturnType = string;
123
+ type CreateSiwsMessageErrorType = InvalidAddressErrorType | SiwsInvalidMessageFieldErrorType;
124
+ /**
125
+ * @description Creates SIP-X formatted message.
126
+ *
127
+ * @example
128
+ * const message = createMessage({
129
+ * address: 'SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173',
130
+ * chainId: 1,
131
+ * domain: 'example.com',
132
+ * nonce: 'foobarbaz',
133
+ * uri: 'https://example.com/path',
134
+ * version: '1',
135
+ * })
136
+ *
137
+ * @see https://github.com/stacksgov/sips/pull/70
138
+ */
139
+ declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): CreateSiwsMessageReturnType;
140
+ //#endregion
141
+ //#region src/generateSiwsNonce.d.ts
142
+ /**
143
+ * @description Generates random SIP-X nonce.
144
+ *
145
+ * @example
146
+ * const nonce = generateNonce()
147
+ *
148
+ * @see https://github.com/stacksgov/sips/pull/70
149
+ *
150
+ * @returns A randomly generated SIP-X nonce.
151
+ */
152
+ declare function generateSiwsNonce(): string;
153
+ //#endregion
154
+ //#region src/validateSiwsMessage.d.ts
155
+ type ValidateSiwsMessageParameters = {
156
+ /**
157
+ * Stacks address to check against.
158
+ */
159
+ address?: string | undefined;
160
+ /**
161
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.
162
+ */
163
+ domain?: string | undefined;
164
+ /**
165
+ * SIP-X message fields.
166
+ */
167
+ message: ExactPartial<SiwsMessage>;
168
+ /**
169
+ * Random string to check against.
170
+ */
171
+ nonce?: string | undefined;
172
+ /**
173
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.
174
+ */
175
+ scheme?: string | undefined;
176
+ /**
177
+ * Current time to check optional `expirationTime` and `notBefore` fields.
178
+ *
179
+ * @default new Date()
180
+ */
181
+ time?: Date | undefined;
182
+ };
183
+ type ValidateSiwsMessageReturnType = boolean;
184
+ /**
185
+ * @description Validates SIP-X message.
186
+ *
187
+ * @see https://github.com/stacksgov/sips/pull/70
188
+ */
189
+ declare function validateSiwsMessage(parameters: ValidateSiwsMessageParameters): ValidateSiwsMessageReturnType;
190
+ //#endregion
191
+ //#region src/verifySiwsMessage.d.ts
192
+ type VerifySiwsMessageParameters = Prettify<Pick<ValidateSiwsMessageParameters, "address" | "domain" | "nonce" | "scheme" | "time"> & {
193
+ /**
194
+ * SIP-X formatted message.
195
+ */
196
+ message: string;
197
+ /**
198
+ * Signature to check against.
199
+ */
200
+ signature: string;
201
+ }>;
202
+ type VerifySiwsMessageReturnType = boolean;
203
+ /**
204
+ * Verifies [SIP-X](https://github.com/stacksgov/sips/pull/70) formatted message was signed.
205
+ *
206
+ * @param parameters - {@link VerifySiwsMessageParameters}
207
+ * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}
208
+ */
209
+ declare function verifySiwsMessage(parameters: VerifySiwsMessageParameters): VerifySiwsMessageReturnType;
210
+ //#endregion
211
+ export { CreateSiwsMessageErrorType, CreateSiwsMessageParameters, CreateSiwsMessageReturnType, ValidateSiwsMessageParameters, ValidateSiwsMessageReturnType, VerifySiwsMessageParameters, VerifySiwsMessageReturnType, createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
212
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,345 @@
1
+ import { createMessageSignature, publicKeyFromSignatureRsv, publicKeyToAddress, validateStacksAddress } from "@stacks/transactions";
2
+ import { bytesToHex } from "@stacks/common";
3
+ import { hashMessage, verifyMessageSignatureRsv } from "@stacks/encryption";
4
+ import { STACKS_MAINNET } from "@stacks/network";
5
+
6
+ //#region src/errors/base.ts
7
+ let errorConfig = { getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : void 0 };
8
+ var BaseError = class BaseError extends Error {
9
+ details;
10
+ docsPath;
11
+ metaMessages;
12
+ shortMessage;
13
+ name = "BaseError";
14
+ constructor(shortMessage, args = {}) {
15
+ const details = (() => {
16
+ if (args.cause instanceof BaseError) return args.cause.details;
17
+ if (args.cause?.message) return args.cause.message;
18
+ return args.details;
19
+ })();
20
+ const docsPath = (() => {
21
+ if (args.cause instanceof BaseError) return args.cause.docsPath || args.docsPath;
22
+ return args.docsPath;
23
+ })();
24
+ const docsUrl = errorConfig.getDocsUrl?.({
25
+ ...args,
26
+ docsPath
27
+ });
28
+ const message = [
29
+ shortMessage || "An error occurred.",
30
+ "",
31
+ ...args.metaMessages ? [...args.metaMessages, ""] : [],
32
+ ...docsUrl ? [`Docs: ${docsUrl}`] : [],
33
+ ...details ? [`Details: ${details}`] : []
34
+ ].filter((data) => data !== "").join("\n").replace(/\n$/, "");
35
+ super(message, args.cause ? { cause: args.cause } : void 0);
36
+ this.details = details;
37
+ this.docsPath = docsPath;
38
+ this.metaMessages = args.metaMessages;
39
+ this.name = args.name ?? this.name;
40
+ this.shortMessage = shortMessage;
41
+ }
42
+ walk(fn) {
43
+ return walk(this, fn);
44
+ }
45
+ };
46
+ function walk(err, fn) {
47
+ if (fn?.(err)) return err;
48
+ if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) return walk(err.cause, fn);
49
+ return fn ? null : err;
50
+ }
51
+
52
+ //#endregion
53
+ //#region src/errors/siws.ts
54
+ var SiwsInvalidMessageFieldError = class extends BaseError {
55
+ constructor({ field, metaMessages }) {
56
+ super(`Invalid Sign-In with Stacks message field "${field}".`, {
57
+ metaMessages,
58
+ name: "SiwsInvalidMessageFieldError"
59
+ });
60
+ }
61
+ };
62
+
63
+ //#endregion
64
+ //#region src/errors/address.ts
65
+ var InvalidAddressError = class extends BaseError {
66
+ constructor({ address }) {
67
+ super(`Address "${address}" is invalid.`, { name: "InvalidAddressError" });
68
+ }
69
+ };
70
+
71
+ //#endregion
72
+ //#region src/utils.ts
73
+ function isUri(value) {
74
+ if (/[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i.test(value)) return false;
75
+ if (/%[^0-9a-f]/i.test(value)) return false;
76
+ if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return false;
77
+ const splitted = splitUri(value);
78
+ const scheme = splitted[1];
79
+ const authority = splitted[2];
80
+ const path = splitted[3];
81
+ const query = splitted[4];
82
+ const fragment = splitted[5];
83
+ if (!(scheme?.length && path.length >= 0)) return false;
84
+ if (authority?.length) {
85
+ if (!(path.length === 0 || /^\//.test(path))) return false;
86
+ } else if (/^\/\//.test(path)) return false;
87
+ if (!/^[a-z][a-z0-9\+\-\.]*$/.test(scheme.toLowerCase())) return false;
88
+ let out = "";
89
+ out += `${scheme}:`;
90
+ if (authority?.length) out += `//${authority}`;
91
+ out += path;
92
+ if (query?.length) out += `?${query}`;
93
+ if (fragment?.length) out += `#${fragment}`;
94
+ return out;
95
+ }
96
+ function splitUri(value) {
97
+ return value.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
98
+ }
99
+ function isAddressEqual(a, b) {
100
+ if (!validateStacksAddress(a)) throw new InvalidAddressError({ address: a });
101
+ if (!validateStacksAddress(b)) throw new InvalidAddressError({ address: b });
102
+ return a === b;
103
+ }
104
+ function getAddress(address) {
105
+ if (!validateStacksAddress(address)) throw new InvalidAddressError({ address });
106
+ return address;
107
+ }
108
+
109
+ //#endregion
110
+ //#region src/createSiwsMessage.ts
111
+ /**
112
+ * @description Creates SIP-X formatted message.
113
+ *
114
+ * @example
115
+ * const message = createMessage({
116
+ * address: 'SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173',
117
+ * chainId: 1,
118
+ * domain: 'example.com',
119
+ * nonce: 'foobarbaz',
120
+ * uri: 'https://example.com/path',
121
+ * version: '1',
122
+ * })
123
+ *
124
+ * @see https://github.com/stacksgov/sips/pull/70
125
+ */
126
+ function createSiwsMessage(parameters) {
127
+ const { chainId, domain, expirationTime, issuedAt = /* @__PURE__ */ new Date(), nonce, notBefore, requestId, resources, scheme, uri, version } = parameters;
128
+ {
129
+ if (chainId !== Math.floor(chainId)) throw new SiwsInvalidMessageFieldError({
130
+ field: "chainId",
131
+ metaMessages: [
132
+ "- Chain ID must be a SIP-005 chain ID.",
133
+ "- See https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md",
134
+ "",
135
+ `Provided value: ${chainId}`
136
+ ]
137
+ });
138
+ if (!(domainRegex.test(domain) || ipRegex.test(domain) || localhostRegex.test(domain))) throw new SiwsInvalidMessageFieldError({
139
+ field: "domain",
140
+ metaMessages: [
141
+ "- Domain must be an RFC 3986 authority.",
142
+ "- See https://www.rfc-editor.org/rfc/rfc3986",
143
+ "",
144
+ `Provided value: ${domain}`
145
+ ]
146
+ });
147
+ if (!nonceRegex.test(nonce)) throw new SiwsInvalidMessageFieldError({
148
+ field: "nonce",
149
+ metaMessages: [
150
+ "- Nonce must be at least 8 characters.",
151
+ "- Nonce must be alphanumeric.",
152
+ "",
153
+ `Provided value: ${nonce}`
154
+ ]
155
+ });
156
+ if (!isUri(uri)) throw new SiwsInvalidMessageFieldError({
157
+ field: "uri",
158
+ metaMessages: [
159
+ "- URI must be a RFC 3986 URI referring to the resource that is the subject of the signing.",
160
+ "- See https://www.rfc-editor.org/rfc/rfc3986",
161
+ "",
162
+ `Provided value: ${uri}`
163
+ ]
164
+ });
165
+ if (version !== "1") throw new SiwsInvalidMessageFieldError({
166
+ field: "version",
167
+ metaMessages: [
168
+ "- Version must be '1'.",
169
+ "",
170
+ `Provided value: ${version}`
171
+ ]
172
+ });
173
+ if (scheme && !schemeRegex.test(scheme)) throw new SiwsInvalidMessageFieldError({
174
+ field: "scheme",
175
+ metaMessages: [
176
+ "- Scheme must be an RFC 3986 URI scheme.",
177
+ "- See https://www.rfc-editor.org/rfc/rfc3986#section-3.1",
178
+ "",
179
+ `Provided value: ${scheme}`
180
+ ]
181
+ });
182
+ const statement$1 = parameters.statement;
183
+ if (statement$1?.includes("\n")) throw new SiwsInvalidMessageFieldError({
184
+ field: "statement",
185
+ metaMessages: [
186
+ "- Statement must not include '\\n'.",
187
+ "",
188
+ `Provided value: ${statement$1}`
189
+ ]
190
+ });
191
+ }
192
+ const address = getAddress(parameters.address);
193
+ const origin = (() => {
194
+ if (scheme) return `${scheme}://${domain}`;
195
+ return domain;
196
+ })();
197
+ const statement = (() => {
198
+ if (!parameters.statement) return "";
199
+ return `${parameters.statement}\n`;
200
+ })();
201
+ const prefix = `${origin} wants you to sign in with your Stacks account:\n${address}\n\n${statement}`;
202
+ let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}\nNonce: ${nonce}\nIssued At: ${issuedAt.toISOString()}`;
203
+ if (expirationTime) suffix += `\nExpiration Time: ${expirationTime.toISOString()}`;
204
+ if (notBefore) suffix += `\nNot Before: ${notBefore.toISOString()}`;
205
+ if (requestId) suffix += `\nRequest ID: ${requestId}`;
206
+ if (resources) {
207
+ let content = "\nResources:";
208
+ for (const resource of resources) {
209
+ if (!isUri(resource)) throw new SiwsInvalidMessageFieldError({
210
+ field: "resources",
211
+ metaMessages: [
212
+ "- Every resource must be a RFC 3986 URI.",
213
+ "- See https://www.rfc-editor.org/rfc/rfc3986",
214
+ "",
215
+ `Provided value: ${resource}`
216
+ ]
217
+ });
218
+ content += `\n- ${resource}`;
219
+ }
220
+ suffix += content;
221
+ }
222
+ return `${prefix}\n${suffix}`;
223
+ }
224
+ const domainRegex = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?$/;
225
+ const ipRegex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/;
226
+ const localhostRegex = /^localhost(:[0-9]{1,5})?$/;
227
+ const nonceRegex = /^[a-zA-Z0-9]{8,}$/;
228
+ const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/;
229
+
230
+ //#endregion
231
+ //#region src/generateSiwsNonce.ts
232
+ const size = 256;
233
+ let index = size;
234
+ let buffer;
235
+ function uid(length = 11) {
236
+ if (!buffer || index + length > size * 2) {
237
+ buffer = "";
238
+ index = 0;
239
+ for (let i = 0; i < size; i++) buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1);
240
+ }
241
+ return buffer.substring(index, index++ + length);
242
+ }
243
+ /**
244
+ * @description Generates random SIP-X nonce.
245
+ *
246
+ * @example
247
+ * const nonce = generateNonce()
248
+ *
249
+ * @see https://github.com/stacksgov/sips/pull/70
250
+ *
251
+ * @returns A randomly generated SIP-X nonce.
252
+ */
253
+ function generateSiwsNonce() {
254
+ return uid(96);
255
+ }
256
+
257
+ //#endregion
258
+ //#region src/validateSiwsMessage.ts
259
+ /**
260
+ * @description Validates SIP-X message.
261
+ *
262
+ * @see https://github.com/stacksgov/sips/pull/70
263
+ */
264
+ function validateSiwsMessage(parameters) {
265
+ const { address, domain, message, nonce, scheme, time = /* @__PURE__ */ new Date() } = parameters;
266
+ if (domain && message.domain !== domain) return false;
267
+ if (nonce && message.nonce !== nonce) return false;
268
+ if (scheme && message.scheme !== scheme) return false;
269
+ if (message.expirationTime && time >= message.expirationTime) return false;
270
+ if (message.notBefore && time < message.notBefore) return false;
271
+ try {
272
+ if (!message.address) return false;
273
+ if (address && !isAddressEqual(message.address, address)) return false;
274
+ } catch {
275
+ return false;
276
+ }
277
+ return true;
278
+ }
279
+
280
+ //#endregion
281
+ //#region src/parseSiwsMessage.ts
282
+ /**
283
+ * @description Parses SIP-X formatted message into message fields object.
284
+ *
285
+ * @see https://github.com/stacksgov/sips/pull/70
286
+ *
287
+ * @returns SIP-X fields object
288
+ */
289
+ function parseSiwsMessage(message) {
290
+ const { scheme, statement,...prefix } = message.match(prefixRegex)?.groups ?? {};
291
+ const { chainId, expirationTime, issuedAt, notBefore, requestId,...suffix } = message.match(suffixRegex)?.groups ?? {};
292
+ const resources = message.split("Resources:")[1]?.split("\n- ").slice(1);
293
+ return {
294
+ ...prefix,
295
+ ...suffix,
296
+ ...chainId ? { chainId: Number(chainId) } : {},
297
+ ...expirationTime ? { expirationTime: new Date(expirationTime) } : {},
298
+ ...issuedAt ? { issuedAt: new Date(issuedAt) } : {},
299
+ ...notBefore ? { notBefore: new Date(notBefore) } : {},
300
+ ...requestId ? { requestId } : {},
301
+ ...resources ? { resources } : {},
302
+ ...scheme ? { scheme } : {},
303
+ ...statement ? { statement } : {}
304
+ };
305
+ }
306
+ const prefixRegex = /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Stacks account:\n)(?<address>S[A-Z0-9]{39,40})\n\n(?:(?<statement>.*)\n\n)?/;
307
+ const suffixRegex = /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;
308
+
309
+ //#endregion
310
+ //#region src/verifySiwsMessage.ts
311
+ /**
312
+ * Verifies [SIP-X](https://github.com/stacksgov/sips/pull/70) formatted message was signed.
313
+ *
314
+ * @param parameters - {@link VerifySiwsMessageParameters}
315
+ * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}
316
+ */
317
+ function verifySiwsMessage(parameters) {
318
+ const { address, domain, message, nonce, scheme, signature, time = /* @__PURE__ */ new Date() } = parameters;
319
+ const parsed = parseSiwsMessage(message);
320
+ if (!parsed.address) return false;
321
+ if (!parsed.chainId) return false;
322
+ const isValid = validateSiwsMessage({
323
+ address,
324
+ domain,
325
+ message: parsed,
326
+ nonce,
327
+ scheme,
328
+ time
329
+ });
330
+ if (!isValid) return false;
331
+ const stacksSignature = createMessageSignature(signature);
332
+ const hash = hashMessage(message);
333
+ const publicKey = publicKeyFromSignatureRsv(bytesToHex(hash), stacksSignature.data);
334
+ const stacksAddress = publicKeyToAddress(publicKey, parsed.chainId === STACKS_MAINNET.chainId ? "mainnet" : "testnet");
335
+ const isValidSignature = verifyMessageSignatureRsv({
336
+ signature,
337
+ message,
338
+ publicKey
339
+ });
340
+ return isValidSignature && stacksAddress === parsed.address;
341
+ }
342
+
343
+ //#endregion
344
+ export { createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
345
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["errorConfig: ErrorConfig","shortMessage: string","args: BaseErrorParameters","fn?: any","err: unknown","fn?: ((err: unknown) => boolean) | undefined","value: string","a: string","b: string","address: string","parameters: CreateSiwsMessageParameters","statement","buffer: string","parameters: ValidateSiwsMessageParameters","message: string","parameters: VerifySiwsMessageParameters"],"sources":["../src/errors/base.ts","../src/errors/siws.ts","../src/errors/address.ts","../src/utils.ts","../src/createSiwsMessage.ts","../src/generateSiwsNonce.ts","../src/validateSiwsMessage.ts","../src/parseSiwsMessage.ts","../src/verifySiwsMessage.ts"],"sourcesContent":["type ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined;\n};\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = \"\",\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? \"https://viem.sh\"}${docsPath}${\n docsSlug ? `#${docsSlug}` : \"\"\n }`\n : undefined,\n};\n\nexport function setErrorConfig(config: ErrorConfig): void {\n errorConfig = config;\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined;\n details?: string | undefined;\n docsBaseUrl?: string | undefined;\n docsPath?: string | undefined;\n docsSlug?: string | undefined;\n metaMessages?: string[] | undefined;\n name?: string | undefined;\n};\n\nexport type BaseErrorType = BaseError & { name: \"BaseError\" };\nexport class BaseError extends Error {\n details: string;\n docsPath?: string | undefined;\n metaMessages?: string[] | undefined;\n shortMessage: string;\n\n override name = \"BaseError\";\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details;\n if (args.cause?.message) return args.cause.message;\n return args.details!;\n })();\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath;\n return args.docsPath;\n })();\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });\n\n const message = [\n shortMessage || \"An error occurred.\",\n \"\",\n ...(args.metaMessages ? [...args.metaMessages, \"\"] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ]\n .filter((data) => data !== \"\")\n .join(\"\\n\")\n .replace(/\\n$/, \"\");\n\n super(message, args.cause ? { cause: args.cause } : undefined);\n\n this.details = details;\n this.docsPath = docsPath;\n this.metaMessages = args.metaMessages;\n this.name = args.name ?? this.name;\n this.shortMessage = shortMessage;\n }\n\n walk(): Error;\n walk(fn: (err: unknown) => boolean): Error | null;\n // biome-ignore lint/suspicious/noExplicitAny: <explanation>\n walk(fn?: any): any {\n return walk(this, fn);\n }\n}\n\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err;\n if (\n err &&\n typeof err === \"object\" &&\n \"cause\" in err &&\n err.cause !== undefined\n )\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n","import { BaseError } from \"./base.js\";\n\nexport type SiwsInvalidMessageFieldErrorType = SiwsInvalidMessageFieldError & {\n name: \"SiwsInvalidMessageFieldError\";\n};\nexport class SiwsInvalidMessageFieldError extends BaseError {\n constructor({\n field,\n metaMessages,\n }: {\n field: string;\n metaMessages?: string[] | undefined;\n }) {\n super(`Invalid Sign-In with Stacks message field \"${field}\".`, {\n metaMessages,\n name: \"SiwsInvalidMessageFieldError\",\n });\n }\n}\n","import { BaseError } from \"./base.js\";\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: \"InvalidAddressError\";\n};\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n name: \"InvalidAddressError\",\n });\n }\n}\n","import { validateStacksAddress } from \"@stacks/transactions\";\nimport { InvalidAddressError } from \"./errors/address.js\";\n\nexport function isUri(value: string): boolean | string {\n // based on https://github.com/ogt/valid-url\n\n // check for illegal characters\n if (/[^a-z0-9\\:\\/\\?\\#\\[\\]\\@\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=\\.\\-\\_\\~\\%]/i.test(value))\n return false;\n\n // check for hex escapes that aren't complete\n if (/%[^0-9a-f]/i.test(value)) return false;\n if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return false;\n\n // from RFC 3986\n const splitted = splitUri(value);\n const scheme = splitted[1];\n const authority = splitted[2];\n const path = splitted[3];\n const query = splitted[4];\n const fragment = splitted[5];\n\n // scheme and path are required, though the path can be empty\n if (!(scheme?.length && path.length >= 0)) return false;\n\n // if authority is present, the path must be empty or begin with a /\n if (authority?.length) {\n if (!(path.length === 0 || /^\\//.test(path))) return false;\n } else {\n // if authority is not present, the path must not start with //\n if (/^\\/\\//.test(path)) return false;\n }\n\n // scheme must begin with a letter, then consist of letters, digits, +, ., or -\n if (!/^[a-z][a-z0-9\\+\\-\\.]*$/.test(scheme.toLowerCase())) return false;\n\n let out = \"\";\n // re-assemble the URL per section 5.3 in RFC 3986\n out += `${scheme}:`;\n if (authority?.length) out += `//${authority}`;\n\n out += path;\n\n if (query?.length) out += `?${query}`;\n if (fragment?.length) out += `#${fragment}`;\n\n return out;\n}\n\nfunction splitUri(value: string): RegExpMatchArray {\n return value.match(\n /(?:([^:\\/?#]+):)?(?:\\/\\/([^\\/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?/,\n )!;\n}\n\nexport function isAddressEqual(a: string, b: string): boolean {\n if (!validateStacksAddress(a)) throw new InvalidAddressError({ address: a });\n if (!validateStacksAddress(b)) throw new InvalidAddressError({ address: b });\n return a === b;\n}\n\nexport function getAddress(address: string): string {\n if (!validateStacksAddress(address))\n throw new InvalidAddressError({ address });\n return address;\n}\n","import type { InvalidAddressErrorType } from \"./errors/address.js\";\nimport {\n SiwsInvalidMessageFieldError,\n type SiwsInvalidMessageFieldErrorType,\n} from \"./errors/siws.js\";\nimport type { SiwsMessage } from \"./types.js\";\nimport { getAddress, isUri } from \"./utils.js\";\n\nexport type CreateSiwsMessageParameters = SiwsMessage;\n\nexport type CreateSiwsMessageReturnType = string;\n\nexport type CreateSiwsMessageErrorType =\n | InvalidAddressErrorType\n | SiwsInvalidMessageFieldErrorType;\n\n/**\n * @description Creates SIP-X formatted message.\n *\n * @example\n * const message = createMessage({\n * address: 'SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173',\n * chainId: 1,\n * domain: 'example.com',\n * nonce: 'foobarbaz',\n * uri: 'https://example.com/path',\n * version: '1',\n * })\n *\n * @see https://github.com/stacksgov/sips/pull/70\n */\nexport function createSiwsMessage(\n parameters: CreateSiwsMessageParameters,\n): CreateSiwsMessageReturnType {\n const {\n chainId,\n domain,\n expirationTime,\n issuedAt = new Date(),\n nonce,\n notBefore,\n requestId,\n resources,\n scheme,\n uri,\n version,\n } = parameters;\n\n // Validate fields\n {\n // Required fields\n if (chainId !== Math.floor(chainId))\n throw new SiwsInvalidMessageFieldError({\n field: \"chainId\",\n metaMessages: [\n \"- Chain ID must be a SIP-005 chain ID.\",\n \"- See https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md\",\n \"\",\n `Provided value: ${chainId}`,\n ],\n });\n if (\n !(\n domainRegex.test(domain) ||\n ipRegex.test(domain) ||\n localhostRegex.test(domain)\n )\n )\n throw new SiwsInvalidMessageFieldError({\n field: \"domain\",\n metaMessages: [\n \"- Domain must be an RFC 3986 authority.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${domain}`,\n ],\n });\n if (!nonceRegex.test(nonce))\n throw new SiwsInvalidMessageFieldError({\n field: \"nonce\",\n metaMessages: [\n \"- Nonce must be at least 8 characters.\",\n \"- Nonce must be alphanumeric.\",\n \"\",\n `Provided value: ${nonce}`,\n ],\n });\n if (!isUri(uri))\n throw new SiwsInvalidMessageFieldError({\n field: \"uri\",\n metaMessages: [\n \"- URI must be a RFC 3986 URI referring to the resource that is the subject of the signing.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${uri}`,\n ],\n });\n if (version !== \"1\")\n throw new SiwsInvalidMessageFieldError({\n field: \"version\",\n metaMessages: [\n \"- Version must be '1'.\",\n \"\",\n `Provided value: ${version}`,\n ],\n });\n\n // Optional fields\n if (scheme && !schemeRegex.test(scheme))\n throw new SiwsInvalidMessageFieldError({\n field: \"scheme\",\n metaMessages: [\n \"- Scheme must be an RFC 3986 URI scheme.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986#section-3.1\",\n \"\",\n `Provided value: ${scheme}`,\n ],\n });\n const statement = parameters.statement;\n if (statement?.includes(\"\\n\"))\n throw new SiwsInvalidMessageFieldError({\n field: \"statement\",\n metaMessages: [\n \"- Statement must not include '\\\\n'.\",\n \"\",\n `Provided value: ${statement}`,\n ],\n });\n }\n\n // Construct message\n const address = getAddress(parameters.address);\n const origin = (() => {\n if (scheme) return `${scheme}://${domain}`;\n return domain;\n })();\n const statement = (() => {\n if (!parameters.statement) return \"\";\n return `${parameters.statement}\\n`;\n })();\n const prefix = `${origin} wants you to sign in with your Stacks account:\\n${address}\\n\\n${statement}`;\n\n let suffix = `URI: ${uri}\\nVersion: ${version}\\nChain ID: ${chainId}\\nNonce: ${nonce}\\nIssued At: ${issuedAt.toISOString()}`;\n\n if (expirationTime)\n suffix += `\\nExpiration Time: ${expirationTime.toISOString()}`;\n if (notBefore) suffix += `\\nNot Before: ${notBefore.toISOString()}`;\n if (requestId) suffix += `\\nRequest ID: ${requestId}`;\n if (resources) {\n let content = \"\\nResources:\";\n for (const resource of resources) {\n if (!isUri(resource))\n throw new SiwsInvalidMessageFieldError({\n field: \"resources\",\n metaMessages: [\n \"- Every resource must be a RFC 3986 URI.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${resource}`,\n ],\n });\n content += `\\n- ${resource}`;\n }\n suffix += content;\n }\n\n return `${prefix}\\n${suffix}`;\n}\n\nconst domainRegex =\n /^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?$/;\nconst ipRegex =\n /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/;\nconst localhostRegex = /^localhost(:[0-9]{1,5})?$/;\nconst nonceRegex = /^[a-zA-Z0-9]{8,}$/;\nconst schemeRegex = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/;\n","const size = 256;\nlet index = size;\nlet buffer: string;\n\nfunction uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = \"\";\n index = 0;\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1);\n }\n }\n return buffer.substring(index, index++ + length);\n}\n\n/**\n * @description Generates random SIP-X nonce.\n *\n * @example\n * const nonce = generateNonce()\n *\n * @see https://github.com/stacksgov/sips/pull/70\n *\n * @returns A randomly generated SIP-X nonce.\n */\nexport function generateSiwsNonce(): string {\n return uid(96);\n}\n","import type { ExactPartial, SiwsMessage } from \"./types.js\";\nimport { isAddressEqual } from \"./utils.js\";\n\nexport type ValidateSiwsMessageParameters = {\n /**\n * Stacks address to check against.\n */\n address?: string | undefined;\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.\n */\n domain?: string | undefined;\n /**\n * SIP-X message fields.\n */\n message: ExactPartial<SiwsMessage>;\n /**\n * Random string to check against.\n */\n nonce?: string | undefined;\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.\n */\n scheme?: string | undefined;\n /**\n * Current time to check optional `expirationTime` and `notBefore` fields.\n *\n * @default new Date()\n */\n time?: Date | undefined;\n};\n\nexport type ValidateSiwsMessageReturnType = boolean;\n\n/**\n * @description Validates SIP-X message.\n *\n * @see https://github.com/stacksgov/sips/pull/70\n */\nexport function validateSiwsMessage(\n parameters: ValidateSiwsMessageParameters,\n): ValidateSiwsMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n time = new Date(),\n } = parameters;\n\n if (domain && message.domain !== domain) return false;\n if (nonce && message.nonce !== nonce) return false;\n if (scheme && message.scheme !== scheme) return false;\n\n if (message.expirationTime && time >= message.expirationTime) return false;\n if (message.notBefore && time < message.notBefore) return false;\n\n try {\n if (!message.address) return false;\n if (address && !isAddressEqual(message.address, address)) return false;\n } catch {\n return false;\n }\n\n return true;\n}\n","import type { ExactPartial, Prettify, SiwsMessage } from \"./types.js\";\n\n/**\n * @description Parses SIP-X formatted message into message fields object.\n *\n * @see https://github.com/stacksgov/sips/pull/70\n *\n * @returns SIP-X fields object\n */\nexport function parseSiwsMessage(\n message: string,\n): Prettify<ExactPartial<SiwsMessage>> {\n const { scheme, statement, ...prefix } = (message.match(prefixRegex)\n ?.groups ?? {}) as {\n address: string;\n domain: string;\n scheme?: string;\n statement?: string;\n };\n const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } =\n (message.match(suffixRegex)?.groups ?? {}) as {\n chainId: string;\n expirationTime?: string;\n issuedAt?: string;\n nonce: string;\n notBefore?: string;\n requestId?: string;\n uri: string;\n version: \"1\";\n };\n const resources = message.split(\"Resources:\")[1]?.split(\"\\n- \").slice(1);\n return {\n ...prefix,\n ...suffix,\n ...(chainId ? { chainId: Number(chainId) } : {}),\n ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),\n ...(issuedAt ? { issuedAt: new Date(issuedAt) } : {}),\n ...(notBefore ? { notBefore: new Date(notBefore) } : {}),\n ...(requestId ? { requestId } : {}),\n ...(resources ? { resources } : {}),\n ...(scheme ? { scheme } : {}),\n ...(statement ? { statement } : {}),\n };\n}\n\n// https://regexr.com/80gdj\nconst prefixRegex =\n /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\\/\\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Stacks account:\\n)(?<address>S[A-Z0-9]{39,40})\\n\\n(?:(?<statement>.*)\\n\\n)?/;\n\n// https://regexr.com/80gf9\nconst suffixRegex =\n /(?:URI: (?<uri>.+))\\n(?:Version: (?<version>.+))\\n(?:Chain ID: (?<chainId>\\d+))\\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\\n(?:Issued At: (?<issuedAt>.+))(?:\\nExpiration Time: (?<expirationTime>.+))?(?:\\nNot Before: (?<notBefore>.+))?(?:\\nRequest ID: (?<requestId>.+))?/;\n","import { bytesToHex } from \"@stacks/common\";\nimport { hashMessage, verifyMessageSignatureRsv } from \"@stacks/encryption\";\nimport { STACKS_MAINNET } from \"@stacks/network\";\nimport {\n createMessageSignature,\n publicKeyFromSignatureRsv,\n publicKeyToAddress,\n} from \"@stacks/transactions\";\nimport { parseSiwsMessage } from \"./parseSiwsMessage.js\";\nimport type { Prettify } from \"./types.js\";\nimport {\n type ValidateSiwsMessageParameters,\n validateSiwsMessage,\n} from \"./validateSiwsMessage.js\";\n\nexport type VerifySiwsMessageParameters = Prettify<\n Pick<\n ValidateSiwsMessageParameters,\n \"address\" | \"domain\" | \"nonce\" | \"scheme\" | \"time\"\n > & {\n /**\n * SIP-X formatted message.\n */\n message: string;\n /**\n * Signature to check against.\n */\n signature: string;\n }\n>;\n\nexport type VerifySiwsMessageReturnType = boolean;\n\n/**\n * Verifies [SIP-X](https://github.com/stacksgov/sips/pull/70) formatted message was signed.\n *\n * @param parameters - {@link VerifySiwsMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}\n */\nexport function verifySiwsMessage(\n parameters: VerifySiwsMessageParameters,\n): VerifySiwsMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n signature,\n time = new Date(),\n } = parameters;\n\n const parsed = parseSiwsMessage(message);\n if (!parsed.address) return false;\n if (!parsed.chainId) return false;\n\n const isValid = validateSiwsMessage({\n address,\n domain,\n message: parsed,\n nonce,\n scheme,\n time,\n });\n if (!isValid) return false;\n\n const stacksSignature = createMessageSignature(signature);\n const hash = hashMessage(message);\n const publicKey = publicKeyFromSignatureRsv(\n bytesToHex(hash),\n stacksSignature.data,\n );\n const stacksAddress = publicKeyToAddress(\n publicKey,\n parsed.chainId === STACKS_MAINNET.chainId ? \"mainnet\" : \"testnet\",\n );\n\n const isValidSignature = verifyMessageSignatureRsv({\n signature,\n message,\n publicKey,\n });\n\n // Verify the address matches the signature address\n return isValidSignature && stacksAddress === parsed.address;\n}\n"],"mappings":";;;;;;AAIA,IAAIA,cAA2B,EAC7B,YAAY,CAAC,EACX,aACA,WAAW,IACX,UACoB,KACpB,YACK,EAAE,eAAe,kBAAkB,EAAE,SAAS,EAC7C,YAAY,GAAG,SAAS,IAAI,GAC7B,WAER;AAiBD,IAAa,YAAb,MAAa,kBAAkB,MAAM;CACnC;CACA;CACA;CACA;CAEA,AAAS,OAAO;CAEhB,YAAYC,cAAsBC,OAA4B,CAAE,GAAE;EAChE,MAAM,UAAU,CAAC,MAAM;AACrB,OAAI,KAAK,iBAAiB,UAAW,QAAO,KAAK,MAAM;AACvD,OAAI,KAAK,OAAO,QAAS,QAAO,KAAK,MAAM;AAC3C,UAAO,KAAK;EACb,IAAG;EACJ,MAAM,WAAW,CAAC,MAAM;AACtB,OAAI,KAAK,iBAAiB,UACxB,QAAO,KAAK,MAAM,YAAY,KAAK;AACrC,UAAO,KAAK;EACb,IAAG;EACJ,MAAM,UAAU,YAAY,aAAa;GAAE,GAAG;GAAM;EAAU,EAAC;EAE/D,MAAM,UAAU;GACd,gBAAgB;GAChB;GACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAG,IAAG,CAAE;GACvD,GAAI,UAAU,EAAE,QAAQ,QAAQ,CAAE,IAAG,CAAE;GACvC,GAAI,UAAU,EAAE,WAAW,QAAQ,CAAE,IAAG,CAAE;EAC3C,EACE,OAAO,CAAC,SAAS,SAAS,GAAG,CAC7B,KAAK,KAAK,CACV,QAAQ,OAAO,GAAG;AAErB,QAAM,SAAS,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAO,WAAa;AAE9D,OAAK,UAAU;AACf,OAAK,WAAW;AAChB,OAAK,eAAe,KAAK;AACzB,OAAK,OAAO,KAAK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,UAAU,EAAE,SAAS,OAAO,QAAQ,CAAE,IAAG,CAAE;EAC/C,GAAI,iBAAiB,EAAE,gBAAgB,IAAI,KAAK,gBAAiB,IAAG,CAAE;EACtE,GAAI,WAAW,EAAE,UAAU,IAAI,KAAK,UAAW,IAAG,CAAE;EACpD,GAAI,YAAY,EAAE,WAAW,IAAI,KAAK,WAAY,IAAG,CAAE;EACvD,GAAI,YAAY,EAAE,UAAW,IAAG,CAAE;EAClC,GAAI,YAAY,EAAE,UAAW,IAAG,CAAE;EAClC,GAAI,SAAS,EAAE,OAAQ,IAAG,CAAE;EAC5B,GAAI,YAAY,EAAE,UAAW,IAAG,CAAE;CACnC;AACF;AAGD,MAAM,cACJ;AAGF,MAAM,cACJ;;;;;;;;;;ACZF,SAAgB,kBACdC,YAC6B;CAC7B,MAAM,EACJ,SACA,QACA,SACA,OACA,QACA,WACA,uBAAO,IAAI,QACZ,GAAG;CAEJ,MAAM,SAAS,iBAAiB,QAAQ;AACxC,MAAK,OAAO,QAAS,QAAO;AAC5B,MAAK,OAAO,QAAS,QAAO;CAE5B,MAAM,UAAU,oBAAoB;EAClC;EACA;EACA,SAAS;EACT;EACA;EACA;CACD,EAAC;AACF,MAAK,QAAS,QAAO;CAErB,MAAM,kBAAkB,uBAAuB,UAAU;CACzD,MAAM,OAAO,YAAY,QAAQ;CACjC,MAAM,YAAY,0BAChB,WAAW,KAAK,EAChB,gBAAgB,KACjB;CACD,MAAM,gBAAgB,mBACpB,WACA,OAAO,YAAY,eAAe,UAAU,YAAY,UACzD;CAED,MAAM,mBAAmB,0BAA0B;EACjD;EACA;EACA;CACD,EAAC;AAGF,QAAO,oBAAoB,kBAAkB,OAAO;AACrD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sign-in-with-stacks",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -20,8 +20,8 @@
20
20
  "@stacks/network": "7.0.2",
21
21
  "@stacks/transactions": "7.0.6",
22
22
  "@tsconfig/recommended": "1.0.8",
23
- "@types/node": "22.15.21",
24
- "tsdown": "0.12.3",
23
+ "@types/node": "22.15.28",
24
+ "tsdown": "0.12.5",
25
25
  "typescript": "5.8.3",
26
26
  "vitest": "3.1.4"
27
27
  },
@@ -15,7 +15,7 @@ let errorConfig: ErrorConfig = {
15
15
  : undefined,
16
16
  };
17
17
 
18
- export function setErrorConfig(config: ErrorConfig) {
18
+ export function setErrorConfig(config: ErrorConfig): void {
19
19
  errorConfig = config;
20
20
  }
21
21
 
package/src/utils.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { validateStacksAddress } from "@stacks/transactions";
2
2
  import { InvalidAddressError } from "./errors/address.js";
3
3
 
4
- export function isUri(value: string) {
4
+ export function isUri(value: string): boolean | string {
5
5
  // based on https://github.com/ogt/valid-url
6
6
 
7
7
  // check for illegal characters
@@ -47,7 +47,7 @@ export function isUri(value: string) {
47
47
  return out;
48
48
  }
49
49
 
50
- function splitUri(value: string) {
50
+ function splitUri(value: string): RegExpMatchArray {
51
51
  return value.match(
52
52
  /(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
53
53
  )!;
package/tsconfig.json CHANGED
@@ -4,7 +4,9 @@
4
4
  "compilerOptions": {
5
5
  "target": "ESNext",
6
6
  "module": "NodeNext",
7
- "moduleResolution": "NodeNext"
7
+ "moduleResolution": "NodeNext",
8
+ "isolatedDeclarations": true,
9
+ "declaration": true
8
10
  },
9
11
  "include": ["**/*.ts"],
10
12
  "exclude": ["dist", "node_modules"]
package/tsdown.config.ts CHANGED
@@ -1,9 +1,11 @@
1
- import { defineConfig } from "tsdown";
1
+ import { defineConfig, type UserConfig, type UserConfigFn } from "tsdown";
2
2
 
3
- export default defineConfig({
3
+ const config: UserConfigFn | UserConfig = defineConfig({
4
4
  entry: ["src/index.ts"],
5
5
  sourcemap: true,
6
6
  clean: true,
7
7
  dts: true,
8
8
  platform: "neutral",
9
9
  });
10
+
11
+ export default config;