sign-in-with-stacks 0.1.6 → 0.2.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.
@@ -0,0 +1,217 @@
1
+ import { r as generateSiwsNonce, t as verifySiwsMessage } from "./src-BEYJw2bv.js";
2
+ import { APIError, createAuthEndpoint } from "better-auth/api";
3
+ import { setSessionCookie } from "better-auth/cookies";
4
+ import z from "zod";
5
+
6
+ //#region src/plugins/better-auth/schema.ts
7
+ const schema = { walletAddress: { fields: {
8
+ userId: {
9
+ type: "string",
10
+ references: {
11
+ model: "user",
12
+ field: "id"
13
+ },
14
+ required: true
15
+ },
16
+ address: {
17
+ type: "string",
18
+ required: true
19
+ },
20
+ chainId: {
21
+ type: "number",
22
+ required: true
23
+ },
24
+ isPrimary: {
25
+ type: "boolean",
26
+ defaultValue: false
27
+ },
28
+ createdAt: {
29
+ type: "date",
30
+ required: true
31
+ }
32
+ } } };
33
+
34
+ //#endregion
35
+ //#region src/plugins/better-auth/plugin.ts
36
+ const siws = (options) => ({
37
+ id: "sign-in-with-stacks",
38
+ schema,
39
+ endpoints: {
40
+ nonce: createAuthEndpoint("/siws/nonce", {
41
+ method: "POST",
42
+ body: z.object({
43
+ walletAddress: z.string(),
44
+ chainId: z.number().int().positive().max(2147483647).optional().default(1)
45
+ })
46
+ }, async (ctx) => {
47
+ const { walletAddress, chainId } = ctx.body;
48
+ const nonce = options.getNonce ? await options.getNonce() : generateSiwsNonce();
49
+ await ctx.context.internalAdapter.createVerificationValue({
50
+ identifier: `siws:${walletAddress.toLowerCase()}:${chainId}`,
51
+ value: nonce,
52
+ expiresAt: new Date(Date.now() + 900 * 1e3)
53
+ });
54
+ return ctx.json({ nonce });
55
+ }),
56
+ verify: createAuthEndpoint("/siws/verify", {
57
+ method: "POST",
58
+ body: z.object({
59
+ walletAddress: z.string().min(1),
60
+ message: z.string().min(1),
61
+ signature: z.string().min(1),
62
+ chainId: z.number().int().positive().max(2147483647).optional().default(1),
63
+ email: z.email().optional()
64
+ }).refine((data) => options.anonymous !== false || !!data.email, {
65
+ message: "Email is required when the anonymous plugin option is disabled.",
66
+ path: ["email"]
67
+ }),
68
+ requireRequest: true
69
+ }, async (ctx) => {
70
+ const { walletAddress, message, signature, chainId, email } = ctx.body;
71
+ const isAnon = options.anonymous ?? true;
72
+ if (!isAnon && !email) throw new APIError("BAD_REQUEST", {
73
+ message: "Email is required when anonymous is disabled.",
74
+ status: 400
75
+ });
76
+ try {
77
+ const verification = await ctx.context.internalAdapter.findVerificationValue(`siws:${walletAddress.toLowerCase()}:${chainId}`);
78
+ if (!verification || /* @__PURE__ */ new Date() > verification.expiresAt) throw new APIError("UNAUTHORIZED", {
79
+ message: "Unauthorized: Invalid or expired nonce",
80
+ status: 401,
81
+ code: "UNAUTHORIZED_INVALID_OR_EXPIRED_NONCE"
82
+ });
83
+ const { value: nonce } = verification;
84
+ if (!verifySiwsMessage({
85
+ message,
86
+ signature,
87
+ address: walletAddress,
88
+ domain: options.domain,
89
+ nonce
90
+ })) throw new APIError("UNAUTHORIZED", {
91
+ message: "Unauthorized: Invalid SIWS signature",
92
+ status: 401
93
+ });
94
+ await ctx.context.internalAdapter.deleteVerificationValue(verification.id);
95
+ let user = null;
96
+ const existingWalletAddress = await ctx.context.adapter.findOne({
97
+ model: "walletAddress",
98
+ where: [{
99
+ field: "address",
100
+ operator: "eq",
101
+ value: walletAddress
102
+ }, {
103
+ field: "chainId",
104
+ operator: "eq",
105
+ value: chainId
106
+ }]
107
+ });
108
+ if (existingWalletAddress) user = await ctx.context.adapter.findOne({
109
+ model: "user",
110
+ where: [{
111
+ field: "id",
112
+ operator: "eq",
113
+ value: existingWalletAddress.userId
114
+ }]
115
+ });
116
+ else {
117
+ const anyWalletAddress = await ctx.context.adapter.findOne({
118
+ model: "walletAddress",
119
+ where: [{
120
+ field: "address",
121
+ operator: "eq",
122
+ value: walletAddress
123
+ }]
124
+ });
125
+ if (anyWalletAddress) user = await ctx.context.adapter.findOne({
126
+ model: "user",
127
+ where: [{
128
+ field: "id",
129
+ operator: "eq",
130
+ value: anyWalletAddress.userId
131
+ }]
132
+ });
133
+ }
134
+ if (!user) {
135
+ const domain = options.emailDomainName ?? getOrigin(ctx.context.baseURL);
136
+ const userEmail = !isAnon && email ? email : `${walletAddress}@${domain}`;
137
+ user = await ctx.context.internalAdapter.createUser({
138
+ name: walletAddress,
139
+ email: userEmail
140
+ });
141
+ await ctx.context.adapter.create({
142
+ model: "walletAddress",
143
+ data: {
144
+ userId: user.id,
145
+ address: walletAddress,
146
+ chainId,
147
+ isPrimary: true,
148
+ createdAt: /* @__PURE__ */ new Date()
149
+ }
150
+ });
151
+ await ctx.context.internalAdapter.createAccount({
152
+ userId: user.id,
153
+ providerId: "siws",
154
+ accountId: `${walletAddress}:${chainId}`,
155
+ createdAt: /* @__PURE__ */ new Date(),
156
+ updatedAt: /* @__PURE__ */ new Date()
157
+ });
158
+ } else if (!existingWalletAddress) {
159
+ await ctx.context.adapter.create({
160
+ model: "walletAddress",
161
+ data: {
162
+ userId: user.id,
163
+ address: walletAddress,
164
+ chainId,
165
+ isPrimary: false,
166
+ createdAt: /* @__PURE__ */ new Date()
167
+ }
168
+ });
169
+ await ctx.context.internalAdapter.createAccount({
170
+ userId: user.id,
171
+ providerId: "siws",
172
+ accountId: `${walletAddress}:${chainId}`,
173
+ createdAt: /* @__PURE__ */ new Date(),
174
+ updatedAt: /* @__PURE__ */ new Date()
175
+ });
176
+ }
177
+ const session = await ctx.context.internalAdapter.createSession(user.id);
178
+ if (!session) throw new APIError("INTERNAL_SERVER_ERROR", {
179
+ message: "Internal Server Error",
180
+ status: 500
181
+ });
182
+ await setSessionCookie(ctx, {
183
+ session,
184
+ user
185
+ });
186
+ return ctx.json({
187
+ token: session.token,
188
+ success: true,
189
+ user: {
190
+ id: user.id,
191
+ walletAddress,
192
+ chainId
193
+ }
194
+ });
195
+ } catch (error) {
196
+ if (error instanceof APIError) throw error;
197
+ throw new APIError("UNAUTHORIZED", {
198
+ message: "Something went wrong. Please try again later.",
199
+ error: error instanceof Error ? error.message : "Unknown error",
200
+ status: 401
201
+ });
202
+ }
203
+ })
204
+ }
205
+ });
206
+ function getOrigin(url) {
207
+ try {
208
+ const parsedUrl = new URL(url);
209
+ return parsedUrl.origin === "null" ? null : parsedUrl.origin;
210
+ } catch (error) {
211
+ return null;
212
+ }
213
+ }
214
+
215
+ //#endregion
216
+ export { siws as t };
217
+ //# sourceMappingURL=better-auth-Cfrf-ACw.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"better-auth-Cfrf-ACw.js","names":["user: User | null","existingWalletAddress: WalletAddress | null","anyWalletAddress: WalletAddress | null"],"sources":["../src/plugins/better-auth/schema.ts","../src/plugins/better-auth/plugin.ts"],"sourcesContent":["import type { BetterAuthPluginDBSchema } from \"better-auth/db\";\n\nexport const schema = {\n walletAddress: {\n fields: {\n userId: {\n type: \"string\",\n references: {\n model: \"user\",\n field: \"id\",\n },\n required: true,\n },\n address: {\n type: \"string\",\n required: true,\n },\n chainId: {\n type: \"number\",\n required: true,\n },\n isPrimary: {\n type: \"boolean\",\n defaultValue: false,\n },\n createdAt: {\n type: \"date\",\n required: true,\n },\n },\n },\n} satisfies BetterAuthPluginDBSchema;\n","import type { BetterAuthPlugin, User } from \"better-auth\";\nimport { APIError, createAuthEndpoint } from \"better-auth/api\";\nimport { setSessionCookie } from \"better-auth/cookies\";\nimport z from \"zod\";\nimport { generateSiwsNonce, verifySiwsMessage } from \"../../index.js\";\nimport { schema } from \"./schema.js\";\nimport type { WalletAddress } from \"./types.js\";\n\nexport interface SIWSPluginOptions {\n // The domain name of your application (required for SIWS message generation)\n domain: string;\n // The email domain name for creating user accounts when not using anonymous mode. Defaults to the domain from your base URL\n emailDomainName?: string | undefined;\n // Whether to allow anonymous sign-ins without requiring an email. Default is true\n anonymous?: boolean | undefined;\n // Function to generate a unique nonce for each sign-in attempt. You must implement this function to return a cryptographically secure random string. Must return a Promise<string>\n getNonce?: () => Promise<string>;\n}\n\nexport const siws = (options: SIWSPluginOptions) =>\n ({\n id: \"sign-in-with-stacks\",\n schema: schema,\n endpoints: {\n nonce: createAuthEndpoint(\n \"/siws/nonce\",\n {\n method: \"POST\",\n body: z.object({\n // TODO Stacks address regex\n walletAddress: z.string(),\n chainId: z\n .number()\n .int()\n .positive()\n .max(2147483647)\n .optional()\n .default(0x00000001), // Default to Stacks mainnet\n }),\n },\n async (ctx) => {\n const { walletAddress, chainId } = ctx.body;\n const nonce = options.getNonce\n ? await options.getNonce()\n : generateSiwsNonce();\n\n // Store nonce with 15-minute expiration\n await ctx.context.internalAdapter.createVerificationValue({\n identifier: `siws:${walletAddress.toLowerCase()}:${chainId}`,\n value: nonce,\n expiresAt: new Date(Date.now() + 15 * 60 * 1000),\n });\n\n return ctx.json({ nonce });\n },\n ),\n\n verify: createAuthEndpoint(\n \"/siws/verify\",\n {\n method: \"POST\",\n body: z\n .object({\n // TODO Stacks address regex\n walletAddress: z.string().min(1),\n message: z.string().min(1),\n signature: z.string().min(1),\n chainId: z\n .number()\n .int()\n .positive()\n .max(2147483647)\n .optional()\n .default(0x00000001), // Default to Stacks mainnet\n email: z.email().optional(),\n })\n .refine((data) => options.anonymous !== false || !!data.email, {\n message:\n \"Email is required when the anonymous plugin option is disabled.\",\n path: [\"email\"],\n }),\n requireRequest: true,\n },\n async (ctx) => {\n const { walletAddress, message, signature, chainId, email } =\n ctx.body;\n const isAnon = options.anonymous ?? true;\n\n if (!isAnon && !email) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Email is required when anonymous is disabled.\",\n status: 400,\n });\n }\n\n try {\n // Find stored nonce with wallet address and chain ID context\n const verification =\n await ctx.context.internalAdapter.findVerificationValue(\n `siws:${walletAddress.toLowerCase()}:${chainId}`,\n );\n\n // Ensure nonce is valid and not expired\n if (!verification || new Date() > verification.expiresAt) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Unauthorized: Invalid or expired nonce\",\n status: 401,\n code: \"UNAUTHORIZED_INVALID_OR_EXPIRED_NONCE\",\n });\n }\n\n // Verify SIWS message\n const { value: nonce } = verification;\n const valid = verifySiwsMessage({\n message,\n signature,\n address: walletAddress,\n domain: options.domain,\n nonce,\n });\n\n if (!valid) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Unauthorized: Invalid SIWS signature\",\n status: 401,\n });\n }\n\n // Clean up used nonce\n await ctx.context.internalAdapter.deleteVerificationValue(\n verification.id,\n );\n\n // Look for existing user by their wallet addresses\n let user: User | null = null;\n\n // Check if there's a wallet address record for this exact address+chainId combination\n const existingWalletAddress: WalletAddress | null =\n await ctx.context.adapter.findOne({\n model: \"walletAddress\",\n where: [\n { field: \"address\", operator: \"eq\", value: walletAddress },\n { field: \"chainId\", operator: \"eq\", value: chainId },\n ],\n });\n\n if (existingWalletAddress) {\n // Get the user associated with this wallet address\n user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"id\",\n operator: \"eq\",\n value: existingWalletAddress.userId,\n },\n ],\n });\n } else {\n // No exact match found, check if this address exists on any other chain\n const anyWalletAddress: WalletAddress | null =\n await ctx.context.adapter.findOne({\n model: \"walletAddress\",\n where: [\n { field: \"address\", operator: \"eq\", value: walletAddress },\n ],\n });\n\n if (anyWalletAddress) {\n // Same address exists on different chain, get that user\n user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"id\",\n operator: \"eq\",\n value: anyWalletAddress.userId,\n },\n ],\n });\n }\n }\n\n // Create new user if none exists\n if (!user) {\n const domain =\n options.emailDomainName ?? getOrigin(ctx.context.baseURL);\n // Use checksummed address for email generation\n const userEmail =\n !isAnon && email ? email : `${walletAddress}@${domain}`;\n\n user = await ctx.context.internalAdapter.createUser({\n name: walletAddress,\n email: userEmail,\n });\n\n // Create wallet address record\n await ctx.context.adapter.create<WalletAddress>({\n model: \"walletAddress\",\n data: {\n userId: user.id,\n address: walletAddress,\n chainId,\n isPrimary: true, // First address is primary\n createdAt: new Date(),\n },\n });\n\n // Create account record for wallet authentication\n await ctx.context.internalAdapter.createAccount({\n userId: user.id,\n providerId: \"siws\",\n accountId: `${walletAddress}:${chainId}`,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n } else {\n // User exists, but check if this specific address/chain combo exists\n if (!existingWalletAddress) {\n // Add this new chainId to existing user's addresses\n await ctx.context.adapter.create({\n model: \"walletAddress\",\n data: {\n userId: user.id,\n address: walletAddress,\n chainId,\n isPrimary: false, // Additional addresses are not primary by default\n createdAt: new Date(),\n },\n });\n\n // Create account record for this new wallet+chain combination\n await ctx.context.internalAdapter.createAccount({\n userId: user.id,\n providerId: \"siws\",\n accountId: `${walletAddress}:${chainId}`,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n }\n }\n\n const session = await ctx.context.internalAdapter.createSession(\n user.id,\n );\n\n if (!session) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Internal Server Error\",\n status: 500,\n });\n }\n\n await setSessionCookie(ctx, { session, user });\n\n return ctx.json({\n token: session.token,\n success: true,\n user: {\n id: user.id,\n walletAddress,\n chainId,\n },\n });\n } catch (error) {\n if (error instanceof APIError) throw error;\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Something went wrong. Please try again later.\",\n error: error instanceof Error ? error.message : \"Unknown error\",\n status: 401,\n });\n }\n },\n ),\n },\n }) satisfies BetterAuthPlugin;\n\nfunction getOrigin(url: string) {\n try {\n const parsedUrl = new URL(url);\n // For custom URL schemes (like exp://), the origin property returns the string \"null\"\n // instead of null. We need to handle this case and return null so the fallback logic works.\n return parsedUrl.origin === \"null\" ? null : parsedUrl.origin;\n } catch (error) {\n return null;\n }\n}\n"],"mappings":";;;;;;AAEA,MAAa,SAAS,EACpB,eAAe,EACb,QAAQ;CACN,QAAQ;EACN,MAAM;EACN,YAAY;GACV,OAAO;GACP,OAAO;GACR;EACD,UAAU;EACX;CACD,SAAS;EACP,MAAM;EACN,UAAU;EACX;CACD,SAAS;EACP,MAAM;EACN,UAAU;EACX;CACD,WAAW;EACT,MAAM;EACN,cAAc;EACf;CACD,WAAW;EACT,MAAM;EACN,UAAU;EACX;CACF,EACF,EACF;;;;ACZD,MAAa,QAAQ,aAClB;CACC,IAAI;CACI;CACR,WAAW;EACT,OAAO,mBACL,eACA;GACE,QAAQ;GACR,MAAM,EAAE,OAAO;IAEb,eAAe,EAAE,QAAQ;IACzB,SAAS,EACN,QAAQ,CACR,KAAK,CACL,UAAU,CACV,IAAI,WAAW,CACf,UAAU,CACV,QAAQ,EAAW;IACvB,CAAC;GACH,EACD,OAAO,QAAQ;GACb,MAAM,EAAE,eAAe,YAAY,IAAI;GACvC,MAAM,QAAQ,QAAQ,WAClB,MAAM,QAAQ,UAAU,GACxB,mBAAmB;AAGvB,SAAM,IAAI,QAAQ,gBAAgB,wBAAwB;IACxD,YAAY,QAAQ,cAAc,aAAa,CAAC,GAAG;IACnD,OAAO;IACP,WAAW,IAAI,KAAK,KAAK,KAAK,GAAG,MAAU,IAAK;IACjD,CAAC;AAEF,UAAO,IAAI,KAAK,EAAE,OAAO,CAAC;IAE7B;EAED,QAAQ,mBACN,gBACA;GACE,QAAQ;GACR,MAAM,EACH,OAAO;IAEN,eAAe,EAAE,QAAQ,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,QAAQ,KAAK;MACb,YAAY;MACZ,WAAW,GAAG,cAAc,GAAG;MAC/B,2BAAW,IAAI,MAAM;MACrB,2BAAW,IAAI,MAAM;MACtB,CAAC;;IAIN,MAAM,UAAU,MAAM,IAAI,QAAQ,gBAAgB,cAChD,KAAK,GACN;AAED,QAAI,CAAC,QACH,OAAM,IAAI,SAAS,yBAAyB;KAC1C,SAAS;KACT,QAAQ;KACT,CAAC;AAGJ,UAAM,iBAAiB,KAAK;KAAE;KAAS;KAAM,CAAC;AAE9C,WAAO,IAAI,KAAK;KACd,OAAO,QAAQ;KACf,SAAS;KACT,MAAM;MACJ,IAAI,KAAK;MACT;MACA;MACD;KACF,CAAC;YACK,OAAO;AACd,QAAI,iBAAiB,SAAU,OAAM;AACrC,UAAM,IAAI,SAAS,gBAAgB;KACjC,SAAS;KACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU;KAChD,QAAQ;KACT,CAAC;;IAGP;EACF;CACF;AAEH,SAAS,UAAU,KAAa;AAC9B,KAAI;EACF,MAAM,YAAY,IAAI,IAAI,IAAI;AAG9B,SAAO,UAAU,WAAW,SAAS,OAAO,UAAU;UAC/C,OAAO;AACd,SAAO"}
@@ -0,0 +1,82 @@
1
+ import z from "zod";
2
+ import * as better_auth0 from "better-auth";
3
+
4
+ //#region src/plugins/better-auth/plugin.d.ts
5
+ interface SIWSPluginOptions {
6
+ domain: string;
7
+ emailDomainName?: string | undefined;
8
+ anonymous?: boolean | undefined;
9
+ getNonce?: () => Promise<string>;
10
+ }
11
+ declare const siws: (options: SIWSPluginOptions) => {
12
+ id: "sign-in-with-stacks";
13
+ schema: {
14
+ walletAddress: {
15
+ fields: {
16
+ userId: {
17
+ type: "string";
18
+ references: {
19
+ model: string;
20
+ field: string;
21
+ };
22
+ required: true;
23
+ };
24
+ address: {
25
+ type: "string";
26
+ required: true;
27
+ };
28
+ chainId: {
29
+ type: "number";
30
+ required: true;
31
+ };
32
+ isPrimary: {
33
+ type: "boolean";
34
+ defaultValue: false;
35
+ };
36
+ createdAt: {
37
+ type: "date";
38
+ required: true;
39
+ };
40
+ };
41
+ };
42
+ };
43
+ endpoints: {
44
+ nonce: better_auth0.StrictEndpoint<"/siws/nonce", {
45
+ method: "POST";
46
+ body: z.ZodObject<{
47
+ walletAddress: z.ZodString;
48
+ chainId: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
49
+ }, z.z.core.$strip>;
50
+ }, {
51
+ nonce: string;
52
+ }>;
53
+ verify: better_auth0.StrictEndpoint<"/siws/verify", {
54
+ method: "POST";
55
+ body: z.ZodObject<{
56
+ walletAddress: z.ZodString;
57
+ message: z.ZodString;
58
+ signature: z.ZodString;
59
+ chainId: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
60
+ email: z.ZodOptional<z.ZodEmail>;
61
+ }, z.z.core.$strip>;
62
+ requireRequest: true;
63
+ }, {
64
+ token: string;
65
+ success: boolean;
66
+ user: {
67
+ id: string;
68
+ walletAddress: string;
69
+ chainId: number;
70
+ };
71
+ }>;
72
+ };
73
+ };
74
+ //#endregion
75
+ //#region src/plugins/better-auth/client.d.ts
76
+ declare const siwsClient: () => {
77
+ id: "siws";
78
+ $InferServerPlugin: ReturnType<typeof siws>;
79
+ };
80
+ //#endregion
81
+ export { SIWSPluginOptions as n, siws as r, siwsClient as t };
82
+ //# sourceMappingURL=client-DiW-Aqpm.d.ts.map
@@ -0,0 +1,11 @@
1
+ //#region src/plugins/better-auth/client.ts
2
+ const siwsClient = () => {
3
+ return {
4
+ id: "siws",
5
+ $InferServerPlugin: {}
6
+ };
7
+ };
8
+
9
+ //#endregion
10
+ export { siwsClient as t };
11
+ //# sourceMappingURL=client-LJniKVEE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-LJniKVEE.js","names":[],"sources":["../src/plugins/better-auth/client.ts"],"sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type { siws } from \"./plugin.js\";\n\nexport const siwsClient = () => {\n return {\n id: \"siws\",\n $InferServerPlugin: {} as ReturnType<typeof siws>,\n } satisfies BetterAuthClientPlugin;\n};\n"],"mappings":";AAGA,MAAa,mBAAmB;AAC9B,QAAO;EACL,IAAI;EACJ,oBAAoB,EAAE;EACvB"}
package/dist/index.d.ts CHANGED
@@ -48,72 +48,72 @@ declare class SiwsInvalidMessageFieldError extends BaseError {
48
48
  //#endregion
49
49
  //#region src/types.d.ts
50
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
- */
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
58
  type Prettify<T> = { [K in keyof T]: T[K] } & {};
59
59
  type ExactPartial<type> = { [key in keyof type]?: type[key] | undefined };
60
60
  /**
61
- * @description SIP-X message fields
62
- *
63
- * @see https://github.com/stacksgov/sips/pull/70
64
- */
61
+ * @description SIP-X message fields
62
+ *
63
+ * @see https://github.com/stacksgov/sips/pull/70
64
+ */
65
65
  type SiwsMessage = {
66
66
  /**
67
- * The Stacks address performing the signing.
68
- */
67
+ * The Stacks address performing the signing.
68
+ */
69
69
  address: string;
70
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
- */
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
73
  chainId: number;
74
74
  /**
75
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
76
- */
75
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing.
76
+ */
77
77
  domain: string;
78
78
  /**
79
- * Time when the signed authentication message is no longer valid.
80
- */
79
+ * Time when the signed authentication message is no longer valid.
80
+ */
81
81
  expirationTime?: Date | undefined;
82
82
  /**
83
- * Time when the message was generated, typically the current time.
84
- */
83
+ * Time when the message was generated, typically the current time.
84
+ */
85
85
  issuedAt?: Date | undefined;
86
86
  /**
87
- * A random string typically chosen by the relying party and used to prevent replay attacks.
88
- */
87
+ * A random string typically chosen by the relying party and used to prevent replay attacks.
88
+ */
89
89
  nonce: string;
90
90
  /**
91
- * Time when the signed authentication message will become valid.
92
- */
91
+ * Time when the signed authentication message will become valid.
92
+ */
93
93
  notBefore?: Date | undefined;
94
94
  /**
95
- * A system-specific identifier that may be used to uniquely refer to the sign-in request.
96
- */
95
+ * A system-specific identifier that may be used to uniquely refer to the sign-in request.
96
+ */
97
97
  requestId?: string | undefined;
98
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
- */
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
101
  resources?: string[] | undefined;
102
102
  /**
103
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
104
- */
103
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request.
104
+ */
105
105
  scheme?: string | undefined;
106
106
  /**
107
- * A human-readable ASCII assertion that the user will sign.
108
- */
107
+ * A human-readable ASCII assertion that the user will sign.
108
+ */
109
109
  statement?: string | undefined;
110
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
- */
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
113
  uri: string;
114
114
  /**
115
- * The current version of the SIWS Message.
116
- */
115
+ * The current version of the SIWS Message.
116
+ */
117
117
  version: "1";
118
118
  };
119
119
  //#endregion
@@ -122,90 +122,90 @@ 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
140
  //#endregion
141
141
  //#region src/generateSiwsNonce.d.ts
142
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
- */
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
152
  declare function generateSiwsNonce(): string;
153
153
  //#endregion
154
154
  //#region src/validateSiwsMessage.d.ts
155
155
  type ValidateSiwsMessageParameters = {
156
156
  /**
157
- * Stacks address to check against.
158
- */
157
+ * Stacks address to check against.
158
+ */
159
159
  address?: string | undefined;
160
160
  /**
161
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.
162
- */
161
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.
162
+ */
163
163
  domain?: string | undefined;
164
164
  /**
165
- * SIP-X message fields.
166
- */
165
+ * SIP-X message fields.
166
+ */
167
167
  message: ExactPartial<SiwsMessage>;
168
168
  /**
169
- * Random string to check against.
170
- */
169
+ * Random string to check against.
170
+ */
171
171
  nonce?: string | undefined;
172
172
  /**
173
- * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.
174
- */
173
+ * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.
174
+ */
175
175
  scheme?: string | undefined;
176
176
  /**
177
- * Current time to check optional `expirationTime` and `notBefore` fields.
178
- *
179
- * @default new Date()
180
- */
177
+ * Current time to check optional `expirationTime` and `notBefore` fields.
178
+ *
179
+ * @default new Date()
180
+ */
181
181
  time?: Date | undefined;
182
182
  };
183
183
  type ValidateSiwsMessageReturnType = boolean;
184
184
  /**
185
- * @description Validates SIP-X message.
186
- *
187
- * @see https://github.com/stacksgov/sips/pull/70
188
- */
185
+ * @description Validates SIP-X message.
186
+ *
187
+ * @see https://github.com/stacksgov/sips/pull/70
188
+ */
189
189
  declare function validateSiwsMessage(parameters: ValidateSiwsMessageParameters): ValidateSiwsMessageReturnType;
190
190
  //#endregion
191
191
  //#region src/verifySiwsMessage.d.ts
192
192
  type VerifySiwsMessageParameters = Prettify<Pick<ValidateSiwsMessageParameters, "address" | "domain" | "nonce" | "scheme" | "time"> & {
193
193
  /**
194
- * SIP-X formatted message.
195
- */
194
+ * SIP-X formatted message.
195
+ */
196
196
  message: string;
197
197
  /**
198
- * Signature to check against.
199
- */
198
+ * Signature to check against.
199
+ */
200
200
  signature: string;
201
201
  }>;
202
202
  type VerifySiwsMessageReturnType = boolean;
203
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
- */
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
209
  declare function verifySiwsMessage(parameters: VerifySiwsMessageParameters): VerifySiwsMessageReturnType;
210
210
  //#endregion
211
211
  export { type CreateSiwsMessageErrorType, type CreateSiwsMessageParameters, type CreateSiwsMessageReturnType, type ValidateSiwsMessageParameters, type ValidateSiwsMessageReturnType, type VerifySiwsMessageParameters, type VerifySiwsMessageReturnType, createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };