@depup/supabase__auth-js 2.99.2-depup.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.
Files changed (195) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +25 -0
  3. package/changes.json +5 -0
  4. package/dist/main/AuthAdminApi.d.ts +4 -0
  5. package/dist/main/AuthAdminApi.d.ts.map +1 -0
  6. package/dist/main/AuthAdminApi.js +7 -0
  7. package/dist/main/AuthAdminApi.js.map +1 -0
  8. package/dist/main/AuthClient.d.ts +4 -0
  9. package/dist/main/AuthClient.d.ts.map +1 -0
  10. package/dist/main/AuthClient.js +7 -0
  11. package/dist/main/AuthClient.js.map +1 -0
  12. package/dist/main/GoTrueAdminApi.d.ts +227 -0
  13. package/dist/main/GoTrueAdminApi.d.ts.map +1 -0
  14. package/dist/main/GoTrueAdminApi.js +596 -0
  15. package/dist/main/GoTrueAdminApi.js.map +1 -0
  16. package/dist/main/GoTrueClient.d.ts +783 -0
  17. package/dist/main/GoTrueClient.d.ts.map +1 -0
  18. package/dist/main/GoTrueClient.js +3029 -0
  19. package/dist/main/GoTrueClient.js.map +1 -0
  20. package/dist/main/index.d.ts +9 -0
  21. package/dist/main/index.d.ts.map +1 -0
  22. package/dist/main/index.js +20 -0
  23. package/dist/main/index.js.map +1 -0
  24. package/dist/main/lib/base64url.d.ts +76 -0
  25. package/dist/main/lib/base64url.d.ts.map +1 -0
  26. package/dist/main/lib/base64url.js +269 -0
  27. package/dist/main/lib/base64url.js.map +1 -0
  28. package/dist/main/lib/constants.d.ts +26 -0
  29. package/dist/main/lib/constants.d.ts.map +1 -0
  30. package/dist/main/lib/constants.js +31 -0
  31. package/dist/main/lib/constants.js.map +1 -0
  32. package/dist/main/lib/error-codes.d.ts +7 -0
  33. package/dist/main/lib/error-codes.d.ts.map +1 -0
  34. package/dist/main/lib/error-codes.js +3 -0
  35. package/dist/main/lib/error-codes.js.map +1 -0
  36. package/dist/main/lib/errors.d.ts +243 -0
  37. package/dist/main/lib/errors.d.ts.map +1 -0
  38. package/dist/main/lib/errors.js +289 -0
  39. package/dist/main/lib/errors.js.map +1 -0
  40. package/dist/main/lib/fetch.d.ts +34 -0
  41. package/dist/main/lib/fetch.d.ts.map +1 -0
  42. package/dist/main/lib/fetch.js +184 -0
  43. package/dist/main/lib/fetch.js.map +1 -0
  44. package/dist/main/lib/helpers.d.ts +91 -0
  45. package/dist/main/lib/helpers.d.ts.map +1 -0
  46. package/dist/main/lib/helpers.js +395 -0
  47. package/dist/main/lib/helpers.js.map +1 -0
  48. package/dist/main/lib/local-storage.d.ts +9 -0
  49. package/dist/main/lib/local-storage.d.ts.map +1 -0
  50. package/dist/main/lib/local-storage.js +21 -0
  51. package/dist/main/lib/local-storage.js.map +1 -0
  52. package/dist/main/lib/locks.d.ts +107 -0
  53. package/dist/main/lib/locks.d.ts.map +1 -0
  54. package/dist/main/lib/locks.js +314 -0
  55. package/dist/main/lib/locks.js.map +1 -0
  56. package/dist/main/lib/polyfills.d.ts +5 -0
  57. package/dist/main/lib/polyfills.d.ts.map +1 -0
  58. package/dist/main/lib/polyfills.js +29 -0
  59. package/dist/main/lib/polyfills.js.map +1 -0
  60. package/dist/main/lib/types.d.ts +1861 -0
  61. package/dist/main/lib/types.d.ts.map +1 -0
  62. package/dist/main/lib/types.js +23 -0
  63. package/dist/main/lib/types.js.map +1 -0
  64. package/dist/main/lib/version.d.ts +2 -0
  65. package/dist/main/lib/version.d.ts.map +1 -0
  66. package/dist/main/lib/version.js +11 -0
  67. package/dist/main/lib/version.js.map +1 -0
  68. package/dist/main/lib/web3/ethereum.d.ts +96 -0
  69. package/dist/main/lib/web3/ethereum.d.ts.map +1 -0
  70. package/dist/main/lib/web3/ethereum.js +66 -0
  71. package/dist/main/lib/web3/ethereum.js.map +1 -0
  72. package/dist/main/lib/web3/solana.d.ts +160 -0
  73. package/dist/main/lib/web3/solana.d.ts.map +1 -0
  74. package/dist/main/lib/web3/solana.js +4 -0
  75. package/dist/main/lib/web3/solana.js.map +1 -0
  76. package/dist/main/lib/webauthn.d.ts +276 -0
  77. package/dist/main/lib/webauthn.d.ts.map +1 -0
  78. package/dist/main/lib/webauthn.dom.d.ts +583 -0
  79. package/dist/main/lib/webauthn.dom.d.ts.map +1 -0
  80. package/dist/main/lib/webauthn.dom.js +4 -0
  81. package/dist/main/lib/webauthn.dom.js.map +1 -0
  82. package/dist/main/lib/webauthn.errors.d.ts +80 -0
  83. package/dist/main/lib/webauthn.errors.d.ts.map +1 -0
  84. package/dist/main/lib/webauthn.errors.js +265 -0
  85. package/dist/main/lib/webauthn.errors.js.map +1 -0
  86. package/dist/main/lib/webauthn.js +706 -0
  87. package/dist/main/lib/webauthn.js.map +1 -0
  88. package/dist/module/AuthAdminApi.d.ts +4 -0
  89. package/dist/module/AuthAdminApi.d.ts.map +1 -0
  90. package/dist/module/AuthAdminApi.js +4 -0
  91. package/dist/module/AuthAdminApi.js.map +1 -0
  92. package/dist/module/AuthClient.d.ts +4 -0
  93. package/dist/module/AuthClient.d.ts.map +1 -0
  94. package/dist/module/AuthClient.js +4 -0
  95. package/dist/module/AuthClient.js.map +1 -0
  96. package/dist/module/GoTrueAdminApi.d.ts +227 -0
  97. package/dist/module/GoTrueAdminApi.d.ts.map +1 -0
  98. package/dist/module/GoTrueAdminApi.js +593 -0
  99. package/dist/module/GoTrueAdminApi.js.map +1 -0
  100. package/dist/module/GoTrueClient.d.ts +783 -0
  101. package/dist/module/GoTrueClient.d.ts.map +1 -0
  102. package/dist/module/GoTrueClient.js +3026 -0
  103. package/dist/module/GoTrueClient.js.map +1 -0
  104. package/dist/module/index.d.ts +9 -0
  105. package/dist/module/index.d.ts.map +1 -0
  106. package/dist/module/index.js +9 -0
  107. package/dist/module/index.js.map +1 -0
  108. package/dist/module/lib/base64url.d.ts +76 -0
  109. package/dist/module/lib/base64url.d.ts.map +1 -0
  110. package/dist/module/lib/base64url.js +257 -0
  111. package/dist/module/lib/base64url.js.map +1 -0
  112. package/dist/module/lib/constants.d.ts +26 -0
  113. package/dist/module/lib/constants.d.ts.map +1 -0
  114. package/dist/module/lib/constants.js +28 -0
  115. package/dist/module/lib/constants.js.map +1 -0
  116. package/dist/module/lib/error-codes.d.ts +7 -0
  117. package/dist/module/lib/error-codes.d.ts.map +1 -0
  118. package/dist/module/lib/error-codes.js +2 -0
  119. package/dist/module/lib/error-codes.js.map +1 -0
  120. package/dist/module/lib/errors.d.ts +243 -0
  121. package/dist/module/lib/errors.d.ts.map +1 -0
  122. package/dist/module/lib/errors.js +266 -0
  123. package/dist/module/lib/errors.js.map +1 -0
  124. package/dist/module/lib/fetch.d.ts +34 -0
  125. package/dist/module/lib/fetch.d.ts.map +1 -0
  126. package/dist/module/lib/fetch.js +174 -0
  127. package/dist/module/lib/fetch.js.map +1 -0
  128. package/dist/module/lib/helpers.d.ts +91 -0
  129. package/dist/module/lib/helpers.d.ts.map +1 -0
  130. package/dist/module/lib/helpers.js +368 -0
  131. package/dist/module/lib/helpers.js.map +1 -0
  132. package/dist/module/lib/local-storage.d.ts +9 -0
  133. package/dist/module/lib/local-storage.d.ts.map +1 -0
  134. package/dist/module/lib/local-storage.js +18 -0
  135. package/dist/module/lib/local-storage.js.map +1 -0
  136. package/dist/module/lib/locks.d.ts +107 -0
  137. package/dist/module/lib/locks.d.ts.map +1 -0
  138. package/dist/module/lib/locks.js +306 -0
  139. package/dist/module/lib/locks.js.map +1 -0
  140. package/dist/module/lib/polyfills.d.ts +5 -0
  141. package/dist/module/lib/polyfills.d.ts.map +1 -0
  142. package/dist/module/lib/polyfills.js +26 -0
  143. package/dist/module/lib/polyfills.js.map +1 -0
  144. package/dist/module/lib/types.d.ts +1861 -0
  145. package/dist/module/lib/types.d.ts.map +1 -0
  146. package/dist/module/lib/types.js +20 -0
  147. package/dist/module/lib/types.js.map +1 -0
  148. package/dist/module/lib/version.d.ts +2 -0
  149. package/dist/module/lib/version.d.ts.map +1 -0
  150. package/dist/module/lib/version.js +8 -0
  151. package/dist/module/lib/version.js.map +1 -0
  152. package/dist/module/lib/web3/ethereum.d.ts +96 -0
  153. package/dist/module/lib/web3/ethereum.d.ts.map +1 -0
  154. package/dist/module/lib/web3/ethereum.js +60 -0
  155. package/dist/module/lib/web3/ethereum.js.map +1 -0
  156. package/dist/module/lib/web3/solana.d.ts +160 -0
  157. package/dist/module/lib/web3/solana.d.ts.map +1 -0
  158. package/dist/module/lib/web3/solana.js +3 -0
  159. package/dist/module/lib/web3/solana.js.map +1 -0
  160. package/dist/module/lib/webauthn.d.ts +276 -0
  161. package/dist/module/lib/webauthn.d.ts.map +1 -0
  162. package/dist/module/lib/webauthn.dom.d.ts +583 -0
  163. package/dist/module/lib/webauthn.dom.d.ts.map +1 -0
  164. package/dist/module/lib/webauthn.dom.js +3 -0
  165. package/dist/module/lib/webauthn.dom.js.map +1 -0
  166. package/dist/module/lib/webauthn.errors.d.ts +80 -0
  167. package/dist/module/lib/webauthn.errors.d.ts.map +1 -0
  168. package/dist/module/lib/webauthn.errors.js +257 -0
  169. package/dist/module/lib/webauthn.errors.js.map +1 -0
  170. package/dist/module/lib/webauthn.js +689 -0
  171. package/dist/module/lib/webauthn.js.map +1 -0
  172. package/dist/tsconfig.module.tsbuildinfo +1 -0
  173. package/dist/tsconfig.tsbuildinfo +1 -0
  174. package/package.json +56 -0
  175. package/src/AuthAdminApi.ts +5 -0
  176. package/src/AuthClient.ts +5 -0
  177. package/src/GoTrueAdminApi.ts +723 -0
  178. package/src/GoTrueClient.ts +4078 -0
  179. package/src/index.ts +13 -0
  180. package/src/lib/base64url.ts +308 -0
  181. package/src/lib/constants.ts +34 -0
  182. package/src/lib/error-codes.ts +90 -0
  183. package/src/lib/errors.ts +324 -0
  184. package/src/lib/fetch.ts +283 -0
  185. package/src/lib/helpers.ts +463 -0
  186. package/src/lib/local-storage.ts +21 -0
  187. package/src/lib/locks.ts +375 -0
  188. package/src/lib/polyfills.ts +23 -0
  189. package/src/lib/types.ts +2229 -0
  190. package/src/lib/version.ts +7 -0
  191. package/src/lib/web3/ethereum.ts +184 -0
  192. package/src/lib/web3/solana.ts +186 -0
  193. package/src/lib/webauthn.dom.ts +636 -0
  194. package/src/lib/webauthn.errors.ts +317 -0
  195. package/src/lib/webauthn.ts +946 -0
@@ -0,0 +1,174 @@
1
+ import { __rest } from "tslib";
2
+ import { API_VERSIONS, API_VERSION_HEADER_NAME } from './constants';
3
+ import { expiresAt, looksLikeFetchResponse, parseResponseAPIVersion } from './helpers';
4
+ import { AuthApiError, AuthRetryableFetchError, AuthWeakPasswordError, AuthUnknownError, AuthSessionMissingError, } from './errors';
5
+ const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
6
+ const NETWORK_ERROR_CODES = [502, 503, 504];
7
+ export async function handleError(error) {
8
+ var _a;
9
+ if (!looksLikeFetchResponse(error)) {
10
+ throw new AuthRetryableFetchError(_getErrorMessage(error), 0);
11
+ }
12
+ if (NETWORK_ERROR_CODES.includes(error.status)) {
13
+ // status in 500...599 range - server had an error, request might be retryed.
14
+ throw new AuthRetryableFetchError(_getErrorMessage(error), error.status);
15
+ }
16
+ let data;
17
+ try {
18
+ data = await error.json();
19
+ }
20
+ catch (e) {
21
+ throw new AuthUnknownError(_getErrorMessage(e), e);
22
+ }
23
+ let errorCode = undefined;
24
+ const responseAPIVersion = parseResponseAPIVersion(error);
25
+ if (responseAPIVersion &&
26
+ responseAPIVersion.getTime() >= API_VERSIONS['2024-01-01'].timestamp &&
27
+ typeof data === 'object' &&
28
+ data &&
29
+ typeof data.code === 'string') {
30
+ errorCode = data.code;
31
+ }
32
+ else if (typeof data === 'object' && data && typeof data.error_code === 'string') {
33
+ errorCode = data.error_code;
34
+ }
35
+ if (!errorCode) {
36
+ // Legacy support for weak password errors, when there were no error codes
37
+ if (typeof data === 'object' &&
38
+ data &&
39
+ typeof data.weak_password === 'object' &&
40
+ data.weak_password &&
41
+ Array.isArray(data.weak_password.reasons) &&
42
+ data.weak_password.reasons.length &&
43
+ data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {
44
+ throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons);
45
+ }
46
+ }
47
+ else if (errorCode === 'weak_password') {
48
+ throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []);
49
+ }
50
+ else if (errorCode === 'session_not_found') {
51
+ // The `session_id` inside the JWT does not correspond to a row in the
52
+ // `sessions` table. This usually means the user has signed out, has been
53
+ // deleted, or their session has somehow been terminated.
54
+ throw new AuthSessionMissingError();
55
+ }
56
+ throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode);
57
+ }
58
+ const _getRequestParams = (method, options, parameters, body) => {
59
+ const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
60
+ if (method === 'GET') {
61
+ return params;
62
+ }
63
+ params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers);
64
+ params.body = JSON.stringify(body);
65
+ return Object.assign(Object.assign({}, params), parameters);
66
+ };
67
+ export async function _request(fetcher, method, url, options) {
68
+ var _a;
69
+ const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);
70
+ if (!headers[API_VERSION_HEADER_NAME]) {
71
+ headers[API_VERSION_HEADER_NAME] = API_VERSIONS['2024-01-01'].name;
72
+ }
73
+ if (options === null || options === void 0 ? void 0 : options.jwt) {
74
+ headers['Authorization'] = `Bearer ${options.jwt}`;
75
+ }
76
+ const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {};
77
+ if (options === null || options === void 0 ? void 0 : options.redirectTo) {
78
+ qs['redirect_to'] = options.redirectTo;
79
+ }
80
+ const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : '';
81
+ const data = await _handleRequest(fetcher, method, url + queryString, {
82
+ headers,
83
+ noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson,
84
+ }, {}, options === null || options === void 0 ? void 0 : options.body);
85
+ return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null };
86
+ }
87
+ async function _handleRequest(fetcher, method, url, options, parameters, body) {
88
+ const requestParams = _getRequestParams(method, options, parameters, body);
89
+ let result;
90
+ try {
91
+ result = await fetcher(url, Object.assign({}, requestParams));
92
+ }
93
+ catch (e) {
94
+ console.error(e);
95
+ // fetch failed, likely due to a network or CORS error
96
+ throw new AuthRetryableFetchError(_getErrorMessage(e), 0);
97
+ }
98
+ if (!result.ok) {
99
+ await handleError(result);
100
+ }
101
+ if (options === null || options === void 0 ? void 0 : options.noResolveJson) {
102
+ return result;
103
+ }
104
+ try {
105
+ return await result.json();
106
+ }
107
+ catch (e) {
108
+ await handleError(e);
109
+ }
110
+ }
111
+ export function _sessionResponse(data) {
112
+ var _a;
113
+ let session = null;
114
+ if (hasSession(data)) {
115
+ session = Object.assign({}, data);
116
+ if (!data.expires_at) {
117
+ session.expires_at = expiresAt(data.expires_in);
118
+ }
119
+ }
120
+ const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
121
+ return { data: { session, user }, error: null };
122
+ }
123
+ export function _sessionResponsePassword(data) {
124
+ const response = _sessionResponse(data);
125
+ if (!response.error &&
126
+ data.weak_password &&
127
+ typeof data.weak_password === 'object' &&
128
+ Array.isArray(data.weak_password.reasons) &&
129
+ data.weak_password.reasons.length &&
130
+ data.weak_password.message &&
131
+ typeof data.weak_password.message === 'string' &&
132
+ data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {
133
+ response.data.weak_password = data.weak_password;
134
+ }
135
+ return response;
136
+ }
137
+ export function _userResponse(data) {
138
+ var _a;
139
+ const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;
140
+ return { data: { user }, error: null };
141
+ }
142
+ export function _ssoResponse(data) {
143
+ return { data, error: null };
144
+ }
145
+ export function _generateLinkResponse(data) {
146
+ const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]);
147
+ const properties = {
148
+ action_link,
149
+ email_otp,
150
+ hashed_token,
151
+ redirect_to,
152
+ verification_type,
153
+ };
154
+ const user = Object.assign({}, rest);
155
+ return {
156
+ data: {
157
+ properties,
158
+ user,
159
+ },
160
+ error: null,
161
+ };
162
+ }
163
+ export function _noResolveJsonResponse(data) {
164
+ return data;
165
+ }
166
+ /**
167
+ * hasSession checks if the response object contains a valid session
168
+ * @param data A response object
169
+ * @returns true if a session is in the response
170
+ */
171
+ function hasSession(data) {
172
+ return data.access_token && data.refresh_token && data.expires_in;
173
+ }
174
+ //# sourceMappingURL=fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAA;AAUtF,OAAO,EACL,YAAY,EACZ,uBAAuB,EACvB,qBAAqB,EACrB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,UAAU,CAAA;AAiBjB,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAU,EAAE,CAC5C,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,iBAAiB,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;AAErF,MAAM,mBAAmB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;AAE3C,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,KAAc;;IAC9C,IAAI,CAAC,sBAAsB,CAAC,KAAK,CAAC,EAAE,CAAC;QACnC,MAAM,IAAI,uBAAuB,CAAC,gBAAgB,CAAC,KAAK,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I,EAAE,CAAA;AACxC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,IAAS;IACpC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;AAC9B,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,IAAS;IAC7C,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,iBAAiB,KAAc,IAAI,EAAb,IAAI,UAAK,IAAI,EAAxF,gFAAiF,CAAO,CAAA;IAE9F,MAAM,UAAU,GAA2B;QACzC,WAAW;QACX,SAAS;QACT,YAAY;QACZ,WAAW;QACX,iBAAiB;KAClB,CAAA;IAED,MAAM,IAAI,qBAAc,IAAI,CAAE,CAAA;IAC9B,OAAO;QACL,IAAI,EAAE;YACJ,UAAU;YACV,IAAI;SACL;QACD,KAAK,EAAE,IAAI;KACZ,CAAA;AACH,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,IAAS;IAC9C,OAAO,IAAI,CAAA;AACb,CAAC;AAED;;;;GAIG;AACH,SAAS,UAAU,CAAC,IAAS;IAC3B,OAAO,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,UAAU,CAAA;AACnE,CAAC"}
@@ -0,0 +1,91 @@
1
+ import { JwtHeader, JwtPayload, SupportedStorage, User } from './types';
2
+ import { Uint8Array_ } from './webauthn.dom';
3
+ export declare function expiresAt(expiresIn: number): number;
4
+ /**
5
+ * Generates a unique identifier for internal callback subscriptions.
6
+ *
7
+ * This function uses JavaScript Symbols to create guaranteed-unique identifiers
8
+ * for auth state change callbacks. Symbols are ideal for this use case because:
9
+ * - They are guaranteed unique by the JavaScript runtime
10
+ * - They work in all environments (browser, SSR, Node.js)
11
+ * - They avoid issues with Next.js 16 deterministic rendering requirements
12
+ * - They are perfect for internal, non-serializable identifiers
13
+ *
14
+ * Note: This function is only used for internal subscription management,
15
+ * not for security-critical operations like session tokens.
16
+ */
17
+ export declare function generateCallbackId(): symbol;
18
+ export declare const isBrowser: () => boolean;
19
+ /**
20
+ * Checks whether localStorage is supported on this browser.
21
+ */
22
+ export declare const supportsLocalStorage: () => boolean;
23
+ /**
24
+ * Extracts parameters encoded in the URL both in the query and fragment.
25
+ */
26
+ export declare function parseParametersFromURL(href: string): {
27
+ [parameter: string]: string;
28
+ };
29
+ type Fetch = typeof fetch;
30
+ export declare const resolveFetch: (customFetch?: Fetch) => Fetch;
31
+ export declare const looksLikeFetchResponse: (maybeResponse: unknown) => maybeResponse is Response;
32
+ export declare const setItemAsync: (storage: SupportedStorage, key: string, data: any) => Promise<void>;
33
+ export declare const getItemAsync: (storage: SupportedStorage, key: string) => Promise<unknown>;
34
+ export declare const removeItemAsync: (storage: SupportedStorage, key: string) => Promise<void>;
35
+ /**
36
+ * A deferred represents some asynchronous work that is not yet finished, which
37
+ * may or may not culminate in a value.
38
+ * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
39
+ */
40
+ export declare class Deferred<T = any> {
41
+ static promiseConstructor: PromiseConstructor;
42
+ readonly promise: PromiseLike<T>;
43
+ readonly resolve: (value?: T | PromiseLike<T>) => void;
44
+ readonly reject: (reason?: any) => any;
45
+ constructor();
46
+ }
47
+ export declare function decodeJWT(token: string): {
48
+ header: JwtHeader;
49
+ payload: JwtPayload;
50
+ signature: Uint8Array_;
51
+ raw: {
52
+ header: string;
53
+ payload: string;
54
+ };
55
+ };
56
+ /**
57
+ * Creates a promise that resolves to null after some time.
58
+ */
59
+ export declare function sleep(time: number): Promise<null>;
60
+ /**
61
+ * Converts the provided async function into a retryable function. Each result
62
+ * or thrown error is sent to the isRetryable function which should return true
63
+ * if the function should run again.
64
+ */
65
+ export declare function retryable<T>(fn: (attempt: number) => Promise<T>, isRetryable: (attempt: number, error: any | null, result?: T) => boolean): Promise<T>;
66
+ export declare function generatePKCEVerifier(): string;
67
+ export declare function generatePKCEChallenge(verifier: string): Promise<string>;
68
+ export declare function getCodeChallengeAndMethod(storage: SupportedStorage, storageKey: string, isPasswordRecovery?: boolean): Promise<string[]>;
69
+ export declare function parseResponseAPIVersion(response: Response): Date | null;
70
+ export declare function validateExp(exp: number): void;
71
+ export declare function getAlgorithm(alg: 'HS256' | 'RS256' | 'ES256'): RsaHashedImportParams | EcKeyImportParams;
72
+ export declare function validateUUID(str: string): void;
73
+ export declare function userNotAvailableProxy(): User;
74
+ /**
75
+ * Creates a proxy around a user object that warns when properties are accessed on the server.
76
+ * This is used to alert developers that using user data from getSession() on the server is insecure.
77
+ *
78
+ * @param user The actual user object to wrap
79
+ * @param suppressWarningRef An object with a 'value' property that controls warning suppression
80
+ * @returns A proxied user object that warns on property access
81
+ */
82
+ export declare function insecureUserWarningProxy(user: User, suppressWarningRef: {
83
+ value: boolean;
84
+ }): User;
85
+ /**
86
+ * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
87
+ * Note: Only works for JSON-safe data.
88
+ */
89
+ export declare function deepClone<T>(obj: T): T;
90
+ export {};
91
+ //# sourceMappingURL=helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAE5C,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAE3C;AAED,eAAO,MAAM,SAAS,eAAyE,CAAA;AAO/F;;GAEG;AACH,eAAO,MAAM,oBAAoB,eAmChC,CAAA;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM;;EAsBlD;AAED,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,GAAI,cAAc,KAAK,KAAG,KAKl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E,KAAK,EAAE,GAAG,GAAG,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC,KAAK,OAAO,GACvE,OAAO,CAAC,CAAC,CAAC,CAuBZ;AAOD,wBAAgB,oBAAoB,WAcnC;AAaD,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,mBAc3D;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,gBAAgB,EACzB,UAAU,EAAE,MAAM,EAClB,kBAAkB,UAAQ,qBAW3B;AAKD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,eAiBzD;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,QAQtC;AAED,wBAAgB,YAAY,CAC1B,GAAG,EAAE,OAAO,GAAG,OAAO,GAAG,OAAO,GAC/B,qBAAqB,GAAG,iBAAiB,CAgB3C;AAID,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,QAIvC;AAED,wBAAgB,qBAAqB,IAAI,IAAI,CAoC5C;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,IAAI,EAAE,kBAAkB,EAAE;IAAE,KAAK,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAkCjG;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAEtC"}
@@ -0,0 +1,368 @@
1
+ import { API_VERSION_HEADER_NAME, BASE64URL_REGEX } from './constants';
2
+ import { AuthInvalidJwtError } from './errors';
3
+ import { base64UrlToUint8Array, stringFromBase64URL } from './base64url';
4
+ export function expiresAt(expiresIn) {
5
+ const timeNow = Math.round(Date.now() / 1000);
6
+ return timeNow + expiresIn;
7
+ }
8
+ /**
9
+ * Generates a unique identifier for internal callback subscriptions.
10
+ *
11
+ * This function uses JavaScript Symbols to create guaranteed-unique identifiers
12
+ * for auth state change callbacks. Symbols are ideal for this use case because:
13
+ * - They are guaranteed unique by the JavaScript runtime
14
+ * - They work in all environments (browser, SSR, Node.js)
15
+ * - They avoid issues with Next.js 16 deterministic rendering requirements
16
+ * - They are perfect for internal, non-serializable identifiers
17
+ *
18
+ * Note: This function is only used for internal subscription management,
19
+ * not for security-critical operations like session tokens.
20
+ */
21
+ export function generateCallbackId() {
22
+ return Symbol('auth-callback');
23
+ }
24
+ export const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';
25
+ const localStorageWriteTests = {
26
+ tested: false,
27
+ writable: false,
28
+ };
29
+ /**
30
+ * Checks whether localStorage is supported on this browser.
31
+ */
32
+ export const supportsLocalStorage = () => {
33
+ if (!isBrowser()) {
34
+ return false;
35
+ }
36
+ try {
37
+ if (typeof globalThis.localStorage !== 'object') {
38
+ return false;
39
+ }
40
+ }
41
+ catch (e) {
42
+ // DOM exception when accessing `localStorage`
43
+ return false;
44
+ }
45
+ if (localStorageWriteTests.tested) {
46
+ return localStorageWriteTests.writable;
47
+ }
48
+ const randomKey = `lswt-${Math.random()}${Math.random()}`;
49
+ try {
50
+ globalThis.localStorage.setItem(randomKey, randomKey);
51
+ globalThis.localStorage.removeItem(randomKey);
52
+ localStorageWriteTests.tested = true;
53
+ localStorageWriteTests.writable = true;
54
+ }
55
+ catch (e) {
56
+ // localStorage can't be written to
57
+ // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document
58
+ localStorageWriteTests.tested = true;
59
+ localStorageWriteTests.writable = false;
60
+ }
61
+ return localStorageWriteTests.writable;
62
+ };
63
+ /**
64
+ * Extracts parameters encoded in the URL both in the query and fragment.
65
+ */
66
+ export function parseParametersFromURL(href) {
67
+ const result = {};
68
+ const url = new URL(href);
69
+ if (url.hash && url.hash[0] === '#') {
70
+ try {
71
+ const hashSearchParams = new URLSearchParams(url.hash.substring(1));
72
+ hashSearchParams.forEach((value, key) => {
73
+ result[key] = value;
74
+ });
75
+ }
76
+ catch (e) {
77
+ // hash is not a query string
78
+ }
79
+ }
80
+ // search parameters take precedence over hash parameters
81
+ url.searchParams.forEach((value, key) => {
82
+ result[key] = value;
83
+ });
84
+ return result;
85
+ }
86
+ export const resolveFetch = (customFetch) => {
87
+ if (customFetch) {
88
+ return (...args) => customFetch(...args);
89
+ }
90
+ return (...args) => fetch(...args);
91
+ };
92
+ export const looksLikeFetchResponse = (maybeResponse) => {
93
+ return (typeof maybeResponse === 'object' &&
94
+ maybeResponse !== null &&
95
+ 'status' in maybeResponse &&
96
+ 'ok' in maybeResponse &&
97
+ 'json' in maybeResponse &&
98
+ typeof maybeResponse.json === 'function');
99
+ };
100
+ // Storage helpers
101
+ export const setItemAsync = async (storage, key, data) => {
102
+ await storage.setItem(key, JSON.stringify(data));
103
+ };
104
+ export const getItemAsync = async (storage, key) => {
105
+ const value = await storage.getItem(key);
106
+ if (!value) {
107
+ return null;
108
+ }
109
+ try {
110
+ return JSON.parse(value);
111
+ }
112
+ catch (_a) {
113
+ return value;
114
+ }
115
+ };
116
+ export const removeItemAsync = async (storage, key) => {
117
+ await storage.removeItem(key);
118
+ };
119
+ /**
120
+ * A deferred represents some asynchronous work that is not yet finished, which
121
+ * may or may not culminate in a value.
122
+ * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
123
+ */
124
+ export class Deferred {
125
+ constructor() {
126
+ // eslint-disable-next-line @typescript-eslint/no-extra-semi
127
+ ;
128
+ this.promise = new Deferred.promiseConstructor((res, rej) => {
129
+ // eslint-disable-next-line @typescript-eslint/no-extra-semi
130
+ ;
131
+ this.resolve = res;
132
+ this.reject = rej;
133
+ });
134
+ }
135
+ }
136
+ Deferred.promiseConstructor = Promise;
137
+ export function decodeJWT(token) {
138
+ const parts = token.split('.');
139
+ if (parts.length !== 3) {
140
+ throw new AuthInvalidJwtError('Invalid JWT structure');
141
+ }
142
+ // Regex checks for base64url format
143
+ for (let i = 0; i < parts.length; i++) {
144
+ if (!BASE64URL_REGEX.test(parts[i])) {
145
+ throw new AuthInvalidJwtError('JWT not in base64url format');
146
+ }
147
+ }
148
+ const data = {
149
+ // using base64url lib
150
+ header: JSON.parse(stringFromBase64URL(parts[0])),
151
+ payload: JSON.parse(stringFromBase64URL(parts[1])),
152
+ signature: base64UrlToUint8Array(parts[2]),
153
+ raw: {
154
+ header: parts[0],
155
+ payload: parts[1],
156
+ },
157
+ };
158
+ return data;
159
+ }
160
+ /**
161
+ * Creates a promise that resolves to null after some time.
162
+ */
163
+ export async function sleep(time) {
164
+ return await new Promise((accept) => {
165
+ setTimeout(() => accept(null), time);
166
+ });
167
+ }
168
+ /**
169
+ * Converts the provided async function into a retryable function. Each result
170
+ * or thrown error is sent to the isRetryable function which should return true
171
+ * if the function should run again.
172
+ */
173
+ export function retryable(fn, isRetryable) {
174
+ const promise = new Promise((accept, reject) => {
175
+ // eslint-disable-next-line @typescript-eslint/no-extra-semi
176
+ ;
177
+ (async () => {
178
+ for (let attempt = 0; attempt < Infinity; attempt++) {
179
+ try {
180
+ const result = await fn(attempt);
181
+ if (!isRetryable(attempt, null, result)) {
182
+ accept(result);
183
+ return;
184
+ }
185
+ }
186
+ catch (e) {
187
+ if (!isRetryable(attempt, e)) {
188
+ reject(e);
189
+ return;
190
+ }
191
+ }
192
+ }
193
+ })();
194
+ });
195
+ return promise;
196
+ }
197
+ function dec2hex(dec) {
198
+ return ('0' + dec.toString(16)).substr(-2);
199
+ }
200
+ // Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs
201
+ export function generatePKCEVerifier() {
202
+ const verifierLength = 56;
203
+ const array = new Uint32Array(verifierLength);
204
+ if (typeof crypto === 'undefined') {
205
+ const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
206
+ const charSetLen = charSet.length;
207
+ let verifier = '';
208
+ for (let i = 0; i < verifierLength; i++) {
209
+ verifier += charSet.charAt(Math.floor(Math.random() * charSetLen));
210
+ }
211
+ return verifier;
212
+ }
213
+ crypto.getRandomValues(array);
214
+ return Array.from(array, dec2hex).join('');
215
+ }
216
+ async function sha256(randomString) {
217
+ const encoder = new TextEncoder();
218
+ const encodedData = encoder.encode(randomString);
219
+ const hash = await crypto.subtle.digest('SHA-256', encodedData);
220
+ const bytes = new Uint8Array(hash);
221
+ return Array.from(bytes)
222
+ .map((c) => String.fromCharCode(c))
223
+ .join('');
224
+ }
225
+ export async function generatePKCEChallenge(verifier) {
226
+ const hasCryptoSupport = typeof crypto !== 'undefined' &&
227
+ typeof crypto.subtle !== 'undefined' &&
228
+ typeof TextEncoder !== 'undefined';
229
+ if (!hasCryptoSupport) {
230
+ console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.');
231
+ return verifier;
232
+ }
233
+ const hashed = await sha256(verifier);
234
+ return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
235
+ }
236
+ export async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) {
237
+ const codeVerifier = generatePKCEVerifier();
238
+ let storedCodeVerifier = codeVerifier;
239
+ if (isPasswordRecovery) {
240
+ storedCodeVerifier += '/PASSWORD_RECOVERY';
241
+ }
242
+ await setItemAsync(storage, `${storageKey}-code-verifier`, storedCodeVerifier);
243
+ const codeChallenge = await generatePKCEChallenge(codeVerifier);
244
+ const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
245
+ return [codeChallenge, codeChallengeMethod];
246
+ }
247
+ /** Parses the API version which is 2YYY-MM-DD. */
248
+ const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;
249
+ export function parseResponseAPIVersion(response) {
250
+ const apiVersion = response.headers.get(API_VERSION_HEADER_NAME);
251
+ if (!apiVersion) {
252
+ return null;
253
+ }
254
+ if (!apiVersion.match(API_VERSION_REGEX)) {
255
+ return null;
256
+ }
257
+ try {
258
+ const date = new Date(`${apiVersion}T00:00:00.0Z`);
259
+ return date;
260
+ }
261
+ catch (e) {
262
+ return null;
263
+ }
264
+ }
265
+ export function validateExp(exp) {
266
+ if (!exp) {
267
+ throw new Error('Missing exp claim');
268
+ }
269
+ const timeNow = Math.floor(Date.now() / 1000);
270
+ if (exp <= timeNow) {
271
+ throw new Error('JWT has expired');
272
+ }
273
+ }
274
+ export function getAlgorithm(alg) {
275
+ switch (alg) {
276
+ case 'RS256':
277
+ return {
278
+ name: 'RSASSA-PKCS1-v1_5',
279
+ hash: { name: 'SHA-256' },
280
+ };
281
+ case 'ES256':
282
+ return {
283
+ name: 'ECDSA',
284
+ namedCurve: 'P-256',
285
+ hash: { name: 'SHA-256' },
286
+ };
287
+ default:
288
+ throw new Error('Invalid alg claim');
289
+ }
290
+ }
291
+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
292
+ export function validateUUID(str) {
293
+ if (!UUID_REGEX.test(str)) {
294
+ throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not');
295
+ }
296
+ }
297
+ export function userNotAvailableProxy() {
298
+ const proxyTarget = {};
299
+ return new Proxy(proxyTarget, {
300
+ get: (target, prop) => {
301
+ if (prop === '__isUserNotAvailableProxy') {
302
+ return true;
303
+ }
304
+ // Preventative check for common problematic symbols during cloning/inspection
305
+ // These symbols might be accessed by structuredClone or other internal mechanisms.
306
+ if (typeof prop === 'symbol') {
307
+ const sProp = prop.toString();
308
+ if (sProp === 'Symbol(Symbol.toPrimitive)' ||
309
+ sProp === 'Symbol(Symbol.toStringTag)' ||
310
+ sProp === 'Symbol(util.inspect.custom)') {
311
+ // Node.js util.inspect
312
+ return undefined;
313
+ }
314
+ }
315
+ throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`);
316
+ },
317
+ set: (_target, prop) => {
318
+ throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
319
+ },
320
+ deleteProperty: (_target, prop) => {
321
+ throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);
322
+ },
323
+ });
324
+ }
325
+ /**
326
+ * Creates a proxy around a user object that warns when properties are accessed on the server.
327
+ * This is used to alert developers that using user data from getSession() on the server is insecure.
328
+ *
329
+ * @param user The actual user object to wrap
330
+ * @param suppressWarningRef An object with a 'value' property that controls warning suppression
331
+ * @returns A proxied user object that warns on property access
332
+ */
333
+ export function insecureUserWarningProxy(user, suppressWarningRef) {
334
+ return new Proxy(user, {
335
+ get: (target, prop, receiver) => {
336
+ // Allow internal checks without warning
337
+ if (prop === '__isInsecureUserWarningProxy') {
338
+ return true;
339
+ }
340
+ // Preventative check for common problematic symbols during cloning/inspection
341
+ // These symbols might be accessed by structuredClone or other internal mechanisms
342
+ if (typeof prop === 'symbol') {
343
+ const sProp = prop.toString();
344
+ if (sProp === 'Symbol(Symbol.toPrimitive)' ||
345
+ sProp === 'Symbol(Symbol.toStringTag)' ||
346
+ sProp === 'Symbol(util.inspect.custom)' ||
347
+ sProp === 'Symbol(nodejs.util.inspect.custom)') {
348
+ // Return the actual value for these symbols to allow proper inspection
349
+ return Reflect.get(target, prop, receiver);
350
+ }
351
+ }
352
+ // Emit warning on first property access
353
+ if (!suppressWarningRef.value && typeof prop === 'string') {
354
+ console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.');
355
+ suppressWarningRef.value = true;
356
+ }
357
+ return Reflect.get(target, prop, receiver);
358
+ },
359
+ });
360
+ }
361
+ /**
362
+ * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
363
+ * Note: Only works for JSON-safe data.
364
+ */
365
+ export function deepClone(obj) {
366
+ return JSON.parse(JSON.stringify(obj));
367
+ }
368
+ //# sourceMappingURL=helpers.js.map