@orpc/server 2.0.0-beta.5 → 2.0.0-beta.50

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 (171) hide show
  1. package/README.md +137 -102
  2. package/dist/adapters/aws-lambda/handler.d.ts +27 -0
  3. package/dist/adapters/aws-lambda/handler.js +24 -0
  4. package/dist/adapters/aws-lambda/index.d.ts +4 -0
  5. package/dist/adapters/aws-lambda/index.js +2 -0
  6. package/dist/adapters/aws-lambda/rpc-handler.d.ts +19 -0
  7. package/dist/adapters/aws-lambda/rpc-handler.js +21 -0
  8. package/dist/adapters/crossws/handler.d.ts +47 -0
  9. package/dist/adapters/crossws/handler.js +53 -0
  10. package/dist/adapters/crossws/index.d.ts +3 -54
  11. package/dist/adapters/crossws/index.js +2 -0
  12. package/dist/adapters/crossws/rpc-handler.d.ts +16 -0
  13. package/dist/adapters/crossws/rpc-handler.js +18 -0
  14. package/dist/adapters/fastify/handler.d.ts +23 -0
  15. package/dist/adapters/fastify/handler.js +20 -0
  16. package/dist/adapters/fastify/index.d.ts +3 -0
  17. package/dist/adapters/fastify/index.js +2 -0
  18. package/dist/adapters/fastify/rpc-handler.d.ts +15 -0
  19. package/dist/adapters/fastify/rpc-handler.js +17 -0
  20. package/dist/adapters/fetch/handler.d.ts +25 -0
  21. package/dist/adapters/fetch/handler.js +22 -0
  22. package/dist/adapters/fetch/index.d.ts +4 -140
  23. package/dist/adapters/fetch/index.js +3 -0
  24. package/dist/adapters/fetch/rpc-handler.d.ts +17 -0
  25. package/dist/adapters/fetch/rpc-handler.js +19 -0
  26. package/dist/adapters/message-port/handler.d.ts +62 -0
  27. package/dist/adapters/message-port/handler.js +72 -0
  28. package/dist/adapters/message-port/index.d.ts +3 -74
  29. package/dist/adapters/message-port/index.js +2 -0
  30. package/dist/adapters/message-port/rpc-handler.d.ts +16 -0
  31. package/dist/adapters/message-port/rpc-handler.js +18 -0
  32. package/dist/adapters/node/handler.d.ts +23 -0
  33. package/dist/adapters/node/handler.js +20 -0
  34. package/dist/adapters/node/index.d.ts +4 -121
  35. package/dist/adapters/node/index.js +3 -0
  36. package/dist/adapters/node/rpc-handler.d.ts +16 -0
  37. package/dist/adapters/node/rpc-handler.js +18 -0
  38. package/dist/adapters/standard/codec.d.ts +16 -0
  39. package/dist/adapters/standard/handler.d.ts +68 -0
  40. package/dist/adapters/standard/handler.js +205 -0
  41. package/dist/adapters/standard/index.d.ts +7 -19
  42. package/dist/adapters/standard/index.js +4 -0
  43. package/dist/adapters/standard/plugin.d.ts +26 -0
  44. package/dist/adapters/standard/plugin.js +14 -0
  45. package/dist/adapters/standard/rpc-handler-codec.d.ts +42 -0
  46. package/dist/adapters/standard/rpc-handler-codec.js +50 -0
  47. package/dist/adapters/standard/rpc-matcher.d.ts +53 -0
  48. package/dist/adapters/standard/rpc-matcher.js +106 -0
  49. package/dist/adapters/standard/utils.d.ts +10 -0
  50. package/dist/adapters/standard/utils.js +8 -0
  51. package/dist/adapters/standard-peer/index.d.ts +2 -16
  52. package/dist/adapters/standard-peer/index.js +1 -0
  53. package/dist/adapters/standard-peer/utils.d.ts +6 -0
  54. package/dist/adapters/standard-peer/utils.js +13 -0
  55. package/dist/adapters/websocket/handler.d.ts +61 -0
  56. package/dist/adapters/websocket/handler.js +75 -0
  57. package/dist/adapters/websocket/index.d.ts +3 -61
  58. package/dist/adapters/websocket/index.js +2 -0
  59. package/dist/adapters/websocket/rpc-handler.d.ts +16 -0
  60. package/dist/adapters/websocket/rpc-handler.js +18 -0
  61. package/dist/builder-variants.d.ts +226 -0
  62. package/dist/builder.d.ts +126 -0
  63. package/dist/builder.js +200 -0
  64. package/dist/constants.d.ts +2 -0
  65. package/dist/constants.js +4 -0
  66. package/dist/context.d.ts +6 -0
  67. package/dist/extensions/callable.d.ts +11 -10
  68. package/dist/extensions/callable.js +8 -0
  69. package/dist/helpers/base64url.d.ts +31 -0
  70. package/dist/helpers/base64url.js +48 -0
  71. package/dist/helpers/cookie.d.ts +50 -0
  72. package/dist/helpers/cookie.js +62 -0
  73. package/dist/helpers/encryption.d.ts +28 -0
  74. package/dist/helpers/encryption.js +90 -0
  75. package/dist/helpers/index.d.ts +5 -149
  76. package/dist/helpers/index.js +4 -0
  77. package/dist/helpers/signing.d.ts +50 -0
  78. package/dist/helpers/signing.js +78 -0
  79. package/dist/implementer-procedure.d.ts +15 -0
  80. package/dist/implementer-procedure.js +37 -0
  81. package/dist/implementer-router.d.ts +34 -0
  82. package/dist/implementer-router.js +98 -0
  83. package/dist/implementer.d.ts +16 -0
  84. package/dist/implementer.js +30 -0
  85. package/dist/index.d.ts +22 -196
  86. package/dist/index.js +16 -0
  87. package/dist/lazy.d.ts +20 -0
  88. package/dist/lazy.js +20 -0
  89. package/dist/middleware-decorated.d.ts +9 -0
  90. package/dist/middleware-decorated.js +67 -0
  91. package/dist/middleware.d.ts +54 -0
  92. package/dist/plugins/batch.d.ts +102 -0
  93. package/dist/plugins/batch.js +371 -0
  94. package/dist/plugins/cors.d.ts +69 -0
  95. package/dist/plugins/cors.js +119 -0
  96. package/dist/plugins/get-method-csrf-protection.d.ts +25 -0
  97. package/dist/plugins/get-method-csrf-protection.js +48 -0
  98. package/dist/plugins/head-method.d.ts +25 -0
  99. package/dist/plugins/head-method.js +107 -0
  100. package/dist/plugins/index.d.ts +15 -197
  101. package/dist/plugins/index.js +14 -0
  102. package/dist/plugins/method-override.d.ts +40 -0
  103. package/dist/plugins/method-override.js +54 -0
  104. package/dist/plugins/request-compression.d.ts +18 -0
  105. package/dist/plugins/request-compression.js +55 -0
  106. package/dist/plugins/request-headers.d.ts +24 -0
  107. package/dist/plugins/request-headers.js +28 -0
  108. package/dist/plugins/request-limit.d.ts +32 -0
  109. package/dist/plugins/request-limit.js +61 -0
  110. package/dist/plugins/response-compression.d.ts +62 -0
  111. package/dist/plugins/response-compression.js +157 -0
  112. package/dist/plugins/response-headers.d.ts +32 -0
  113. package/dist/plugins/response-headers.js +44 -0
  114. package/dist/plugins/rethrow.d.ts +35 -0
  115. package/dist/plugins/rethrow.js +47 -0
  116. package/dist/plugins/signal-sync.d.ts +15 -0
  117. package/dist/plugins/signal-sync.js +76 -0
  118. package/dist/plugins/timeout.d.ts +39 -0
  119. package/dist/plugins/timeout.js +62 -0
  120. package/dist/procedure-client.d.ts +18 -0
  121. package/dist/procedure-client.js +158 -0
  122. package/dist/procedure-decorated.d.ts +10 -0
  123. package/dist/procedure-decorated.js +36 -0
  124. package/dist/procedure-utils.d.ts +21 -0
  125. package/dist/procedure-utils.js +48 -0
  126. package/dist/procedure.d.ts +72 -0
  127. package/dist/procedure.js +18 -0
  128. package/dist/router-client.d.ts +21 -0
  129. package/dist/router-client.js +35 -0
  130. package/dist/router-hidden.js +12 -0
  131. package/dist/router-utils.d.ts +31 -0
  132. package/dist/router-utils.js +157 -0
  133. package/dist/router.d.ts +58 -0
  134. package/package.json +95 -63
  135. package/dist/adapters/crossws/index.d.mts +0 -54
  136. package/dist/adapters/crossws/index.mjs +0 -64
  137. package/dist/adapters/fetch/index.d.mts +0 -140
  138. package/dist/adapters/fetch/index.mjs +0 -204
  139. package/dist/adapters/message-port/index.d.mts +0 -74
  140. package/dist/adapters/message-port/index.mjs +0 -90
  141. package/dist/adapters/node/index.d.mts +0 -121
  142. package/dist/adapters/node/index.mjs +0 -179
  143. package/dist/adapters/standard/index.d.mts +0 -19
  144. package/dist/adapters/standard/index.mjs +0 -8
  145. package/dist/adapters/standard-peer/index.d.mts +0 -16
  146. package/dist/adapters/standard-peer/index.mjs +0 -2
  147. package/dist/adapters/websocket/index.d.mts +0 -61
  148. package/dist/adapters/websocket/index.mjs +0 -76
  149. package/dist/extensions/callable.d.mts +0 -10
  150. package/dist/extensions/callable.mjs +0 -11
  151. package/dist/helpers/index.d.mts +0 -149
  152. package/dist/helpers/index.mjs +0 -198
  153. package/dist/index.d.mts +0 -196
  154. package/dist/index.mjs +0 -385
  155. package/dist/plugins/index.d.mts +0 -197
  156. package/dist/plugins/index.mjs +0 -357
  157. package/dist/shared/server.BL22TloH.d.mts +0 -184
  158. package/dist/shared/server.BL22TloH.d.ts +0 -184
  159. package/dist/shared/server.BsNNjG5J.d.mts +0 -61
  160. package/dist/shared/server.BwHnWUuN.mjs +0 -222
  161. package/dist/shared/server.CX4vUnDk.mjs +0 -11
  162. package/dist/shared/server.Cj5lgPuG.d.mts +0 -66
  163. package/dist/shared/server.CjOb6ItT.mjs +0 -41
  164. package/dist/shared/server.CrlKQucM.mjs +0 -233
  165. package/dist/shared/server.DBANIheG.d.ts +0 -104
  166. package/dist/shared/server.DJIkub_t.d.mts +0 -104
  167. package/dist/shared/server.D_QauotT.mjs +0 -30
  168. package/dist/shared/server.GDpX6Df8.mjs +0 -271
  169. package/dist/shared/server.Pa0F03f_.d.ts +0 -61
  170. package/dist/shared/server.W91HSRkE.mjs +0 -9
  171. package/dist/shared/server.d_2NS3g5.d.ts +0 -66
@@ -0,0 +1,48 @@
1
+ import { encodeBase64 } from "@orpc/shared";
2
+ // src/helpers/base64url.ts
3
+ /**
4
+ * Encodes a Uint8Array to base64url format
5
+ * Base64url is URL-safe and doesn't use padding
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const text = "Hello World"
10
+ * const encoded = encodeBase64url(new TextEncoder().encode(text))
11
+ * const decoded = decodeBase64url(encoded)
12
+ * expect(new TextDecoder().decode(decoded)).toEqual(text)
13
+ * ```
14
+ *
15
+ * @see {@link https://orpc.dev/docs/helpers/base64url | Base64Url Helpers}
16
+ */
17
+ function encodeBase64url(data) {
18
+ return encodeBase64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
19
+ }
20
+ /**
21
+ * Decodes a base64url string to Uint8Array
22
+ * Only accepts canonical, unpadded base64url (the form produced by `encodeBase64url`),
23
+ * returns undefined for anything else, including padded or standard base64 input
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const text = "Hello World"
28
+ * const encoded = encodeBase64url(new TextEncoder().encode(text))
29
+ * const decoded = decodeBase64url(encoded)
30
+ * expect(new TextDecoder().decode(decoded)).toEqual(text)
31
+ * ```
32
+ *
33
+ * @see {@link https://orpc.dev/docs/helpers/base64url | Base64Url Helpers}
34
+ */
35
+ function decodeBase64url(base64url) {
36
+ try {
37
+ if (typeof base64url !== "string") return;
38
+ let base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
39
+ while (base64.length % 4) base64 += "=";
40
+ const binaryString = atob(base64);
41
+ const bytes = new Uint8Array(binaryString.length);
42
+ for (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);
43
+ return encodeBase64url(bytes) === base64url ? bytes : void 0;
44
+ } catch {
45
+ return;
46
+ }
47
+ }
48
+ export { decodeBase64url, encodeBase64url };
@@ -0,0 +1,50 @@
1
+ import { ParseOptions, SetCookie, StringifyOptions } from "cookie";
2
+ export interface SetCookieOptions extends Omit<SetCookie, "name" | "value">, StringifyOptions {
3
+ /**
4
+ * Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4).
5
+ *
6
+ * @default '/'
7
+ */
8
+ path?: string;
9
+ }
10
+ /**
11
+ * Sets a cookie in the response headers.
12
+ *
13
+ * Does nothing if `headers` is `undefined`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const headers = new Headers()
18
+ *
19
+ * setCookie(headers, 'sessionId', 'abc123', { httpOnly: true, maxAge: 3600 })
20
+ *
21
+ * expect(headers.get('Set-Cookie')).toBe('sessionId=abc123; Max-Age=3600; Path=/; HttpOnly')
22
+ * ```
23
+ *
24
+ * @see {@link https://orpc.dev/docs/helpers/cookie | Cookie Helpers}
25
+ */
26
+ export declare function setCookie(headers: Headers | undefined, name: string, value: string, options?: SetCookieOptions): void;
27
+ export interface GetCookieOptions extends ParseOptions {}
28
+ /**
29
+ * Gets a cookie value from request headers
30
+ *
31
+ * Returns `undefined` if the cookie is not found or headers are `undefined`.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const headers = new Headers({ 'Cookie': 'sessionId=abc123; theme=dark' })
36
+ *
37
+ * const sessionId = getCookie(headers, 'sessionId')
38
+ *
39
+ * expect(sessionId).toEqual('abc123')
40
+ * ```
41
+ *
42
+ * @see {@link https://orpc.dev/docs/helpers/cookie | Cookie Helpers}
43
+ */
44
+ export declare function getCookie(headers: Headers | undefined, name: string, options?: GetCookieOptions): string | undefined;
45
+ /**
46
+ * Deletes a cookie by marking it expired.
47
+ *
48
+ * @see {@link https://orpc.dev/docs/helpers/cookie | Cookie Helpers}
49
+ */
50
+ export declare function deleteCookie(headers: Headers | undefined, name: string, options?: Omit<SetCookieOptions, "maxAge">): void;
@@ -0,0 +1,62 @@
1
+ import { parseCookie, stringifySetCookie } from "cookie";
2
+ // src/helpers/cookie.ts
3
+ /**
4
+ * Sets a cookie in the response headers.
5
+ *
6
+ * Does nothing if `headers` is `undefined`.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const headers = new Headers()
11
+ *
12
+ * setCookie(headers, 'sessionId', 'abc123', { httpOnly: true, maxAge: 3600 })
13
+ *
14
+ * expect(headers.get('Set-Cookie')).toBe('sessionId=abc123; Max-Age=3600; Path=/; HttpOnly')
15
+ * ```
16
+ *
17
+ * @see {@link https://orpc.dev/docs/helpers/cookie | Cookie Helpers}
18
+ */
19
+ function setCookie(headers, name, value, options = {}) {
20
+ if (headers === void 0) return;
21
+ const cookieString = stringifySetCookie({
22
+ path: "/",
23
+ ...options,
24
+ name,
25
+ value
26
+ }, options);
27
+ headers.append("Set-Cookie", cookieString);
28
+ }
29
+ /**
30
+ * Gets a cookie value from request headers
31
+ *
32
+ * Returns `undefined` if the cookie is not found or headers are `undefined`.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const headers = new Headers({ 'Cookie': 'sessionId=abc123; theme=dark' })
37
+ *
38
+ * const sessionId = getCookie(headers, 'sessionId')
39
+ *
40
+ * expect(sessionId).toEqual('abc123')
41
+ * ```
42
+ *
43
+ * @see {@link https://orpc.dev/docs/helpers/cookie | Cookie Helpers}
44
+ */
45
+ function getCookie(headers, name, options = {}) {
46
+ if (headers === void 0) return;
47
+ const cookieHeader = headers.get("cookie");
48
+ if (cookieHeader === null) return;
49
+ return parseCookie(cookieHeader, options)[name];
50
+ }
51
+ /**
52
+ * Deletes a cookie by marking it expired.
53
+ *
54
+ * @see {@link https://orpc.dev/docs/helpers/cookie | Cookie Helpers}
55
+ */
56
+ function deleteCookie(headers, name, options = {}) {
57
+ return setCookie(headers, name, "", {
58
+ ...options,
59
+ maxAge: 0
60
+ });
61
+ }
62
+ export { deleteCookie, getCookie, setCookie };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Encrypts a string using AES-GCM with a secret key.
3
+ * The output is base64url encoded to be URL-safe.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * const encrypted = await encrypt("Hello, World!", "test-secret-key")
8
+ * const decrypted = await decrypt(encrypted, "test-secret-key")
9
+ * expect(decrypted).toBe("Hello, World!")
10
+ * ```
11
+ *
12
+ * @see {@link https://orpc.dev/docs/helpers/encryption | Encryption Helpers}
13
+ */
14
+ export declare function encrypt(value: string, secret: string): Promise<string>;
15
+ /**
16
+ * Decrypts a base64url encoded string using AES-GCM with a secret key.
17
+ * Returns the original string if decryption is successful, or undefined if it fails.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const encrypted = await encrypt("Hello, World!", "test-secret-key")
22
+ * const decrypted = await decrypt(encrypted, "test-secret-key")
23
+ * expect(decrypted).toBe("Hello, World!")
24
+ * ```
25
+ *
26
+ * @see {@link https://orpc.dev/docs/helpers/encryption | Encryption Helpers}
27
+ */
28
+ export declare function decrypt(encrypted: string | undefined | null, secret: string): Promise<string | undefined>;
@@ -0,0 +1,90 @@
1
+ import { decodeBase64url, encodeBase64url } from "./base64url.js";
2
+ // src/helpers/encryption.ts
3
+ const PBKDF2_CONFIG = {
4
+ name: "PBKDF2",
5
+ /**
6
+ * Below the OWASP Password Storage Cheat Sheet recommendation of 600,000 iterations
7
+ * for PBKDF2-HMAC-SHA256. The output does not record the iteration count, so changing
8
+ * it would make existing ciphertexts undecryptable; raising it needs a versioned format.
9
+ */
10
+ iterations: 6e4,
11
+ hash: "SHA-256"
12
+ };
13
+ const AES_GCM_CONFIG = {
14
+ name: "AES-GCM",
15
+ length: 256
16
+ };
17
+ const CRYPTO_CONSTANTS = {
18
+ SALT_LENGTH: 16,
19
+ IV_LENGTH: 12
20
+ };
21
+ /**
22
+ * Encrypts a string using AES-GCM with a secret key.
23
+ * The output is base64url encoded to be URL-safe.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const encrypted = await encrypt("Hello, World!", "test-secret-key")
28
+ * const decrypted = await decrypt(encrypted, "test-secret-key")
29
+ * expect(decrypted).toBe("Hello, World!")
30
+ * ```
31
+ *
32
+ * @see {@link https://orpc.dev/docs/helpers/encryption | Encryption Helpers}
33
+ */
34
+ async function encrypt(value, secret) {
35
+ const encoder = new TextEncoder();
36
+ const data = encoder.encode(value);
37
+ const salt = crypto.getRandomValues(new Uint8Array(CRYPTO_CONSTANTS.SALT_LENGTH));
38
+ const keyMaterial = await crypto.subtle.importKey("raw", encoder.encode(secret), PBKDF2_CONFIG.name, false, ["deriveKey"]);
39
+ const key = await crypto.subtle.deriveKey({
40
+ ...PBKDF2_CONFIG,
41
+ salt
42
+ }, keyMaterial, AES_GCM_CONFIG, false, ["encrypt"]);
43
+ const iv = crypto.getRandomValues(new Uint8Array(CRYPTO_CONSTANTS.IV_LENGTH));
44
+ const encrypted = await crypto.subtle.encrypt({
45
+ name: AES_GCM_CONFIG.name,
46
+ iv
47
+ }, key, data);
48
+ const result = new Uint8Array(salt.length + iv.length + encrypted.byteLength);
49
+ result.set(salt, 0);
50
+ result.set(iv, salt.length);
51
+ result.set(new Uint8Array(encrypted), salt.length + iv.length);
52
+ return encodeBase64url(result);
53
+ }
54
+ /**
55
+ * Decrypts a base64url encoded string using AES-GCM with a secret key.
56
+ * Returns the original string if decryption is successful, or undefined if it fails.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * const encrypted = await encrypt("Hello, World!", "test-secret-key")
61
+ * const decrypted = await decrypt(encrypted, "test-secret-key")
62
+ * expect(decrypted).toBe("Hello, World!")
63
+ * ```
64
+ *
65
+ * @see {@link https://orpc.dev/docs/helpers/encryption | Encryption Helpers}
66
+ */
67
+ async function decrypt(encrypted, secret) {
68
+ try {
69
+ const data = decodeBase64url(encrypted);
70
+ if (data === void 0) return;
71
+ const encoder = new TextEncoder();
72
+ const decoder = new TextDecoder();
73
+ const salt = data.slice(0, CRYPTO_CONSTANTS.SALT_LENGTH);
74
+ const iv = data.slice(CRYPTO_CONSTANTS.SALT_LENGTH, CRYPTO_CONSTANTS.SALT_LENGTH + CRYPTO_CONSTANTS.IV_LENGTH);
75
+ const encryptedData = data.slice(CRYPTO_CONSTANTS.SALT_LENGTH + CRYPTO_CONSTANTS.IV_LENGTH);
76
+ const keyMaterial = await crypto.subtle.importKey("raw", encoder.encode(secret), PBKDF2_CONFIG.name, false, ["deriveKey"]);
77
+ const key = await crypto.subtle.deriveKey({
78
+ ...PBKDF2_CONFIG,
79
+ salt
80
+ }, keyMaterial, AES_GCM_CONFIG, false, ["decrypt"]);
81
+ const decrypted = await crypto.subtle.decrypt({
82
+ name: AES_GCM_CONFIG.name,
83
+ iv
84
+ }, key, encryptedData);
85
+ return decoder.decode(decrypted);
86
+ } catch {
87
+ return;
88
+ }
89
+ }
90
+ export { decrypt, encrypt };
@@ -1,149 +1,5 @@
1
- import { ParseOptions, SerializeOptions } from 'cookie';
2
-
3
- /**
4
- * Encodes a Uint8Array to base64url format
5
- * Base64url is URL-safe and doesn't use padding
6
- *
7
- * @example
8
- * ```ts
9
- * const text = "Hello World"
10
- * const encoded = encodeBase64url(new TextEncoder().encode(text))
11
- * const decoded = decodeBase64url(encoded)
12
- * expect(new TextDecoder().decode(decoded)).toEqual(text)
13
- * ```
14
- */
15
- declare function encodeBase64url(data: Uint8Array): string;
16
- /**
17
- * Decodes a base64url string to Uint8Array
18
- * Returns undefined if the input is invalid
19
- *
20
- * @example
21
- * ```ts
22
- * const text = "Hello World"
23
- * const encoded = encodeBase64url(new TextEncoder().encode(text))
24
- * const decoded = decodeBase64url(encoded)
25
- * expect(new TextDecoder().decode(decoded)).toEqual(text)
26
- * ```
27
- */
28
- declare function decodeBase64url(base64url: string | undefined | null): Uint8Array<ArrayBuffer> | undefined;
29
-
30
- interface SetCookieOptions extends SerializeOptions {
31
- /**
32
- * Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4).
33
- *
34
- * @default '/'
35
- */
36
- path?: string;
37
- }
38
- /**
39
- * Sets a cookie in the response headers,
40
- *
41
- * Does nothing if `headers` is `undefined`.
42
- *
43
- * @example
44
- * ```ts
45
- * const headers = new Headers()
46
- *
47
- * setCookie(headers, 'sessionId', 'abc123', { httpOnly: true, maxAge: 3600 })
48
- *
49
- * expect(headers.get('Set-Cookie')).toBe('sessionId=abc123; HttpOnly; Max-Age=3600')
50
- * ```
51
- *
52
- */
53
- declare function setCookie(headers: Headers | undefined, name: string, value: string, options?: SetCookieOptions): void;
54
- interface GetCookieOptions extends ParseOptions {
55
- }
56
- /**
57
- * Gets a cookie value from request headers
58
- *
59
- * Returns `undefined` if the cookie is not found or headers are `undefined`.
60
- *
61
- * @example
62
- * ```ts
63
- * const headers = new Headers({ 'Cookie': 'sessionId=abc123; theme=dark' })
64
- *
65
- * const sessionId = getCookie(headers, 'sessionId')
66
- *
67
- * expect(sessionId).toEqual('abc123')
68
- * ```
69
- */
70
- declare function getCookie(headers: Headers | undefined, name: string, options?: GetCookieOptions): string | undefined;
71
- /**
72
- * Deletes a cookie by marking it expired.
73
- */
74
- declare function deleteCookie(headers: Headers | undefined, name: string, options?: Omit<SetCookieOptions, 'maxAge'>): void;
75
-
76
- /**
77
- * Encrypts a string using AES-GCM with a secret key.
78
- * The output is base64url encoded to be URL-safe.
79
- *
80
- * @example
81
- * ```ts
82
- * const encrypted = await encrypt("Hello, World!", "test-secret-key")
83
- * const decrypted = await decrypt(encrypted, "test-secret-key")
84
- * expect(decrypted).toBe("Hello, World!")
85
- * ```
86
- */
87
- declare function encrypt(value: string, secret: string): Promise<string>;
88
- /**
89
- * Decrypts a base64url encoded string using AES-GCM with a secret key.
90
- * Returns the original string if decryption is successful, or undefined if it fails.
91
- *
92
- * @example
93
- * ```ts
94
- * const encrypted = await encrypt("Hello, World!", "test-secret-key")
95
- * const decrypted = await decrypt(encrypted, "test-secret-key")
96
- * expect(decrypted).toBe("Hello, World!")
97
- * ```
98
- */
99
- declare function decrypt(encrypted: string | undefined | null, secret: string): Promise<string | undefined>;
100
-
101
- /**
102
- * Signs a string value using HMAC-SHA256 with a secret key.
103
- *
104
- * This function creates a cryptographic signature that can be used to verify
105
- * the integrity and authenticity of the data. The signature is appended to
106
- * the original value, separated by a dot, using base64url encoding (no padding).
107
- *
108
- *
109
- * @example
110
- * ```ts
111
- * const signedValue = await sign("user123", "my-secret-key")
112
- * expect(signedValue).toEqual("user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA")
113
- * ```
114
- */
115
- declare function sign(value: string, secret: string): Promise<string>;
116
- /**
117
- * Verifies and extracts the original value from a signed string.
118
- *
119
- * This function validates the signature of a previously signed value using the same
120
- * secret key. If the signature is valid, it returns the original value. If the
121
- * signature is invalid or the format is incorrect, it returns undefined.
122
- *
123
- *
124
- * @example
125
- * ```ts
126
- * const signedValue = "user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA"
127
- * const originalValue = await unsign(signedValue, "my-secret-key")
128
- * expect(originalValue).toEqual("user123")
129
- * ```
130
- */
131
- declare function unsign(signedValue: string | undefined | null, secret: string): Promise<string | undefined>;
132
- /**
133
- * Extracts the value part from a signed string without verification.
134
- *
135
- * This function simply extracts the original value from a signed string
136
- * without performing any signature verification. It's useful when you need
137
- * to access the value quickly without the overhead of cryptographic verification.
138
- *
139
- * @example
140
- * ```ts
141
- * const signedValue = "user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA"
142
- * const value = getSignedValue(signedValue)
143
- * expect(value).toEqual("user123")
144
- * ```
145
- */
146
- declare function getSignedValue(signedValue: string | undefined | null): string | undefined;
147
-
148
- export { decodeBase64url, decrypt, deleteCookie, encodeBase64url, encrypt, getCookie, getSignedValue, setCookie, sign, unsign };
149
- export type { GetCookieOptions, SetCookieOptions };
1
+ import { decodeBase64url, encodeBase64url } from "./base64url.js";
2
+ import { GetCookieOptions, SetCookieOptions, deleteCookie, getCookie, setCookie } from "./cookie.js";
3
+ import { decrypt, encrypt } from "./encryption.js";
4
+ import { getSignedValue, sign, unsign } from "./signing.js";
5
+ export { GetCookieOptions, SetCookieOptions, decodeBase64url, decrypt, deleteCookie, encodeBase64url, encrypt, getCookie, getSignedValue, setCookie, sign, unsign };
@@ -0,0 +1,4 @@
1
+ export { decodeBase64url, encodeBase64url } from "./base64url.js";
2
+ export { deleteCookie, getCookie, setCookie } from "./cookie.js";
3
+ export { decrypt, encrypt } from "./encryption.js";
4
+ export { getSignedValue, sign, unsign } from "./signing.js";
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Signs a string value using HMAC-SHA256 with a secret key.
3
+ *
4
+ * This function creates a cryptographic signature that can be used to verify
5
+ * the integrity and authenticity of the data. The signature is appended to
6
+ * the original value, separated by a dot, using base64url encoding (no padding).
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const signedValue = await sign("user123", "my-secret-key")
11
+ * expect(signedValue).toEqual("user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA")
12
+ * ```
13
+ *
14
+ * @see {@link https://orpc.dev/docs/helpers/signing | Signing Helpers}
15
+ */
16
+ export declare function sign(value: string, secret: string): Promise<string>;
17
+ /**
18
+ * Verifies and extracts the original value from a signed string.
19
+ *
20
+ * This function validates the signature of a previously signed value using the same
21
+ * secret key. If the signature is valid, it returns the original value. If the
22
+ * signature is invalid or the format is incorrect, it returns undefined.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const signedValue = "user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA"
27
+ * const originalValue = await unsign(signedValue, "my-secret-key")
28
+ * expect(originalValue).toEqual("user123")
29
+ * ```
30
+ *
31
+ * @see {@link https://orpc.dev/docs/helpers/signing | Signing Helpers}
32
+ */
33
+ export declare function unsign(signedValue: string | undefined | null, secret: string): Promise<string | undefined>;
34
+ /**
35
+ * Extracts the value part from a signed string without verification.
36
+ *
37
+ * This function simply extracts the original value from a signed string
38
+ * without performing any signature verification. It's useful when you need
39
+ * to access the value quickly without the overhead of cryptographic verification.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const signedValue = "user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA"
44
+ * const value = getSignedValue(signedValue)
45
+ * expect(value).toEqual("user123")
46
+ * ```
47
+ *
48
+ * @see {@link https://orpc.dev/docs/helpers/signing | Signing Helpers}
49
+ */
50
+ export declare function getSignedValue(signedValue: string | undefined | null): string | undefined;
@@ -0,0 +1,78 @@
1
+ import { decodeBase64url, encodeBase64url } from "./base64url.js";
2
+ // src/helpers/signing.ts
3
+ const ALGORITHM = {
4
+ name: "HMAC",
5
+ hash: "SHA-256"
6
+ };
7
+ /**
8
+ * Signs a string value using HMAC-SHA256 with a secret key.
9
+ *
10
+ * This function creates a cryptographic signature that can be used to verify
11
+ * the integrity and authenticity of the data. The signature is appended to
12
+ * the original value, separated by a dot, using base64url encoding (no padding).
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const signedValue = await sign("user123", "my-secret-key")
17
+ * expect(signedValue).toEqual("user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA")
18
+ * ```
19
+ *
20
+ * @see {@link https://orpc.dev/docs/helpers/signing | Signing Helpers}
21
+ */
22
+ async function sign(value, secret) {
23
+ const encoder = new TextEncoder();
24
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), ALGORITHM, false, ["sign"]);
25
+ const signature = await crypto.subtle.sign(ALGORITHM, key, encoder.encode(value));
26
+ return `${value}.${encodeBase64url(new Uint8Array(signature))}`;
27
+ }
28
+ /**
29
+ * Verifies and extracts the original value from a signed string.
30
+ *
31
+ * This function validates the signature of a previously signed value using the same
32
+ * secret key. If the signature is valid, it returns the original value. If the
33
+ * signature is invalid or the format is incorrect, it returns undefined.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * const signedValue = "user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA"
38
+ * const originalValue = await unsign(signedValue, "my-secret-key")
39
+ * expect(originalValue).toEqual("user123")
40
+ * ```
41
+ *
42
+ * @see {@link https://orpc.dev/docs/helpers/signing | Signing Helpers}
43
+ */
44
+ async function unsign(signedValue, secret) {
45
+ if (typeof signedValue !== "string") return;
46
+ const lastDotIndex = signedValue.lastIndexOf(".");
47
+ if (lastDotIndex === -1) return;
48
+ const value = signedValue.slice(0, lastDotIndex);
49
+ const signatureBase64url = signedValue.slice(lastDotIndex + 1);
50
+ const signature = decodeBase64url(signatureBase64url);
51
+ if (signature === void 0) return;
52
+ const encoder = new TextEncoder();
53
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), ALGORITHM, false, ["verify"]);
54
+ return await crypto.subtle.verify(ALGORITHM, key, signature, encoder.encode(value)) ? value : void 0;
55
+ }
56
+ /**
57
+ * Extracts the value part from a signed string without verification.
58
+ *
59
+ * This function simply extracts the original value from a signed string
60
+ * without performing any signature verification. It's useful when you need
61
+ * to access the value quickly without the overhead of cryptographic verification.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * const signedValue = "user123.oneQsU0r5dvwQFHFEjjV1uOI_IR3gZfkYHij3TRauVA"
66
+ * const value = getSignedValue(signedValue)
67
+ * expect(value).toEqual("user123")
68
+ * ```
69
+ *
70
+ * @see {@link https://orpc.dev/docs/helpers/signing | Signing Helpers}
71
+ */
72
+ function getSignedValue(signedValue) {
73
+ if (typeof signedValue !== "string") return;
74
+ const lastDotIndex = signedValue.lastIndexOf(".");
75
+ if (lastDotIndex === -1) return;
76
+ return signedValue.slice(0, lastDotIndex);
77
+ }
78
+ export { getSignedValue, sign, unsign };
@@ -0,0 +1,15 @@
1
+ import { BuilderDefinition } from "./builder.js";
2
+ import { Context, MergedContext, MergedInitialContext } from "./context.js";
3
+ import { Middleware } from "./middleware.js";
4
+ import { Procedure, ProcedureHandler } from "./procedure.js";
5
+ import { AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, ORPCErrorConstructorMap } from "@orpc/contract";
6
+ import { IntersectPick } from "@orpc/shared";
7
+ export declare class ProcedureImplementer<TInitialContext extends Context, TInjectedContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> {
8
+ "~orpc": BuilderDefinition<TInputSchema, TOutputSchema, TErrorMap>;
9
+ "constructor"(definition: BuilderDefinition<TInputSchema, TOutputSchema, TErrorMap>);
10
+ "use"<$OutContext extends IntersectPick<MergedContext<TInitialContext, TInjectedContext>, $OutContext>, $InContext extends Context = MergedContext<TInitialContext, TInjectedContext>, $ErrorMap extends ErrorMap = TErrorMap>(middleware: Middleware<$InContext | MergedContext<TInitialContext, TInjectedContext>, $OutContext, InferSchemaOutput<TInputSchema>, InferSchemaInput<TOutputSchema>, $ErrorMap>): ProcedureImplementer<MergedInitialContext<TInitialContext, TInjectedContext, $InContext>, MergedContext<TInjectedContext, $OutContext>, TInputSchema, TOutputSchema, TErrorMap>;
11
+ "handler"(handler: ProcedureHandler<MergedContext<TInitialContext, TInjectedContext>, InferSchemaOutput<TInputSchema>, InferSchemaInput<TOutputSchema>, ORPCErrorConstructorMap<TErrorMap>>): ImplementedProcedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, TErrorMap>;
12
+ }
13
+ export declare class ImplementedProcedure<TInitialContext extends Context, TInjectedContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends Procedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, TErrorMap> {
14
+ use<$OutContext extends IntersectPick<MergedContext<TInitialContext, TInjectedContext>, $OutContext>, $InContext extends Context = MergedContext<TInitialContext, TInjectedContext>, $ErrorMap extends ErrorMap = TErrorMap>(middleware: Middleware<$InContext | MergedContext<TInitialContext, TInjectedContext>, $OutContext, InferSchemaOutput<TInputSchema>, InferSchemaInput<TOutputSchema>, $ErrorMap>): ImplementedProcedure<MergedInitialContext<TInitialContext, TInjectedContext, $InContext>, MergedContext<TInjectedContext, $OutContext>, TInputSchema, TOutputSchema, TErrorMap>;
15
+ }
@@ -0,0 +1,37 @@
1
+ import { Procedure } from "./procedure.js";
2
+ // src/implementer-procedure.ts
3
+ var ProcedureImplementer = class ProcedureImplementer {
4
+ "~orpc";
5
+ "constructor"(definition) {
6
+ this["~orpc"] = definition;
7
+ }
8
+ "use"(middleware) {
9
+ return new ProcedureImplementer({
10
+ ...this["~orpc"],
11
+ orderedMiddlewares: [...this["~orpc"].orderedMiddlewares, {
12
+ middleware,
13
+ inputSchemasLengthAtUse: this["~orpc"].inputSchemas?.length,
14
+ outputSchemasLengthAtUse: this["~orpc"].outputSchemas?.length
15
+ }]
16
+ });
17
+ }
18
+ "handler"(handler) {
19
+ return new ImplementedProcedure({
20
+ ...this["~orpc"],
21
+ handler
22
+ });
23
+ }
24
+ };
25
+ var ImplementedProcedure = class ImplementedProcedure extends Procedure {
26
+ use(middleware) {
27
+ return new ImplementedProcedure({
28
+ ...this["~orpc"],
29
+ orderedMiddlewares: [...this["~orpc"].orderedMiddlewares, {
30
+ middleware,
31
+ inputSchemasLengthAtUse: this["~orpc"].inputSchemas?.length,
32
+ outputSchemasLengthAtUse: this["~orpc"].outputSchemas?.length
33
+ }]
34
+ });
35
+ }
36
+ };
37
+ export { ImplementedProcedure, ProcedureImplementer };
@@ -0,0 +1,34 @@
1
+ import { Context, MergedContext, MergedInitialContext } from "./context.js";
2
+ import { ProcedureImplementer } from "./implementer-procedure.js";
3
+ import { Lazy } from "./lazy.js";
4
+ import { AnyMiddleware, Middleware } from "./middleware.js";
5
+ import { DecoratedMiddleware } from "./middleware-decorated.js";
6
+ import { ProcedureConfig } from "./procedure.js";
7
+ import { ContractedRouter } from "./router.js";
8
+ import { AugmentedRouterWithMiddlewares } from "./router-utils.js";
9
+ import { ErrorMap, InferRouterContractErrorMap, ProcedureContract, RouterContract } from "@orpc/contract";
10
+ import { IntersectPick, Public } from "@orpc/shared";
11
+ export declare class SharedRouterImplementer<TContract extends RouterContract, TInitialContext extends Context> {
12
+ private readonly contract;
13
+ private readonly config;
14
+ private readonly middlewares;
15
+ private constructor();
16
+ static create<TContract extends RouterContract, TInitialContext extends Context>(contract: TContract, config: ProcedureConfig): SharedRouterImplementer<TContract, TInitialContext>;
17
+ static create<TContract extends RouterContract, TInitialContext extends Context, TInjectedContext extends Context>(contract: TContract, config: ProcedureConfig, middlewares: AnyMiddleware[]): SharedRouterImplementerWithMiddlewares<TContract, TInitialContext, TInjectedContext>;
18
+ use<$OutContext extends IntersectPick<TInitialContext, $OutContext>, $InContext extends Context = TInitialContext, $ErrorMap extends ErrorMap = InferRouterContractErrorMap<TContract>>(middleware: Middleware<$InContext | TInitialContext, $OutContext, unknown, unknown, $ErrorMap>): RouterImplementerWithMiddlewares<TContract, MergedInitialContext<TInitialContext, object, $InContext>, $OutContext>;
19
+ middleware<$OutContext extends IntersectPick<TInitialContext, $OutContext>, $Input, $InContext extends Context = TInitialContext, $Output = any>(middleware: Middleware<$InContext | TInitialContext, $OutContext, $Input, $Output, InferRouterContractErrorMap<TContract>>): DecoratedMiddleware<MergedInitialContext<TInitialContext, object, $InContext>, $OutContext, $Input, $Output, object>;
20
+ router<T extends ContractedRouter<TContract, any>>(router: T): T;
21
+ lazy<T extends ContractedRouter<TContract, any>>(loader: () => Promise<{
22
+ default: T;
23
+ }>): Lazy<T>;
24
+ }
25
+ export interface SharedRouterImplementerWithMiddlewares<TContract extends RouterContract, TInitialContext extends Context, TInjectedContext extends Context> {
26
+ use<$OutContext extends IntersectPick<MergedContext<TInitialContext, TInjectedContext>, $OutContext>, $InContext extends Context = MergedContext<TInitialContext, TInjectedContext>, $ErrorMap extends ErrorMap = InferRouterContractErrorMap<TContract>>(middleware: Middleware<$InContext | MergedContext<TInitialContext, TInjectedContext>, $OutContext, unknown, unknown, $ErrorMap>): RouterImplementerWithMiddlewares<TContract, MergedInitialContext<TInitialContext, TInjectedContext, $InContext>, MergedContext<TInjectedContext, $OutContext>>;
27
+ middleware<$OutContext extends IntersectPick<MergedContext<TInitialContext, TInjectedContext>, $OutContext>, $Input, $InContext extends Context = MergedContext<TInitialContext, TInjectedContext>, $Output = any>(middleware: Middleware<$InContext | MergedContext<TInitialContext, TInjectedContext>, $OutContext, $Input, $Output, InferRouterContractErrorMap<TContract>>): DecoratedMiddleware<MergedInitialContext<TInitialContext, TInjectedContext, $InContext>, MergedContext<TInjectedContext, $OutContext>, $Input, $Output, object>;
28
+ router<T extends ContractedRouter<TContract, MergedContext<TInitialContext, TInjectedContext>>>(router: T): AugmentedRouterWithMiddlewares<T, TInitialContext, TInjectedContext, object>;
29
+ lazy<T extends ContractedRouter<TContract, any>>(loader: () => Promise<{
30
+ default: T;
31
+ }>): Lazy<AugmentedRouterWithMiddlewares<T, TInitialContext, TInjectedContext, object>>;
32
+ }
33
+ export type RouterImplementer<TContract extends RouterContract, TInitialContext extends Context> = TContract extends ProcedureContract<infer $InputSchema, infer $OutputSchema, infer $ErrorMap> ? ProcedureImplementer<TInitialContext, object, $InputSchema, $OutputSchema, $ErrorMap> : Public<SharedRouterImplementer<TContract, TInitialContext>> & { [K in keyof TContract]: TContract[K] extends RouterContract ? RouterImplementer<TContract[K], TInitialContext> : never; };
34
+ export type RouterImplementerWithMiddlewares<TContract extends RouterContract, TInitialContext extends Context, TInjectedContext extends Context> = TContract extends ProcedureContract<infer $InputSchema, infer $OutputSchema, infer $ErrorMap> ? ProcedureImplementer<TInitialContext, TInjectedContext, $InputSchema, $OutputSchema, $ErrorMap> : SharedRouterImplementerWithMiddlewares<TContract, TInitialContext, TInjectedContext> & { [K in keyof TContract]: TContract[K] extends RouterContract ? RouterImplementerWithMiddlewares<TContract[K], TInitialContext, TInjectedContext> : never; };