sign-in-with-stacks 0.1.1 → 0.1.4

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/dist/index.d.ts CHANGED
@@ -18,7 +18,8 @@ declare class BaseError extends Error {
18
18
  constructor(shortMessage: string, args?: BaseErrorParameters);
19
19
  walk(): Error;
20
20
  walk(fn: (err: unknown) => boolean): Error | null;
21
- } //#endregion
21
+ }
22
+ //#endregion
22
23
  //#region src/errors/address.d.ts
23
24
  type InvalidAddressErrorType = InvalidAddressError & {
24
25
  name: "InvalidAddressError";
@@ -30,7 +31,6 @@ declare class InvalidAddressError extends BaseError {
30
31
  address: string;
31
32
  });
32
33
  }
33
-
34
34
  //#endregion
35
35
  //#region src/errors/siws.d.ts
36
36
  type SiwsInvalidMessageFieldErrorType = SiwsInvalidMessageFieldError & {
@@ -45,172 +45,168 @@ declare class SiwsInvalidMessageFieldError extends BaseError {
45
45
  metaMessages?: string[] | undefined;
46
46
  });
47
47
  }
48
-
49
48
  //#endregion
50
49
  //#region src/types.d.ts
51
50
  /**
52
- * @description Combines members of an intersection into a readable type.
53
- *
54
- * @see {@link https://twitter.com/mattpocockuk/status/1622730173446557697?s=20&t=NdpAcmEFXY01xkqU3KO0Mg}
55
- * @example
56
- * Prettify<{ a: string } & { b: string } & { c: number, d: bigint }>
57
- * => { a: string, b: string, c: number, d: bigint }
58
- */
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
+ */
59
58
  type Prettify<T> = { [K in keyof T]: T[K] } & {};
60
59
  type ExactPartial<type> = { [key in keyof type]?: type[key] | undefined };
61
60
  /**
62
- * @description SIP-X message fields
63
- *
64
- * @see https://github.com/stacksgov/sips/pull/70
65
- */
61
+ * @description SIP-X message fields
62
+ *
63
+ * @see https://github.com/stacksgov/sips/pull/70
64
+ */
66
65
  type SiwsMessage = {
67
66
  /**
68
- * The Stacks address performing the signing.
69
- */
67
+ * The Stacks address performing the signing.
68
+ */
70
69
  address: string;
71
70
  /**
72
- * 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,
73
- */
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
+ */
74
73
  chainId: number;
75
74
  /**
76
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
77
- */
75
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
76
+ */
78
77
  domain: string;
79
78
  /**
80
- * Time when the signed authentication message is no longer valid.
81
- */
79
+ * Time when the signed authentication message is no longer valid.
80
+ */
82
81
  expirationTime?: Date | undefined;
83
82
  /**
84
- * Time when the message was generated, typically the current time.
85
- */
83
+ * Time when the message was generated, typically the current time.
84
+ */
86
85
  issuedAt?: Date | undefined;
87
86
  /**
88
- * A random string typically chosen by the relying party and used to prevent replay attacks.
89
- */
87
+ * A random string typically chosen by the relying party and used to prevent replay attacks.
88
+ */
90
89
  nonce: string;
91
90
  /**
92
- * Time when the signed authentication message will become valid.
93
- */
91
+ * Time when the signed authentication message will become valid.
92
+ */
94
93
  notBefore?: Date | undefined;
95
94
  /**
96
- * A system-specific identifier that may be used to uniquely refer to the sign-in request.
97
- */
95
+ * A system-specific identifier that may be used to uniquely refer to the sign-in request.
96
+ */
98
97
  requestId?: string | undefined;
99
98
  /**
100
- * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party.
101
- */
99
+ * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party.
100
+ */
102
101
  resources?: string[] | undefined;
103
102
  /**
104
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
105
- */
103
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
104
+ */
106
105
  scheme?: string | undefined;
107
106
  /**
108
- * A human-readable ASCII assertion that the user will sign.
109
- */
107
+ * A human-readable ASCII assertion that the user will sign.
108
+ */
110
109
  statement?: string | undefined;
111
110
  /**
112
- * [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).
113
- */
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
+ */
114
113
  uri: string;
115
114
  /**
116
- * The current version of the SIWS Message.
117
- */
115
+ * The current version of the SIWS Message.
116
+ */
118
117
  version: "1";
119
- }; //#endregion
118
+ };
119
+ //#endregion
120
120
  //#region src/createSiwsMessage.d.ts
121
121
  type CreateSiwsMessageParameters = SiwsMessage;
122
122
  type CreateSiwsMessageReturnType = string;
123
123
  type CreateSiwsMessageErrorType = InvalidAddressErrorType | SiwsInvalidMessageFieldErrorType;
124
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
- */
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
139
  declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): CreateSiwsMessageReturnType;
140
-
141
140
  //#endregion
142
141
  //#region src/generateSiwsNonce.d.ts
143
142
  /**
144
- * @description Generates random SIP-X nonce.
145
- *
146
- * @example
147
- * const nonce = generateNonce()
148
- *
149
- * @see https://github.com/stacksgov/sips/pull/70
150
- *
151
- * @returns A randomly generated SIP-X nonce.
152
- */
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
+ */
153
152
  declare function generateSiwsNonce(): string;
154
-
155
153
  //#endregion
156
154
  //#region src/validateSiwsMessage.d.ts
157
155
  type ValidateSiwsMessageParameters = {
158
156
  /**
159
- * Stacks address to check against.
160
- */
157
+ * Stacks address to check against.
158
+ */
161
159
  address?: string | undefined;
162
160
  /**
163
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.
164
- */
161
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.
162
+ */
165
163
  domain?: string | undefined;
166
164
  /**
167
- * SIP-X message fields.
168
- */
165
+ * SIP-X message fields.
166
+ */
169
167
  message: ExactPartial<SiwsMessage>;
170
168
  /**
171
- * Random string to check against.
172
- */
169
+ * Random string to check against.
170
+ */
173
171
  nonce?: string | undefined;
174
172
  /**
175
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.
176
- */
173
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.
174
+ */
177
175
  scheme?: string | undefined;
178
176
  /**
179
- * Current time to check optional `expirationTime` and `notBefore` fields.
180
- *
181
- * @default new Date()
182
- */
177
+ * Current time to check optional `expirationTime` and `notBefore` fields.
178
+ *
179
+ * @default new Date()
180
+ */
183
181
  time?: Date | undefined;
184
182
  };
185
183
  type ValidateSiwsMessageReturnType = boolean;
186
184
  /**
187
- * @description Validates SIP-X message.
188
- *
189
- * @see https://github.com/stacksgov/sips/pull/70
190
- */
185
+ * @description Validates SIP-X message.
186
+ *
187
+ * @see https://github.com/stacksgov/sips/pull/70
188
+ */
191
189
  declare function validateSiwsMessage(parameters: ValidateSiwsMessageParameters): ValidateSiwsMessageReturnType;
192
-
193
190
  //#endregion
194
191
  //#region src/verifySiwsMessage.d.ts
195
192
  type VerifySiwsMessageParameters = Prettify<Pick<ValidateSiwsMessageParameters, "address" | "domain" | "nonce" | "scheme" | "time"> & {
196
193
  /**
197
- * SIP-X formatted message.
198
- */
194
+ * SIP-X formatted message.
195
+ */
199
196
  message: string;
200
197
  /**
201
- * Signature to check against.
202
- */
198
+ * Signature to check against.
199
+ */
203
200
  signature: string;
204
201
  }>;
205
202
  type VerifySiwsMessageReturnType = boolean;
206
203
  /**
207
- * Verifies [SIP-X](https://github.com/stacksgov/sips/pull/70) formatted message was signed.
208
- *
209
- * @param parameters - {@link VerifySiwsMessageParameters}
210
- * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}
211
- */
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
+ */
212
209
  declare function verifySiwsMessage(parameters: VerifySiwsMessageParameters): VerifySiwsMessageReturnType;
213
-
214
210
  //#endregion
215
- export { CreateSiwsMessageErrorType, CreateSiwsMessageParameters, CreateSiwsMessageReturnType, ValidateSiwsMessageParameters, ValidateSiwsMessageReturnType, VerifySiwsMessageParameters, VerifySiwsMessageReturnType, createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
211
+ export { type CreateSiwsMessageErrorType, type CreateSiwsMessageParameters, type CreateSiwsMessageReturnType, type ValidateSiwsMessageParameters, type ValidateSiwsMessageReturnType, type VerifySiwsMessageParameters, type VerifySiwsMessageReturnType, createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
216
212
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -124,7 +124,7 @@ function getAddress(address) {
124
124
  * @see https://github.com/stacksgov/sips/pull/70
125
125
  */
126
126
  function createSiwsMessage(parameters) {
127
- const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version } = parameters;
127
+ const { chainId, domain, expirationTime, issuedAt = /* @__PURE__ */ new Date(), nonce, notBefore, requestId, resources, scheme, uri, version } = parameters;
128
128
  {
129
129
  if (chainId !== Math.floor(chainId)) throw new SiwsInvalidMessageFieldError({
130
130
  field: "chainId",
@@ -179,26 +179,24 @@ function createSiwsMessage(parameters) {
179
179
  `Provided value: ${scheme}`
180
180
  ]
181
181
  });
182
- const statement$1 = parameters.statement;
183
- if (statement$1?.includes("\n")) throw new SiwsInvalidMessageFieldError({
182
+ const statement = parameters.statement;
183
+ if (statement?.includes("\n")) throw new SiwsInvalidMessageFieldError({
184
184
  field: "statement",
185
185
  metaMessages: [
186
186
  "- Statement must not include '\\n'.",
187
187
  "",
188
- `Provided value: ${statement$1}`
188
+ `Provided value: ${statement}`
189
189
  ]
190
190
  });
191
191
  }
192
192
  const address = getAddress(parameters.address);
193
- const origin = (() => {
193
+ const prefix = `${(() => {
194
194
  if (scheme) return `${scheme}://${domain}`;
195
195
  return domain;
196
- })();
197
- const statement = (() => {
196
+ })()} wants you to sign in with your Stacks account:\n${address}\n\n${(() => {
198
197
  if (!parameters.statement) return "";
199
198
  return `${parameters.statement}\n`;
200
- })();
201
- const prefix = `${origin} wants you to sign in with your Stacks account:\n${address}\n\n${statement}`;
199
+ })()}`;
202
200
  let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}\nNonce: ${nonce}\nIssued At: ${issuedAt.toISOString()}`;
203
201
  if (expirationTime) suffix += `\nExpiration Time: ${expirationTime.toISOString()}`;
204
202
  if (notBefore) suffix += `\nNot Before: ${notBefore.toISOString()}`;
@@ -262,7 +260,7 @@ function generateSiwsNonce() {
262
260
  * @see https://github.com/stacksgov/sips/pull/70
263
261
  */
264
262
  function validateSiwsMessage(parameters) {
265
- const { address, domain, message, nonce, scheme, time = new Date() } = parameters;
263
+ const { address, domain, message, nonce, scheme, time = /* @__PURE__ */ new Date() } = parameters;
266
264
  if (domain && message.domain !== domain) return false;
267
265
  if (nonce && message.nonce !== nonce) return false;
268
266
  if (scheme && message.scheme !== scheme) return false;
@@ -287,8 +285,8 @@ function validateSiwsMessage(parameters) {
287
285
  * @returns SIP-X fields object
288
286
  */
289
287
  function parseSiwsMessage(message) {
290
- const { scheme, statement,...prefix } = message.match(prefixRegex)?.groups ?? {};
291
- const { chainId, expirationTime, issuedAt, notBefore, requestId,...suffix } = message.match(suffixRegex)?.groups ?? {};
288
+ const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {};
289
+ const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {};
292
290
  const resources = message.split("Resources:")[1]?.split("\n- ").slice(1);
293
291
  return {
294
292
  ...prefix,
@@ -315,29 +313,26 @@ const suffixRegex = /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain
315
313
  * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}
316
314
  */
317
315
  function verifySiwsMessage(parameters) {
318
- const { address, domain, message, nonce, scheme, signature, time = new Date() } = parameters;
316
+ const { address, domain, message, nonce, scheme, signature, time = /* @__PURE__ */ new Date() } = parameters;
319
317
  const parsed = parseSiwsMessage(message);
320
318
  if (!parsed.address) return false;
321
319
  if (!parsed.chainId) return false;
322
- const isValid = validateSiwsMessage({
320
+ if (!validateSiwsMessage({
323
321
  address,
324
322
  domain,
325
323
  message: parsed,
326
324
  nonce,
327
325
  scheme,
328
326
  time
329
- });
330
- if (!isValid) return false;
327
+ })) return false;
331
328
  const stacksSignature = createMessageSignature(signature);
332
- const hash = hashMessage(message);
333
- const publicKey = publicKeyFromSignatureRsv(bytesToHex(hash), stacksSignature.data);
329
+ const publicKey = publicKeyFromSignatureRsv(bytesToHex(hashMessage(message)), stacksSignature.data);
334
330
  const stacksAddress = publicKeyToAddress(publicKey, parsed.chainId === STACKS_MAINNET.chainId ? "mainnet" : "testnet");
335
- const isValidSignature = verifyMessageSignatureRsv({
331
+ return verifyMessageSignatureRsv({
336
332
  signature,
337
333
  message,
338
334
  publicKey
339
- });
340
- return isValidSignature && stacksAddress === parsed.address;
335
+ }) && stacksAddress === parsed.address;
341
336
  }
342
337
 
343
338
  //#endregion
package/dist/index.js.map CHANGED
@@ -1 +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) {\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) {\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) {\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,OA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AO,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"}
1
+ {"version":3,"file":"index.js","names":["errorConfig: ErrorConfig","buffer: string"],"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,aAAa,EACX,aACA,WAAW,IACX,eAEA,WACI,GAAG,eAAe,oBAAoB,WACpC,WAAW,IAAI,aAAa,OAE9B,QACP;AAiBD,IAAa,YAAb,MAAa,kBAAkB,MAAM;CACnC;CACA;CACA;CACA;CAEA,AAAS,OAAO;CAEhB,YAAY,cAAsB,OAA4B,EAAE,EAAE;EAChE,MAAM,iBAAiB;AACrB,OAAI,KAAK,iBAAiB,UAAW,QAAO,KAAK,MAAM;AACvD,OAAI,KAAK,OAAO,QAAS,QAAO,KAAK,MAAM;AAC3C,UAAO,KAAK;MACV;EACJ,MAAM,kBAAkB;AACtB,OAAI,KAAK,iBAAiB,UACxB,QAAO,KAAK,MAAM,YAAY,KAAK;AACrC,UAAO,KAAK;MACV;EACJ,MAAM,UAAU,YAAY,aAAa;GAAE,GAAG;GAAM;GAAU,CAAC;EAE/D,MAAM,UAAU;GACd,gBAAgB;GAChB;GACA,GAAI,KAAK,eAA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AAO"}
package/package.json CHANGED
@@ -1,29 +1,40 @@
1
1
  {
2
2
  "name": "sign-in-with-stacks",
3
- "version": "0.1.1",
3
+ "version": "0.1.4",
4
+ "license": "MIT",
5
+ "repository": "pradel/sign-in-with-stacks",
6
+ "funding": "https://github.com/sponsors/pradel",
4
7
  "type": "module",
8
+ "sideEffects": false,
5
9
  "publishConfig": {
6
- "access": "public"
10
+ "access": "public",
11
+ "provenance": true
7
12
  },
8
13
  "main": "dist/index.js",
9
14
  "types": "dist/index.d.ts",
10
15
  "exports": {
11
16
  ".": {
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.js"
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
14
19
  },
15
20
  "./package.json": "./package.json"
16
21
  },
22
+ "files": [
23
+ "dist",
24
+ "src/**/*.ts",
25
+ "!src/**/*.test.ts"
26
+ ],
17
27
  "devDependencies": {
18
- "@changesets/cli": "2.29.4",
19
- "@stacks/encryption": "7.0.6",
20
- "@stacks/network": "7.0.2",
21
- "@stacks/transactions": "7.0.6",
22
- "@tsconfig/recommended": "1.0.8",
23
- "@types/node": "22.15.21",
24
- "tsdown": "0.12.3",
25
- "typescript": "5.8.3",
26
- "vitest": "3.1.4"
28
+ "@changesets/cli": "2.29.7",
29
+ "@stacks/encryption": "7.3.0",
30
+ "@stacks/network": "7.2.0",
31
+ "@stacks/transactions": "7.3.0",
32
+ "@tsconfig/recommended": "1.0.13",
33
+ "@types/node": "24.10.1",
34
+ "publint": "0.3.15",
35
+ "tsdown": "0.16.4",
36
+ "typescript": "5.9.3",
37
+ "vitest": "4.0.9"
27
38
  },
28
39
  "peerDependencies": {
29
40
  "@stacks/common": "^7.0.2",
@@ -34,7 +45,8 @@
34
45
  "scripts": {
35
46
  "build": "tsdown",
36
47
  "test": "vitest",
37
- "typecheck": "tsc --noEmit",
38
- "release": "pnpm publish -r"
48
+ "check-types": "tsc --noEmit",
49
+ "version": "changeset version",
50
+ "release": "changeset publish"
39
51
  }
40
52
  }
@@ -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
  )!;
@@ -1,8 +0,0 @@
1
- # Changesets
2
-
3
- Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
4
- with multi-package repos, or single-package repos to help you version and publish your code. You can
5
- find the full documentation for it [in our repository](https://github.com/changesets/changesets)
6
-
7
- We have a quick list of common questions to get you started engaging with this project in
8
- [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
@@ -1,11 +0,0 @@
1
- {
2
- "$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
3
- "changelog": "@changesets/cli/changelog",
4
- "commit": false,
5
- "fixed": [],
6
- "linked": [],
7
- "access": "restricted",
8
- "baseBranch": "main",
9
- "updateInternalDependencies": "patch",
10
- "ignore": []
11
- }