sign-in-with-stacks 0.1.6 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  Sign-in with Stacks is a library for creating and verifying Sign-In with Stacks messages.
4
4
 
5
+ ## Documentation
6
+
7
+ [Head to the documentation](https://pradel.github.io/sign-in-with-stacks/) to read and learn more about the package.
8
+
5
9
  ## Installation
6
10
 
7
11
  ```
@@ -47,6 +51,15 @@ const valid = verifySiwsMessage({
47
51
  });
48
52
  ```
49
53
 
54
+ ## Plugins
55
+
56
+ - [better-auth plugin](./packages/sign-in-with-stacks/src/plugins/better-auth)
57
+
58
+ ## Examples
59
+
60
+ - [Next.js + better-auth](./examples/better-auth)
61
+ - [Next.js + NextAuth.js](./examples/next-auth)
62
+
50
63
  ## Credits
51
64
 
52
65
  The first version of this library is a port of the view siwe implementation.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  //#region src/errors/base.d.ts
2
-
3
2
  type BaseErrorParameters = {
4
3
  cause?: BaseError | Error | undefined;
5
4
  details?: string | undefined;
@@ -48,72 +47,72 @@ declare class SiwsInvalidMessageFieldError extends BaseError {
48
47
  //#endregion
49
48
  //#region src/types.d.ts
50
49
  /**
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
- */
50
+ * @description Combines members of an intersection into a readable type.
51
+ *
52
+ * @see {@link https://twitter.com/mattpocockuk/status/1622730173446557697?s=20&t=NdpAcmEFXY01xkqU3KO0Mg}
53
+ * @example
54
+ * Prettify<{ a: string } & { b: string } & { c: number, d: bigint }>
55
+ * => { a: string, b: string, c: number, d: bigint }
56
+ */
58
57
  type Prettify<T> = { [K in keyof T]: T[K] } & {};
59
58
  type ExactPartial<type> = { [key in keyof type]?: type[key] | undefined };
60
59
  /**
61
- * @description SIP-X message fields
62
- *
63
- * @see https://github.com/stacksgov/sips/pull/70
64
- */
60
+ * @description SIP-X message fields
61
+ *
62
+ * @see https://github.com/stacksgov/sips/pull/70
63
+ */
65
64
  type SiwsMessage = {
66
65
  /**
67
- * The Stacks address performing the signing.
68
- */
66
+ * The Stacks address performing the signing.
67
+ */
69
68
  address: string;
70
69
  /**
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
- */
70
+ * 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,
71
+ */
73
72
  chainId: number;
74
73
  /**
75
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
76
- */
74
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
75
+ */
77
76
  domain: string;
78
77
  /**
79
- * Time when the signed authentication message is no longer valid.
80
- */
78
+ * Time when the signed authentication message is no longer valid.
79
+ */
81
80
  expirationTime?: Date | undefined;
82
81
  /**
83
- * Time when the message was generated, typically the current time.
84
- */
82
+ * Time when the message was generated, typically the current time.
83
+ */
85
84
  issuedAt?: Date | undefined;
86
85
  /**
87
- * A random string typically chosen by the relying party and used to prevent replay attacks.
88
- */
86
+ * A random string typically chosen by the relying party and used to prevent replay attacks.
87
+ */
89
88
  nonce: string;
90
89
  /**
91
- * Time when the signed authentication message will become valid.
92
- */
90
+ * Time when the signed authentication message will become valid.
91
+ */
93
92
  notBefore?: Date | undefined;
94
93
  /**
95
- * A system-specific identifier that may be used to uniquely refer to the sign-in request.
96
- */
94
+ * A system-specific identifier that may be used to uniquely refer to the sign-in request.
95
+ */
97
96
  requestId?: string | undefined;
98
97
  /**
99
- * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party.
100
- */
98
+ * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party.
99
+ */
101
100
  resources?: string[] | undefined;
102
101
  /**
103
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
104
- */
102
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
103
+ */
105
104
  scheme?: string | undefined;
106
105
  /**
107
- * A human-readable ASCII assertion that the user will sign.
108
- */
106
+ * A human-readable ASCII assertion that the user will sign.
107
+ */
109
108
  statement?: string | undefined;
110
109
  /**
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
- */
110
+ * [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).
111
+ */
113
112
  uri: string;
114
113
  /**
115
- * The current version of the SIWS Message.
116
- */
114
+ * The current version of the SIWS Message.
115
+ */
117
116
  version: "1";
118
117
  };
119
118
  //#endregion
@@ -122,90 +121,90 @@ type CreateSiwsMessageParameters = SiwsMessage;
122
121
  type CreateSiwsMessageReturnType = string;
123
122
  type CreateSiwsMessageErrorType = InvalidAddressErrorType | SiwsInvalidMessageFieldErrorType;
124
123
  /**
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
- */
124
+ * @description Creates SIP-X formatted message.
125
+ *
126
+ * @example
127
+ * const message = createMessage({
128
+ * address: 'SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173',
129
+ * chainId: 1,
130
+ * domain: 'example.com',
131
+ * nonce: 'foobarbaz',
132
+ * uri: 'https://example.com/path',
133
+ * version: '1',
134
+ * })
135
+ *
136
+ * @see https://github.com/stacksgov/sips/pull/70
137
+ */
139
138
  declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): CreateSiwsMessageReturnType;
140
139
  //#endregion
141
140
  //#region src/generateSiwsNonce.d.ts
142
141
  /**
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
- */
142
+ * @description Generates random SIP-X nonce.
143
+ *
144
+ * @example
145
+ * const nonce = generateNonce()
146
+ *
147
+ * @see https://github.com/stacksgov/sips/pull/70
148
+ *
149
+ * @returns A randomly generated SIP-X nonce.
150
+ */
152
151
  declare function generateSiwsNonce(): string;
153
152
  //#endregion
154
153
  //#region src/validateSiwsMessage.d.ts
155
154
  type ValidateSiwsMessageParameters = {
156
155
  /**
157
- * Stacks address to check against.
158
- */
156
+ * Stacks address to check against.
157
+ */
159
158
  address?: string | undefined;
160
159
  /**
161
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.
162
- */
160
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.
161
+ */
163
162
  domain?: string | undefined;
164
163
  /**
165
- * SIP-X message fields.
166
- */
164
+ * SIP-X message fields.
165
+ */
167
166
  message: ExactPartial<SiwsMessage>;
168
167
  /**
169
- * Random string to check against.
170
- */
168
+ * Random string to check against.
169
+ */
171
170
  nonce?: string | undefined;
172
171
  /**
173
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.
174
- */
172
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.
173
+ */
175
174
  scheme?: string | undefined;
176
175
  /**
177
- * Current time to check optional `expirationTime` and `notBefore` fields.
178
- *
179
- * @default new Date()
180
- */
176
+ * Current time to check optional `expirationTime` and `notBefore` fields.
177
+ *
178
+ * @default new Date()
179
+ */
181
180
  time?: Date | undefined;
182
181
  };
183
182
  type ValidateSiwsMessageReturnType = boolean;
184
183
  /**
185
- * @description Validates SIP-X message.
186
- *
187
- * @see https://github.com/stacksgov/sips/pull/70
188
- */
184
+ * @description Validates SIP-X message.
185
+ *
186
+ * @see https://github.com/stacksgov/sips/pull/70
187
+ */
189
188
  declare function validateSiwsMessage(parameters: ValidateSiwsMessageParameters): ValidateSiwsMessageReturnType;
190
189
  //#endregion
191
190
  //#region src/verifySiwsMessage.d.ts
192
191
  type VerifySiwsMessageParameters = Prettify<Pick<ValidateSiwsMessageParameters, "address" | "domain" | "nonce" | "scheme" | "time"> & {
193
192
  /**
194
- * SIP-X formatted message.
195
- */
193
+ * SIP-X formatted message.
194
+ */
196
195
  message: string;
197
196
  /**
198
- * Signature to check against.
199
- */
197
+ * Signature to check against.
198
+ */
200
199
  signature: string;
201
200
  }>;
202
201
  type VerifySiwsMessageReturnType = boolean;
203
202
  /**
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
- */
203
+ * Verifies [SIP-X](https://github.com/stacksgov/sips/pull/70) formatted message was signed.
204
+ *
205
+ * @param parameters - {@link VerifySiwsMessageParameters}
206
+ * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}
207
+ */
209
208
  declare function verifySiwsMessage(parameters: VerifySiwsMessageParameters): VerifySiwsMessageReturnType;
210
209
  //#endregion
211
210
  export { type CreateSiwsMessageErrorType, type CreateSiwsMessageParameters, type CreateSiwsMessageReturnType, type ValidateSiwsMessageParameters, type ValidateSiwsMessageReturnType, type VerifySiwsMessageParameters, type VerifySiwsMessageReturnType, createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
package/dist/index.js CHANGED
@@ -1,340 +1,3 @@
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";
1
+ import { i as createSiwsMessage, n as validateSiwsMessage, r as generateSiwsNonce, t as verifySiwsMessage } from "./verifySiwsMessage-j433CJQY.js";
5
2
 
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 = parameters.statement;
183
- if (statement?.includes("\n")) throw new SiwsInvalidMessageFieldError({
184
- field: "statement",
185
- metaMessages: [
186
- "- Statement must not include '\\n'.",
187
- "",
188
- `Provided value: ${statement}`
189
- ]
190
- });
191
- }
192
- const address = getAddress(parameters.address);
193
- const prefix = `${(() => {
194
- if (scheme) return `${scheme}://${domain}`;
195
- return domain;
196
- })()} wants you to sign in with your Stacks account:\n${address}\n\n${(() => {
197
- if (!parameters.statement) return "";
198
- return `${parameters.statement}\n`;
199
- })()}`;
200
- let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}\nNonce: ${nonce}\nIssued At: ${issuedAt.toISOString()}`;
201
- if (expirationTime) suffix += `\nExpiration Time: ${expirationTime.toISOString()}`;
202
- if (notBefore) suffix += `\nNot Before: ${notBefore.toISOString()}`;
203
- if (requestId) suffix += `\nRequest ID: ${requestId}`;
204
- if (resources) {
205
- let content = "\nResources:";
206
- for (const resource of resources) {
207
- if (!isUri(resource)) throw new SiwsInvalidMessageFieldError({
208
- field: "resources",
209
- metaMessages: [
210
- "- Every resource must be a RFC 3986 URI.",
211
- "- See https://www.rfc-editor.org/rfc/rfc3986",
212
- "",
213
- `Provided value: ${resource}`
214
- ]
215
- });
216
- content += `\n- ${resource}`;
217
- }
218
- suffix += content;
219
- }
220
- return `${prefix}\n${suffix}`;
221
- }
222
- const domainRegex = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?$/;
223
- 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})?$/;
224
- const localhostRegex = /^localhost(:[0-9]{1,5})?$/;
225
- const nonceRegex = /^[a-zA-Z0-9]{8,}$/;
226
- const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/;
227
-
228
- //#endregion
229
- //#region src/generateSiwsNonce.ts
230
- const size = 256;
231
- let index = size;
232
- let buffer;
233
- function uid(length = 11) {
234
- if (!buffer || index + length > size * 2) {
235
- buffer = "";
236
- index = 0;
237
- for (let i = 0; i < size; i++) buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1);
238
- }
239
- return buffer.substring(index, index++ + length);
240
- }
241
- /**
242
- * @description Generates random SIP-X nonce.
243
- *
244
- * @example
245
- * const nonce = generateNonce()
246
- *
247
- * @see https://github.com/stacksgov/sips/pull/70
248
- *
249
- * @returns A randomly generated SIP-X nonce.
250
- */
251
- function generateSiwsNonce() {
252
- return uid(96);
253
- }
254
-
255
- //#endregion
256
- //#region src/validateSiwsMessage.ts
257
- /**
258
- * @description Validates SIP-X message.
259
- *
260
- * @see https://github.com/stacksgov/sips/pull/70
261
- */
262
- function validateSiwsMessage(parameters) {
263
- const { address, domain, message, nonce, scheme, time = /* @__PURE__ */ new Date() } = parameters;
264
- if (domain && message.domain !== domain) return false;
265
- if (nonce && message.nonce !== nonce) return false;
266
- if (scheme && message.scheme !== scheme) return false;
267
- if (message.expirationTime && time >= message.expirationTime) return false;
268
- if (message.notBefore && time < message.notBefore) return false;
269
- try {
270
- if (!message.address) return false;
271
- if (address && !isAddressEqual(message.address, address)) return false;
272
- } catch {
273
- return false;
274
- }
275
- return true;
276
- }
277
-
278
- //#endregion
279
- //#region src/parseSiwsMessage.ts
280
- /**
281
- * @description Parses SIP-X formatted message into message fields object.
282
- *
283
- * @see https://github.com/stacksgov/sips/pull/70
284
- *
285
- * @returns SIP-X fields object
286
- */
287
- function parseSiwsMessage(message) {
288
- const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {};
289
- const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {};
290
- const resources = message.split("Resources:")[1]?.split("\n- ").slice(1);
291
- return {
292
- ...prefix,
293
- ...suffix,
294
- ...chainId ? { chainId: Number(chainId) } : {},
295
- ...expirationTime ? { expirationTime: new Date(expirationTime) } : {},
296
- ...issuedAt ? { issuedAt: new Date(issuedAt) } : {},
297
- ...notBefore ? { notBefore: new Date(notBefore) } : {},
298
- ...requestId ? { requestId } : {},
299
- ...resources ? { resources } : {},
300
- ...scheme ? { scheme } : {},
301
- ...statement ? { statement } : {}
302
- };
303
- }
304
- 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)?/;
305
- 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>.+))?/;
306
-
307
- //#endregion
308
- //#region src/verifySiwsMessage.ts
309
- /**
310
- * Verifies [SIP-X](https://github.com/stacksgov/sips/pull/70) formatted message was signed.
311
- *
312
- * @param parameters - {@link VerifySiwsMessageParameters}
313
- * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}
314
- */
315
- function verifySiwsMessage(parameters) {
316
- const { address, domain, message, nonce, scheme, signature, time = /* @__PURE__ */ new Date() } = parameters;
317
- const parsed = parseSiwsMessage(message);
318
- if (!parsed.address) return false;
319
- if (!parsed.chainId) return false;
320
- if (!validateSiwsMessage({
321
- address,
322
- domain,
323
- message: parsed,
324
- nonce,
325
- scheme,
326
- time
327
- })) return false;
328
- const stacksSignature = createMessageSignature(signature);
329
- const publicKey = publicKeyFromSignatureRsv(bytesToHex(hashMessage(message)), stacksSignature.data);
330
- const stacksAddress = publicKeyToAddress(publicKey, parsed.chainId === STACKS_MAINNET.chainId ? "mainnet" : "testnet");
331
- return verifyMessageSignatureRsv({
332
- signature,
333
- message,
334
- publicKey
335
- }) && stacksAddress === parsed.address;
336
- }
337
-
338
- //#endregion
339
- export { createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
340
- //# sourceMappingURL=index.js.map
3
+ export { createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };