@smartcrab/server 0.1.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.
@@ -0,0 +1,42 @@
1
+ import { type ResultAsync } from "./result.js";
2
+ export type WebhookVerificationHeaders = Headers | Readonly<Record<string, string>>;
3
+ export interface VerifyWebhookInput {
4
+ readonly headers: WebhookVerificationHeaders;
5
+ /** Exact request body text, read before any JSON parsing or re-serialization. */
6
+ readonly rawBody: string;
7
+ /** One active signing secret, or all candidate secrets during rotation. */
8
+ readonly secret: string | readonly string[];
9
+ /** Maximum accepted age or future clock skew in seconds; defaults to 300. */
10
+ readonly toleranceSeconds?: number;
11
+ /** Injectable clock returning Unix seconds; defaults to the current time. */
12
+ readonly clock?: () => number;
13
+ }
14
+ export interface VerifiedWebhook {
15
+ readonly eventId: string;
16
+ readonly timestampSeconds: number;
17
+ }
18
+ export type WebhookVerificationError = {
19
+ readonly type: "missing_header";
20
+ readonly header: string;
21
+ } | {
22
+ readonly type: "malformed_signature_header";
23
+ } | {
24
+ readonly type: "malformed_timestamp_header";
25
+ } | {
26
+ readonly type: "timestamp_too_old";
27
+ readonly ageSeconds: number;
28
+ readonly toleranceSeconds: number;
29
+ } | {
30
+ readonly type: "timestamp_in_future";
31
+ readonly skewSeconds: number;
32
+ readonly toleranceSeconds: number;
33
+ } | {
34
+ readonly type: "signature_mismatch";
35
+ } | {
36
+ readonly type: "crypto_operation_failed";
37
+ };
38
+ /**
39
+ * Verifies a Zeroword customer webhook using only WebCrypto. Preserve and pass
40
+ * the raw body as received; parsing and serializing JSON changes signed bytes.
41
+ */
42
+ export declare const verifyWebhook: (input: VerifyWebhookInput) => ResultAsync<VerifiedWebhook, WebhookVerificationError>;
@@ -0,0 +1,95 @@
1
+ import { Result } from "./result.js";
2
+ import { timingSafeEqual } from "./security.js";
3
+ const EVENT_ID_HEADER = "X-Auth-Event-Id";
4
+ const TIMESTAMP_HEADER = "X-Auth-Timestamp";
5
+ const SIGNATURE_HEADER = "X-Auth-Signature";
6
+ const DEFAULT_TOLERANCE_SECONDS = 300;
7
+ const TIMESTAMP_PATTERN = /^\d+$/;
8
+ const SIGNATURE_PATTERN = /^v1=([0-9a-f]+)$/;
9
+ const textEncoder = new TextEncoder();
10
+ const findHeader = (headers, name) => {
11
+ if ("get" in headers && typeof headers.get === "function") {
12
+ return headers.get(name) ?? undefined;
13
+ }
14
+ const target = name.toLowerCase();
15
+ for (const [key, value] of Object.entries(headers)) {
16
+ if (key.toLowerCase() === target)
17
+ return value;
18
+ }
19
+ return undefined;
20
+ };
21
+ const hmacSha256Hex = Result.fn({
22
+ try: async (input) => {
23
+ const secretBytes = new Uint8Array(textEncoder.encode(input.secret));
24
+ const key = await crypto.subtle.importKey("raw", secretBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
25
+ const payloadBytes = new Uint8Array(textEncoder.encode(`${input.timestamp}.${input.rawBody}`));
26
+ const signature = await crypto.subtle.sign("HMAC", key, payloadBytes);
27
+ const signatureBytes = new Uint8Array(signature);
28
+ let hex = "";
29
+ for (const byte of signatureBytes)
30
+ hex += byte.toString(16).padStart(2, "0");
31
+ return hex;
32
+ },
33
+ catch: () => ({ type: "crypto_operation_failed" }),
34
+ });
35
+ /**
36
+ * Verifies a Zeroword customer webhook using only WebCrypto. Preserve and pass
37
+ * the raw body as received; parsing and serializing JSON changes signed bytes.
38
+ */
39
+ export const verifyWebhook = async (input) => {
40
+ const eventId = findHeader(input.headers, EVENT_ID_HEADER);
41
+ if (eventId === undefined || eventId.length === 0) {
42
+ return Result.fail({ type: "missing_header", header: EVENT_ID_HEADER });
43
+ }
44
+ const timestampHeader = findHeader(input.headers, TIMESTAMP_HEADER);
45
+ if (timestampHeader === undefined || timestampHeader.length === 0) {
46
+ return Result.fail({ type: "missing_header", header: TIMESTAMP_HEADER });
47
+ }
48
+ if (!TIMESTAMP_PATTERN.test(timestampHeader)) {
49
+ return Result.fail({ type: "malformed_timestamp_header" });
50
+ }
51
+ const signatureHeader = findHeader(input.headers, SIGNATURE_HEADER);
52
+ if (signatureHeader === undefined || signatureHeader.length === 0) {
53
+ return Result.fail({ type: "missing_header", header: SIGNATURE_HEADER });
54
+ }
55
+ const signatureMatch = SIGNATURE_PATTERN.exec(signatureHeader);
56
+ const providedSignature = signatureMatch?.[1];
57
+ if (providedSignature === undefined) {
58
+ return Result.fail({ type: "malformed_signature_header" });
59
+ }
60
+ const timestampSeconds = Number.parseInt(timestampHeader, 10);
61
+ const toleranceSeconds = input.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
62
+ const nowSeconds = input.clock?.() ?? Math.floor(Date.now() / 1000);
63
+ if (timestampSeconds < nowSeconds - toleranceSeconds) {
64
+ return Result.fail({
65
+ type: "timestamp_too_old",
66
+ ageSeconds: nowSeconds - timestampSeconds,
67
+ toleranceSeconds,
68
+ });
69
+ }
70
+ if (timestampSeconds > nowSeconds + toleranceSeconds) {
71
+ return Result.fail({
72
+ type: "timestamp_in_future",
73
+ skewSeconds: timestampSeconds - nowSeconds,
74
+ toleranceSeconds,
75
+ });
76
+ }
77
+ const secretCount = typeof input.secret === "string" ? 1 : input.secret.length;
78
+ let matched = false;
79
+ for (let index = 0; index < secretCount; index += 1) {
80
+ const secret = typeof input.secret === "string" ? input.secret : input.secret[index];
81
+ if (secret === undefined)
82
+ continue;
83
+ const expected = await hmacSha256Hex({
84
+ secret,
85
+ timestamp: timestampHeader,
86
+ rawBody: input.rawBody,
87
+ });
88
+ if (Result.isFailure(expected))
89
+ return expected;
90
+ matched = timingSafeEqual(expected.value, providedSignature) || matched;
91
+ }
92
+ if (!matched)
93
+ return Result.fail({ type: "signature_mismatch" });
94
+ return Result.succeed({ eventId, timestampSeconds });
95
+ };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@smartcrab/server",
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "development": "./src/index.ts",
12
+ "import": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./*": {
16
+ "types": "./src/*.ts",
17
+ "development": "./src/*.ts",
18
+ "import": "./dist/*.js",
19
+ "default": "./dist/*.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "src"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "dependencies": {
30
+ "jose": "6.2.8",
31
+ "cookie": "2.0.1",
32
+ "@smartcrab/contracts-public": "0.1.0"
33
+ },
34
+ "devDependencies": {
35
+ "typescript": "5.9.3",
36
+ "vitest": "4.1.11",
37
+ "@cloudflare/workers-types": "5.20260804.1"
38
+ },
39
+ "scripts": {
40
+ "typecheck": "tsc --noEmit",
41
+ "test": "vitest run --passWithNoTests",
42
+ "build": "tsc -p tsconfig.build.json"
43
+ }
44
+ }
package/src/base64.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Base64 helpers (URL-safe and standard) implemented on bare WebCrypto-era
3
+ * globals so the SDK stays runtime-neutral (Workers + Node). Mirrors the
4
+ * alphabet handling in @smartcrab/identifiers, which is deliberately not a
5
+ * dependency of this package.
6
+ */
7
+
8
+ const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
9
+
10
+ /** base64url, no padding (RFC 4648 §5). Suitable for secrets, tokens and cookie values. */
11
+ export const base64UrlEncode = (bytes: Uint8Array): string => {
12
+ let out = "";
13
+ for (let i = 0; i < bytes.length; i += 3) {
14
+ const b0 = bytes[i] ?? 0;
15
+ const b1 = bytes[i + 1];
16
+ const b2 = bytes[i + 2];
17
+ out += BASE64URL_ALPHABET[b0 >> 2] ?? "";
18
+ out += BASE64URL_ALPHABET[((b0 & 0x03) << 4) | ((b1 ?? 0) >> 4)] ?? "";
19
+ if (b1 !== undefined) out += BASE64URL_ALPHABET[((b1 & 0x0f) << 2) | ((b2 ?? 0) >> 6)] ?? "";
20
+ if (b2 !== undefined) out += BASE64URL_ALPHABET[b2 & 0x3f] ?? "";
21
+ }
22
+ return out;
23
+ };
24
+
25
+ /** Throws on invalid characters — call only inside a `Result.fn` boundary. */
26
+ export const base64UrlDecode = (encoded: string): Uint8Array<ArrayBuffer> => {
27
+ const out: number[] = [];
28
+ let buffer = 0;
29
+ let bits = 0;
30
+ for (const char of encoded) {
31
+ const index = BASE64URL_ALPHABET.indexOf(char);
32
+ if (index < 0) {
33
+ throw new Error("invalid base64url input");
34
+ }
35
+ buffer = (buffer << 6) | index;
36
+ bits += 6;
37
+ if (bits >= 8) {
38
+ bits -= 8;
39
+ out.push((buffer >>> bits) & 0xff);
40
+ }
41
+ }
42
+ return new Uint8Array(out);
43
+ };
44
+
45
+ /** Standard base64 (RFC 4648 §4, with padding) — used for HTTP Basic client auth. */
46
+ export const base64StandardEncode = (bytes: Uint8Array): string => {
47
+ const urlEncoded = base64UrlEncode(bytes);
48
+ const standard = urlEncoded.replaceAll("-", "+").replaceAll("_", "/");
49
+ const remainder = bytes.length % 3;
50
+ if (remainder === 1) return `${standard}==`;
51
+ if (remainder === 2) return `${standard}=`;
52
+ return standard;
53
+ };
54
+
55
+ const BASE64URL_BODY_PATTERN = /^[A-Za-z0-9\-_]*$/;
56
+
57
+ /** True when the string only contains base64url characters (no padding). */
58
+ export const isBase64Url = (value: string): boolean => BASE64URL_BODY_PATTERN.test(value);
package/src/cookies.ts ADDED
@@ -0,0 +1,72 @@
1
+ import { parseCookie, stringifySetCookie } from "cookie";
2
+ import type { ServerAuthError } from "./errors.js";
3
+ import { Result, type ResultAsync } from "./result.js";
4
+
5
+ /**
6
+ * Cookie management (design.md §22.2).
7
+ *
8
+ * The session cookie is exactly:
9
+ *
10
+ * ```text
11
+ * __Host-auth-session
12
+ * Secure
13
+ * HttpOnly
14
+ * SameSite=Lax
15
+ * Path=/
16
+ * ```
17
+ *
18
+ * The `__Host-` prefix contract additionally forbids a `Domain` attribute, so
19
+ * this module **structurally cannot emit one**: the serializers below take no
20
+ * `domain` input at all. `createServerAuth` also rejects a configured
21
+ * `cookieDomain` at construction time (belt and braces). The PKCE handshake
22
+ * cookie follows the same rules (`__Host-auth-pkce`).
23
+ */
24
+
25
+ export const SESSION_COOKIE_NAME = "__Host-auth-session";
26
+ export const PKCE_COOKIE_NAME = "__Host-auth-pkce";
27
+
28
+ const BASE_ATTRIBUTES = {
29
+ httpOnly: true,
30
+ secure: true,
31
+ sameSite: "lax",
32
+ path: "/",
33
+ } as const;
34
+
35
+ const serialize = Result.fn({
36
+ try: async (input: {
37
+ readonly name: string;
38
+ readonly value: string;
39
+ readonly maxAgeSeconds: number;
40
+ readonly expiresEpoch?: Date;
41
+ }): Promise<string> =>
42
+ stringifySetCookie({
43
+ name: input.name,
44
+ value: input.value,
45
+ ...BASE_ATTRIBUTES,
46
+ maxAge: input.maxAgeSeconds,
47
+ ...(input.expiresEpoch !== undefined ? { expires: input.expiresEpoch } : {}),
48
+ }),
49
+ catch: (): ServerAuthError => ({ type: "cookie_serialization_failed" }),
50
+ });
51
+
52
+ /** Serializes a `Set-Cookie` value for one of the SDK's own `__Host-` cookies. */
53
+ export const serializeAuthCookie = (
54
+ name: string,
55
+ value: string,
56
+ maxAgeSeconds: number,
57
+ ): ResultAsync<string, ServerAuthError> => serialize({ name, value, maxAgeSeconds });
58
+
59
+ /** Serializes an immediate-expiry `Set-Cookie` that deletes the named cookie. */
60
+ export const clearAuthCookie = (name: string): ResultAsync<string, ServerAuthError> =>
61
+ serialize({ name, value: "", maxAgeSeconds: 0, expiresEpoch: new Date(0) });
62
+
63
+ /**
64
+ * Reads a single cookie from a request. `parseCookie` is non-throwing by
65
+ * design (its default decoder swallows malformed encodings and yields the raw
66
+ * value), so no `Result.fn` boundary is required here.
67
+ */
68
+ export const readCookie = (request: Request, name: string): string | undefined => {
69
+ const header = request.headers.get("cookie");
70
+ if (header === null) return undefined;
71
+ return parseCookie(header)[name];
72
+ };
package/src/errors.ts ADDED
@@ -0,0 +1,113 @@
1
+ import type { OAuthErrorCode } from "@smartcrab/contracts-public";
2
+
3
+ /**
4
+ * Typed error union for @smartcrab/server (IMPL_NOTES §3: discriminated
5
+ * union, snake_case `type`, `retryable?: true` marks transient failures an
6
+ * idempotent caller may retry with backoff).
7
+ *
8
+ * `detail`/`reason` fields only ever carry static, developer-facing strings —
9
+ * never response bodies, tokens, cookie values, or user PII (design.md §32.6).
10
+ */
11
+ export type ServerAuthError =
12
+ | { readonly type: "upstream_timeout"; readonly detail: string; readonly retryable?: true }
13
+ | { readonly type: "upstream_unreachable"; readonly detail: string; readonly retryable?: true }
14
+ | { readonly type: "response_too_large"; readonly detail: string; readonly retryable?: true }
15
+ | { readonly type: "discovery_failed"; readonly status: number; readonly retryable?: true }
16
+ | { readonly type: "discovery_invalid"; readonly detail: string; readonly retryable?: true }
17
+ | { readonly type: "jwks_fetch_failed"; readonly status: number; readonly retryable?: true }
18
+ | { readonly type: "jwks_invalid"; readonly detail: string; readonly retryable?: true }
19
+ | {
20
+ readonly type: "token_endpoint_rejected";
21
+ readonly code: OAuthErrorCode;
22
+ readonly retryable?: true;
23
+ }
24
+ | { readonly type: "token_endpoint_failed"; readonly status: number; readonly retryable?: true }
25
+ | { readonly type: "token_response_invalid"; readonly detail: string; readonly retryable?: true }
26
+ | { readonly type: "id_token_invalid"; readonly reason: string; readonly retryable?: true }
27
+ | { readonly type: "access_token_invalid"; readonly reason: string; readonly retryable?: true }
28
+ | { readonly type: "revocation_failed"; readonly status: number; readonly retryable?: true }
29
+ | { readonly type: "sealing_failed"; readonly retryable?: true }
30
+ | { readonly type: "seal_verification_failed"; readonly retryable?: true }
31
+ | { readonly type: "cookie_serialization_failed"; readonly retryable?: true }
32
+ | {
33
+ readonly type: "crypto_operation_failed";
34
+ readonly operation: string;
35
+ readonly retryable?: true;
36
+ };
37
+
38
+ /** True when the failure is transient (network, timeout, 5xx, `server_error`). */
39
+ export const isRetryableError = (error: ServerAuthError): boolean => error.retryable === true;
40
+
41
+ const PROBLEM_TYPE_BASE = "https://docs.example-auth.com/errors";
42
+
43
+ const titleForStatus = (status: number): string => {
44
+ switch (status) {
45
+ case 400:
46
+ return "Bad Request";
47
+ case 401:
48
+ return "Unauthorized";
49
+ case 403:
50
+ return "Forbidden";
51
+ case 405:
52
+ return "Method Not Allowed";
53
+ case 500:
54
+ return "Internal Server Error";
55
+ case 502:
56
+ return "Bad Gateway";
57
+ case 503:
58
+ return "Service Unavailable";
59
+ default:
60
+ return status >= 500 ? "Internal Server Error" : "Bad Request";
61
+ }
62
+ };
63
+
64
+ /**
65
+ * Minimal RFC 9457 problem response for the SDK's own HTTP boundaries.
66
+ * `@smartcrab/result` (which owns the full Problem Details helpers) is not
67
+ * a dependency of this package, so a deliberately small local equivalent lives
68
+ * here; the shape matches `problemDetailsResponse`.
69
+ */
70
+ export const problemResponse = (status: number, code: string, detail?: string): Response => {
71
+ const body = {
72
+ type: `${PROBLEM_TYPE_BASE}/${code.replaceAll("_", "-")}`,
73
+ title: titleForStatus(status),
74
+ status,
75
+ code,
76
+ ...(detail !== undefined ? { detail } : {}),
77
+ };
78
+ return new Response(JSON.stringify(body), {
79
+ status,
80
+ headers: { "content-type": "application/problem+json", "cache-control": "no-store" },
81
+ });
82
+ };
83
+
84
+ /** Maps an internal typed error to an HTTP problem response for the BFF handlers. */
85
+ export const errorToResponse = (error: ServerAuthError): Response => {
86
+ if (isRetryableError(error)) {
87
+ return problemResponse(503, error.type);
88
+ }
89
+ switch (error.type) {
90
+ case "id_token_invalid":
91
+ case "token_endpoint_rejected":
92
+ case "token_response_invalid":
93
+ return problemResponse(400, error.type);
94
+ case "access_token_invalid":
95
+ return problemResponse(401, error.type);
96
+ case "discovery_invalid":
97
+ case "jwks_invalid":
98
+ case "discovery_failed":
99
+ case "jwks_fetch_failed":
100
+ case "token_endpoint_failed":
101
+ case "revocation_failed":
102
+ case "response_too_large":
103
+ return problemResponse(502, error.type);
104
+ case "sealing_failed":
105
+ case "seal_verification_failed":
106
+ case "cookie_serialization_failed":
107
+ case "crypto_operation_failed":
108
+ return problemResponse(500, error.type);
109
+ case "upstream_timeout":
110
+ case "upstream_unreachable":
111
+ return problemResponse(503, error.type);
112
+ }
113
+ };
package/src/http.ts ADDED
@@ -0,0 +1,112 @@
1
+ import { base64StandardEncode } from "./base64.js";
2
+ import type { ServerAuthError } from "./errors.js";
3
+ import { Result } from "./result.js";
4
+
5
+ /**
6
+ * Fetch plumbing shared by every Authorization Server call. All upstream I/O
7
+ * goes through `fetchBoundedText`, which enforces:
8
+ *
9
+ * - a hard timeout (`AbortSignal.timeout`, default 5s — never hang a request),
10
+ * - a bounded response body (content-length pre-check + streaming cap), so a
11
+ * misbehaving or hostile upstream cannot exhaust isolate memory,
12
+ * - `redirect: "manual"` so upstream redirects are never followed into
13
+ * unexpected origins (responses surface as non-2xx statuses instead).
14
+ *
15
+ * Everything is wrapped in `Result.fn`; no raw try/catch (design.md §5.2).
16
+ */
17
+
18
+ export type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
19
+
20
+ export const DEFAULT_TIMEOUT_MS = 5000;
21
+
22
+ export interface FetchedText {
23
+ readonly status: number;
24
+ readonly body: string;
25
+ }
26
+
27
+ class ResponseTooLargeError extends Error {
28
+ constructor() {
29
+ super("response exceeded the configured byte budget");
30
+ this.name = "ResponseTooLargeError";
31
+ }
32
+ }
33
+
34
+ const isAbortLike = (cause: unknown): boolean =>
35
+ typeof cause === "object" &&
36
+ cause !== null &&
37
+ "name" in cause &&
38
+ (cause.name === "TimeoutError" || cause.name === "AbortError");
39
+
40
+ const readBounded = async (response: Response, maxBytes: number): Promise<string> => {
41
+ const stream = response.body;
42
+ if (stream === null) {
43
+ return response.text();
44
+ }
45
+ const reader = stream.getReader();
46
+ const chunks: Uint8Array[] = [];
47
+ let total = 0;
48
+ for (;;) {
49
+ const { done, value } = await reader.read();
50
+ if (done) break;
51
+ if (value !== undefined) {
52
+ total += value.byteLength;
53
+ if (total > maxBytes) {
54
+ await reader.cancel();
55
+ throw new ResponseTooLargeError();
56
+ }
57
+ chunks.push(value);
58
+ }
59
+ }
60
+ const merged = new Uint8Array(total);
61
+ let offset = 0;
62
+ for (const chunk of chunks) {
63
+ merged.set(chunk, offset);
64
+ offset += chunk.byteLength;
65
+ }
66
+ return new TextDecoder().decode(merged);
67
+ };
68
+
69
+ export const fetchBoundedText = Result.fn({
70
+ try: async (input: {
71
+ readonly fetchImpl: FetchLike;
72
+ readonly url: string;
73
+ readonly init?: RequestInit;
74
+ readonly timeoutMs: number;
75
+ readonly maxBytes: number;
76
+ }): Promise<FetchedText> => {
77
+ const response = await input.fetchImpl(input.url, {
78
+ ...input.init,
79
+ redirect: "manual",
80
+ signal: AbortSignal.timeout(input.timeoutMs),
81
+ });
82
+ const contentLength = response.headers.get("content-length");
83
+ if (contentLength !== null && Number(contentLength) > input.maxBytes) {
84
+ throw new ResponseTooLargeError();
85
+ }
86
+ const body = await readBounded(response, input.maxBytes);
87
+ return { status: response.status, body };
88
+ },
89
+ catch: (cause: unknown): ServerAuthError => {
90
+ if (cause instanceof ResponseTooLargeError) {
91
+ return { type: "response_too_large", detail: "upstream_body_exceeded_budget" };
92
+ }
93
+ if (isAbortLike(cause)) {
94
+ return {
95
+ type: "upstream_timeout",
96
+ detail: "upstream_call_exceeded_timeout",
97
+ retryable: true,
98
+ };
99
+ }
100
+ return { type: "upstream_unreachable", detail: "upstream_request_failed", retryable: true };
101
+ },
102
+ });
103
+
104
+ /**
105
+ * HTTP Basic credentials for `client_secret_basic` token-endpoint auth
106
+ * (design.md §15.4: `web_bff` clients use Basic or post auth). RFC 6749
107
+ * §2.3.1 form-encodes both parts before joining them.
108
+ */
109
+ export const basicAuthorizationHeader = (clientId: string, clientSecret: string): string => {
110
+ const userPass = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;
111
+ return `Basic ${base64StandardEncode(new TextEncoder().encode(userPass))}`;
112
+ };
package/src/index.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @smartcrab/server — runtime-neutral (Workers + Node) Web BFF auth SDK
3
+ * (design.md §22.2). Web-standard `Request`/`Response`/`fetch`/WebCrypto only.
4
+ *
5
+ * See server-auth.ts for the feature list and security.ts for the CSRF /
6
+ * open-redirect policy documentation.
7
+ */
8
+ export { createServerAuth, createAccessTokenVerifier } from "./server-auth.js";
9
+ export type {
10
+ AccessTokenVerifierOptions,
11
+ GetSessionOutcome,
12
+ RequireSessionOptions,
13
+ RequireSessionOutcome,
14
+ ServerAuth,
15
+ ServerAuthConfig,
16
+ UnauthenticatedReason,
17
+ VerifiedAccessToken,
18
+ } from "./server-auth.js";
19
+ export type { Session, SessionUser } from "./session.js";
20
+ export type { ServerAuthError } from "./errors.js";
21
+ export { isRetryableError } from "./errors.js";
22
+ export { PKCE_COOKIE_NAME, SESSION_COOKIE_NAME } from "./cookies.js";
23
+ export { sanitizeRedirectTarget, timingSafeEqual } from "./security.js";
24
+ export { Result } from "./result.js";
25
+ export type {
26
+ Failure,
27
+ Result as ResultValue,
28
+ ResultAsync,
29
+ ResultMaybeAsync,
30
+ Success,
31
+ } from "./result.js";
32
+ export type { FetchLike } from "./http.js";
33
+ export { verifyWebhook } from "./webhook.js";
34
+ export type {
35
+ VerifiedWebhook,
36
+ VerifyWebhookInput,
37
+ WebhookVerificationError,
38
+ WebhookVerificationHeaders,
39
+ } from "./webhook.js";