@authyon/server 0.2.0-beta.0 → 0.2.0-beta.11

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.
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+
16
+ // src/browser.ts
17
+ var browser_exports = {};
18
+ module.exports = __toCommonJS(browser_exports);
19
+ throw new Error(
20
+ "@authyon/server cannot run in a browser. Use @authyon/auth in frontend code and keep client secrets on the server."
21
+ );
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,4 @@
1
+ // src/browser.ts
2
+ throw new Error(
3
+ "@authyon/server cannot run in a browser. Use @authyon/auth in frontend code and keep client secrets on the server."
4
+ );
@@ -0,0 +1,323 @@
1
+ // ../../internal/core/errors/authyonError.ts
2
+ var ErrorCodes = {
3
+ Unknown: "unknown",
4
+ NetworkError: "request.network_error",
5
+ Timeout: "request.timeout",
6
+ SessionMalformed: "session.malformed",
7
+ NotAuthenticated: "auth.not_authenticated",
8
+ InvalidToken: "auth.invalid_token",
9
+ MissingToken: "auth.missing_token",
10
+ EmailTaken: "user.email_taken",
11
+ PasswordWeak: "user.password_weak",
12
+ PasswordPwned: "user.password_pwned",
13
+ RateLimited: "rate_limited"
14
+ };
15
+ var AuthyonError = class extends Error {
16
+ constructor(status, body, options = {}) {
17
+ super(body.detail ?? body.title ?? `Authyon request failed with status ${status}`);
18
+ this.name = "AuthyonError";
19
+ this.status = status;
20
+ this.code = body.code ?? "unknown";
21
+ this.title = body.title ?? "Error";
22
+ this.detail = body.detail;
23
+ this.requestId = options.requestId;
24
+ this.retryAfter = options.retryAfter;
25
+ this.cause = options.cause;
26
+ }
27
+ is(code) {
28
+ return this.code === code;
29
+ }
30
+ isAny(...codes) {
31
+ return codes.includes(this.code);
32
+ }
33
+ hasPrefix(prefix) {
34
+ return this.code.startsWith(prefix);
35
+ }
36
+ isStatus(...statuses) {
37
+ return statuses.includes(this.status);
38
+ }
39
+ /** Stable interpretation for UI decisions, retries, telemetry and support flows. */
40
+ interpret() {
41
+ const category = classifyError(this.status, this.code);
42
+ return {
43
+ category,
44
+ action: actionFor(category),
45
+ retryable: isRetryable(category),
46
+ ...this.retryAfter !== void 0 ? { retryAfter: this.retryAfter } : {},
47
+ ...this.requestId !== void 0 ? { requestId: this.requestId } : {}
48
+ };
49
+ }
50
+ get category() {
51
+ return this.interpret().category;
52
+ }
53
+ get retryable() {
54
+ return this.interpret().retryable;
55
+ }
56
+ toJSON() {
57
+ return {
58
+ name: this.name,
59
+ message: this.message,
60
+ status: this.status,
61
+ code: this.code,
62
+ title: this.title,
63
+ detail: this.detail,
64
+ requestId: this.requestId,
65
+ retryAfter: this.retryAfter,
66
+ ...this.interpret()
67
+ };
68
+ }
69
+ };
70
+ function classifyError(status, code) {
71
+ if (code === ErrorCodes.NetworkError) return "network";
72
+ if (code === ErrorCodes.Timeout || status === 408) return "timeout";
73
+ if (code === ErrorCodes.RateLimited || status === 429) return "rate_limit";
74
+ if (code === ErrorCodes.EmailTaken || status === 409) return "conflict";
75
+ if (code === ErrorCodes.PasswordWeak || code === ErrorCodes.PasswordPwned) return "validation";
76
+ if (code === ErrorCodes.SessionMalformed) return "server";
77
+ if (code.startsWith("auth.") || status === 401) return "authentication";
78
+ if (status === 403) return "authorization";
79
+ if (status === 404) return "not_found";
80
+ if (status === 400 || status === 422) return "validation";
81
+ if (status >= 500) return "server";
82
+ return "unknown";
83
+ }
84
+ function actionFor(category) {
85
+ switch (category) {
86
+ case "network":
87
+ case "timeout":
88
+ case "rate_limit":
89
+ case "server":
90
+ return "retry";
91
+ case "authentication":
92
+ return "reauthenticate";
93
+ case "authorization":
94
+ return "request_access";
95
+ case "validation":
96
+ return "fix_input";
97
+ case "not_found":
98
+ return "not_found";
99
+ case "conflict":
100
+ return "resolve_conflict";
101
+ case "unknown":
102
+ return "contact_support";
103
+ }
104
+ }
105
+ function isRetryable(category) {
106
+ return category === "network" || category === "timeout" || category === "rate_limit" || category === "server";
107
+ }
108
+
109
+ // ../../internal/core/http/httpAdapter.ts
110
+ var FetchHttpAdapter = class {
111
+ constructor(fetchImpl = fetch.bind(globalThis)) {
112
+ this.fetchImpl = fetchImpl;
113
+ }
114
+ request(request) {
115
+ return this.fetchImpl(request.url, {
116
+ method: request.method,
117
+ headers: request.headers,
118
+ body: request.body,
119
+ signal: request.signal,
120
+ redirect: "error"
121
+ });
122
+ }
123
+ };
124
+ var LoggingHttpAdapter = class {
125
+ constructor(adapter, options) {
126
+ this.adapter = adapter;
127
+ this.options = options;
128
+ }
129
+ async request(request) {
130
+ const startedAt = Date.now();
131
+ const eventBase = {
132
+ method: request.method,
133
+ url: sanitizeUrl(request.url)
134
+ };
135
+ this.log({ type: "request", ...eventBase, timestamp: startedAt });
136
+ try {
137
+ const response = await this.adapter.request(request);
138
+ this.log({
139
+ type: "response",
140
+ ...eventBase,
141
+ status: response.status,
142
+ durationMs: Date.now() - startedAt,
143
+ requestId: response.headers.get("x-request-id") ?? response.headers.get("trace-id") ?? void 0,
144
+ timestamp: Date.now()
145
+ });
146
+ return response;
147
+ } catch (error) {
148
+ this.log({
149
+ type: "error",
150
+ ...eventBase,
151
+ errorName: error instanceof Error ? error.name : "UnknownError",
152
+ durationMs: Date.now() - startedAt,
153
+ timestamp: Date.now()
154
+ });
155
+ throw error;
156
+ }
157
+ }
158
+ log(event) {
159
+ if (!this.options.enabled) return;
160
+ const logger = this.options.logger ?? defaultHttpLogger;
161
+ try {
162
+ logger(event);
163
+ } catch {
164
+ }
165
+ }
166
+ };
167
+ function defaultHttpLogger(event) {
168
+ console.debug("[Authyon HTTP]", event);
169
+ }
170
+ function sanitizeUrl(value) {
171
+ const url = new URL(value);
172
+ url.username = "";
173
+ url.password = "";
174
+ url.hash = "";
175
+ url.pathname = url.pathname.replace(/(\/platform\/workspace-invites\/)[^/]+/u, "$1REDACTED");
176
+ const queryKeys = /* @__PURE__ */ new Set();
177
+ url.searchParams.forEach((_value, key) => queryKeys.add(key));
178
+ url.search = queryKeys.size > 0 ? [...queryKeys].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&") : "";
179
+ return url.toString();
180
+ }
181
+
182
+ // ../../internal/core/config/defaults.ts
183
+ var DEFAULT_BASE_URL = "https://api.authyon.com";
184
+ var DEFAULT_EXPIRY_SKEW_MS = 3e4;
185
+
186
+ // ../../internal/core/http/transport.ts
187
+ var DEFAULT_TIMEOUT_MS = 15e3;
188
+ var SharedTransportError = class extends Error {
189
+ constructor(code, cause) {
190
+ super(code === "request.timeout" ? "Request timed out" : "Network request failed");
191
+ this.name = "SharedTransportError";
192
+ this.code = code;
193
+ this.cause = cause;
194
+ }
195
+ };
196
+ function createSharedTransport(options) {
197
+ const baseUrl = normalizeBaseUrl(options.baseUrl, options.allowInsecureHttp ?? false);
198
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
199
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
200
+ throw new Error("Authyon: `timeoutMs` must be a non-negative finite number");
201
+ }
202
+ if (options.httpAdapter && options.fetch) {
203
+ throw new Error("Authyon: use either `httpAdapter` or `fetch`, not both");
204
+ }
205
+ const baseAdapter = options.httpAdapter ?? new FetchHttpAdapter(options.fetch);
206
+ const httpAdapter = options.httpLogger ? new LoggingHttpAdapter(baseAdapter, options.httpLogger) : baseAdapter;
207
+ return {
208
+ baseUrl,
209
+ async request(path, init) {
210
+ const controller = new AbortController();
211
+ const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
212
+ try {
213
+ return await httpAdapter.request({
214
+ url: `${baseUrl}${path}`,
215
+ method: init.method ?? "GET",
216
+ headers: normalizeHeaders(init.headers),
217
+ body: init.body,
218
+ signal: controller.signal
219
+ });
220
+ } catch (cause) {
221
+ throw new SharedTransportError(
222
+ controller.signal.aborted ? ErrorCodes.Timeout : ErrorCodes.NetworkError,
223
+ cause
224
+ );
225
+ } finally {
226
+ if (timeout !== void 0) clearTimeout(timeout);
227
+ }
228
+ }
229
+ };
230
+ }
231
+ function normalizeHeaders(headers) {
232
+ const normalized = {};
233
+ new Headers(headers).forEach((value, key) => {
234
+ normalized[key] = value;
235
+ });
236
+ return normalized;
237
+ }
238
+ function responseMetadata(response) {
239
+ const retryAfterHeader = response.headers.get("retry-after");
240
+ const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : void 0;
241
+ return {
242
+ requestId: response.headers.get("x-request-id") ?? response.headers.get("trace-id") ?? void 0,
243
+ retryAfter: Number.isFinite(retryAfter) ? retryAfter : void 0
244
+ };
245
+ }
246
+ function normalizeBaseUrl(value, allowInsecureHttp) {
247
+ let url;
248
+ try {
249
+ url = new URL(value);
250
+ } catch {
251
+ throw new Error("Authyon: `baseUrl` must be an absolute URL");
252
+ }
253
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
254
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && (loopback || allowInsecureHttp))) {
255
+ throw new Error(
256
+ "Authyon: `baseUrl` must use HTTPS (HTTP is allowed only for loopback or with `allowInsecureHttp`)"
257
+ );
258
+ }
259
+ if (url.username || url.password || url.search || url.hash) {
260
+ throw new Error(
261
+ "Authyon: `baseUrl` cannot contain credentials, query parameters, or fragments"
262
+ );
263
+ }
264
+ return url.toString().replace(/\/+$/, "");
265
+ }
266
+
267
+ // ../../internal/core/http/query.ts
268
+ function appendQuery(path, params) {
269
+ if (!params) return path;
270
+ const query = new URLSearchParams();
271
+ for (const [key, value2] of Object.entries(params)) {
272
+ if (value2 !== void 0) query.set(key, String(value2));
273
+ }
274
+ const value = query.toString();
275
+ return value ? `${path}${path.includes("?") ? "&" : "?"}${value}` : path;
276
+ }
277
+
278
+ // ../../internal/core/http/jsonHttpClient.ts
279
+ var JsonHttpClient = class {
280
+ constructor(transport) {
281
+ this.transport = transport;
282
+ }
283
+ async send(path, options = {}) {
284
+ const headers = { ...options.headers };
285
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
286
+ try {
287
+ return await this.transport.request(appendQuery(path, options.query), {
288
+ method: options.method ?? "GET",
289
+ headers,
290
+ body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
291
+ });
292
+ } catch (cause) {
293
+ if (!(cause instanceof SharedTransportError)) throw cause;
294
+ throw new AuthyonError(0, { code: cause.code, title: cause.message }, { cause: cause.cause });
295
+ }
296
+ }
297
+ async parse(response) {
298
+ if (!response.ok) {
299
+ let body = {};
300
+ try {
301
+ body = await response.json();
302
+ } catch {
303
+ }
304
+ throw new AuthyonError(response.status, body, responseMetadata(response));
305
+ }
306
+ if (response.status === 204) return void 0;
307
+ return await response.json();
308
+ }
309
+ async request(path, options = {}) {
310
+ return this.parse(await this.send(path, options));
311
+ }
312
+ };
313
+
314
+ export {
315
+ ErrorCodes,
316
+ AuthyonError,
317
+ DEFAULT_BASE_URL,
318
+ DEFAULT_EXPIRY_SKEW_MS,
319
+ FetchHttpAdapter,
320
+ LoggingHttpAdapter,
321
+ createSharedTransport,
322
+ JsonHttpClient
323
+ };
@@ -0,0 +1,13 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+
9
+ export {
10
+ __privateGet,
11
+ __privateAdd,
12
+ __privateSet
13
+ };