@sponson/sim 0.0.0-stage → 0.5.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 (78) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +9 -2
  3. package/dist/auth.d.ts +60 -0
  4. package/dist/auth.js +195 -0
  5. package/dist/auth.js.map +1 -0
  6. package/dist/bin.d.ts +2 -0
  7. package/dist/bin.js +16 -0
  8. package/dist/bin.js.map +1 -0
  9. package/dist/chaos.d.ts +74 -0
  10. package/dist/chaos.js +80 -0
  11. package/dist/chaos.js.map +1 -0
  12. package/dist/cli.d.ts +29 -0
  13. package/dist/cli.js +99 -0
  14. package/dist/cli.js.map +1 -0
  15. package/dist/demo.d.ts +39 -0
  16. package/dist/demo.js +168 -0
  17. package/dist/demo.js.map +1 -0
  18. package/dist/graphql.d.ts +22 -0
  19. package/dist/graphql.js +36 -0
  20. package/dist/graphql.js.map +1 -0
  21. package/dist/index.d.ts +46 -0
  22. package/dist/index.js +54 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/provider.d.ts +138 -0
  25. package/dist/provider.js +68 -0
  26. package/dist/provider.js.map +1 -0
  27. package/dist/routes/algolia.d.ts +37 -0
  28. package/dist/routes/algolia.js +83 -0
  29. package/dist/routes/algolia.js.map +1 -0
  30. package/dist/routes/aws.d.ts +43 -0
  31. package/dist/routes/aws.js +211 -0
  32. package/dist/routes/aws.js.map +1 -0
  33. package/dist/routes/clerk.d.ts +33 -0
  34. package/dist/routes/clerk.js +85 -0
  35. package/dist/routes/clerk.js.map +1 -0
  36. package/dist/routes/cloudflare.d.ts +80 -0
  37. package/dist/routes/cloudflare.js +176 -0
  38. package/dist/routes/cloudflare.js.map +1 -0
  39. package/dist/routes/digitalocean.d.ts +58 -0
  40. package/dist/routes/digitalocean.js +158 -0
  41. package/dist/routes/digitalocean.js.map +1 -0
  42. package/dist/routes/fly.d.ts +22 -0
  43. package/dist/routes/fly.js +113 -0
  44. package/dist/routes/fly.js.map +1 -0
  45. package/dist/routes/launchdarkly.d.ts +98 -0
  46. package/dist/routes/launchdarkly.js +213 -0
  47. package/dist/routes/launchdarkly.js.map +1 -0
  48. package/dist/routes/neon.d.ts +73 -0
  49. package/dist/routes/neon.js +184 -0
  50. package/dist/routes/neon.js.map +1 -0
  51. package/dist/routes/netlify.d.ts +126 -0
  52. package/dist/routes/netlify.js +347 -0
  53. package/dist/routes/netlify.js.map +1 -0
  54. package/dist/routes/planetscale.d.ts +95 -0
  55. package/dist/routes/planetscale.js +234 -0
  56. package/dist/routes/planetscale.js.map +1 -0
  57. package/dist/routes/railway.d.ts +24 -0
  58. package/dist/routes/railway.js +112 -0
  59. package/dist/routes/railway.js.map +1 -0
  60. package/dist/routes/rest.d.ts +138 -0
  61. package/dist/routes/rest.js +462 -0
  62. package/dist/routes/rest.js.map +1 -0
  63. package/dist/routes/supabase.d.ts +103 -0
  64. package/dist/routes/supabase.js +234 -0
  65. package/dist/routes/supabase.js.map +1 -0
  66. package/dist/routes/vercel.d.ts +114 -0
  67. package/dist/routes/vercel.js +370 -0
  68. package/dist/routes/vercel.js.map +1 -0
  69. package/dist/routes/xata.d.ts +57 -0
  70. package/dist/routes/xata.js +115 -0
  71. package/dist/routes/xata.js.map +1 -0
  72. package/dist/server.d.ts +4 -0
  73. package/dist/server.js +189 -0
  74. package/dist/server.js.map +1 -0
  75. package/dist/state.d.ts +102 -0
  76. package/dist/state.js +121 -0
  77. package/dist/state.js.map +1 -0
  78. package/package.json +51 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,10 @@
1
- # Temporary Holding Version
1
+ # @sponson/sim
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A local fake cloud for testing [Sponson](https://github.com/MishaBear94/Sponson#readme): subsets of the Vercel, Neon and Clerk APIs with chaos injection, started in-process with `startSim()` or from the command line with `sponson-sim`.
4
+
5
+ - `npx --yes @sponson/sim --demo sponson-demo`: the fake cloud plus a ready demo repository, and the commands to run
6
+ next (the "Try it in 60 seconds" section of Sponson's README).
7
+ - `npx --yes @sponson/sim --port 4777`: just the fake cloud.
8
+ - `eval "$(npx --yes @sponson/sim env)"`: point `sponson` at a sim already running on that port.
9
+
10
+ Documentation: <https://sponson.mintlify.site>. Source and issues: [GitHub](https://github.com/MishaBear94/Sponson).
package/dist/auth.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { IncomingHttpHeaders } from "node:http";
2
+ import { Reply, type AuthRequest } from "./provider.js";
3
+ /** What a SigV4 signature must be made with: the access keys the "account" has, and the expected scope. */
4
+ export interface SigV4Config {
5
+ /** Access key id → secret access key. */
6
+ keys: Record<string, string>;
7
+ region: string;
8
+ /** The signing name the request's path belongs to (`s3`, `amplify`). */
9
+ service: string;
10
+ /** The clock, for the 15-minute skew AWS allows. */
11
+ now?: () => number;
12
+ }
13
+ /** The signature AWS would compute for this request with `secret` (exported for the sim's own tests). */
14
+ export declare function expectedSigV4(req: AuthRequest, headers: IncomingHttpHeaders, secret: string, scope: {
15
+ date: string;
16
+ region: string;
17
+ service: string;
18
+ signed: string[];
19
+ amzDate: string;
20
+ }): string;
21
+ /** Why a SigV4 request is refused, or null when its signature is valid for `config`. */
22
+ export declare function sigV4Problem(headers: IncomingHttpHeaders, req: AuthRequest, config: SigV4Config): string | null;
23
+ /** Digest users and the challenge the sim issues. */
24
+ export interface DigestConfig {
25
+ users: Record<string, string>;
26
+ algorithm?: "MD5" | "SHA-256";
27
+ realm?: string;
28
+ }
29
+ /** Server-side Digest state: the nonces handed out. */
30
+ export interface DigestState {
31
+ nonces: string[];
32
+ }
33
+ /** A 401 carrying a fresh Digest challenge. */
34
+ export declare function digestChallenge(config: DigestConfig, state: DigestState, n: number, stale?: boolean): Reply;
35
+ /** Why a Digest `Authorization` does not authenticate this request, or null when it does. */
36
+ export declare function digestProblem(headers: IncomingHttpHeaders, req: AuthRequest, config: DigestConfig, state: DigestState): string | null;
37
+ /** A token the sim's token endpoint issued. */
38
+ export interface IssuedToken {
39
+ token: string;
40
+ client: string;
41
+ /** How the client authenticated to the token endpoint. */
42
+ method: "client_secret_basic" | "client_secret_post";
43
+ audience?: string;
44
+ scope?: string;
45
+ expiresAt: number;
46
+ revoked?: true;
47
+ }
48
+ /** OAuth2 clients and the tokens issued to them. */
49
+ export interface OAuthState {
50
+ clients: Record<string, string>;
51
+ ttlSeconds: number;
52
+ issued: IssuedToken[];
53
+ }
54
+ /**
55
+ * RFC 6749 §4.4 at a token endpoint: `grant_type=client_credentials`, the client authenticated by HTTP Basic
56
+ * (`client_secret_basic`) or by `client_id`/`client_secret` in the form (`client_secret_post`), never both.
57
+ */
58
+ export declare function issueToken(state: OAuthState, headers: Record<string, string>, body: unknown, now?: number): Reply;
59
+ /** True when the bearer token was issued by the endpoint, is not revoked and has not expired. */
60
+ export declare function tokenValid(state: OAuthState, token: string, now?: number): boolean;
package/dist/auth.js ADDED
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Credential checks a simulated provider can configure, server side: an OAuth2 client-credentials token endpoint,
3
+ * HTTP Digest challenges (RFC 7616), and AWS Signature Version 4 verification. They are written here from the
4
+ * specifications, independently of the client code in @sponson/adapters (the sim depends on nothing in the repo),
5
+ * and both sides are checked against the same published vectors (AWS's SigV4 test suite, RFC 7616 §3.9.1); a
6
+ * client bug therefore fails against the sim instead of being mirrored by it.
7
+ */
8
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
9
+ import { Reply } from "./provider.js";
10
+ function sha256Hex(s) {
11
+ return createHash("sha256").update(s, "utf8").digest("hex");
12
+ }
13
+ function sameText(a, b) {
14
+ const x = Buffer.from(a);
15
+ const y = Buffer.from(b);
16
+ return x.length === y.length && timingSafeEqual(x, y);
17
+ }
18
+ function header(headers, name) {
19
+ const v = headers[name];
20
+ return Array.isArray(v) ? v.join(", ") : v;
21
+ }
22
+ /** RFC 3986 percent-encoding of every byte but the unreserved characters, upper-case hex. */
23
+ function awsEncode(s) {
24
+ let out = "";
25
+ for (const byte of Buffer.from(s, "utf8")) {
26
+ const c = String.fromCharCode(byte);
27
+ out += /[A-Za-z0-9\-._~]/.test(c) ? c : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
28
+ }
29
+ return out;
30
+ }
31
+ function decoded(s) {
32
+ try {
33
+ return decodeURIComponent(s);
34
+ }
35
+ catch {
36
+ return s;
37
+ }
38
+ }
39
+ /** Canonical URI from the request target: segments encoded once for S3, twice for every other service. */
40
+ function sigv4Uri(path, service) {
41
+ if (path === "" || path === "/")
42
+ return "/";
43
+ return path
44
+ .split("/")
45
+ .map((seg) => (service === "s3" ? awsEncode(decoded(seg)) : awsEncode(awsEncode(decoded(seg)))))
46
+ .join("/");
47
+ }
48
+ function sigv4Query(query) {
49
+ if (query === "")
50
+ return "";
51
+ return query
52
+ .split("&")
53
+ .filter((p) => p !== "")
54
+ .map((p) => {
55
+ const i = p.indexOf("=");
56
+ return [awsEncode(decoded(i < 0 ? p : p.slice(0, i))), awsEncode(decoded(i < 0 ? "" : p.slice(i + 1)))];
57
+ })
58
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0))
59
+ .map(([k, v]) => `${k}=${v}`)
60
+ .join("&");
61
+ }
62
+ /** The parts of a SigV4 `Authorization` header. */
63
+ function parseSigV4(value) {
64
+ const m = /^AWS4-HMAC-SHA256\s+Credential=([^/,\s]+)\/(\d{8})\/([^/,\s]+)\/([^/,\s]+)\/aws4_request,\s*SignedHeaders=([a-z0-9;-]+),\s*Signature=([0-9a-f]{64})$/.exec(value.trim());
65
+ return m ? { key: m[1], date: m[2], region: m[3], service: m[4], signed: m[5].split(";"), signature: m[6] } : null;
66
+ }
67
+ /** The signature AWS would compute for this request with `secret` (exported for the sim's own tests). */
68
+ export function expectedSigV4(req, headers, secret, scope) {
69
+ const q = req.target.indexOf("?");
70
+ const path = q < 0 ? req.target : req.target.slice(0, q);
71
+ const query = q < 0 ? "" : req.target.slice(q + 1);
72
+ const canonicalHeaders = scope.signed.map((h) => `${h}:${(header(headers, h) ?? "").trim().replace(/\s+/g, " ")}\n`).join("");
73
+ const payload = header(headers, "x-amz-content-sha256") ?? sha256Hex(req.raw);
74
+ const canonical = [req.method, sigv4Uri(path, scope.service), sigv4Query(query), canonicalHeaders, scope.signed.join(";"), payload].join("\n");
75
+ const credentialScope = `${scope.date}/${scope.region}/${scope.service}/aws4_request`;
76
+ const toSign = ["AWS4-HMAC-SHA256", scope.amzDate, credentialScope, sha256Hex(canonical)].join("\n");
77
+ let key = `AWS4${secret}`;
78
+ for (const part of [scope.date, scope.region, scope.service, "aws4_request"])
79
+ key = createHmac("sha256", key).update(part).digest();
80
+ return createHmac("sha256", key).update(toSign).digest("hex");
81
+ }
82
+ /** X-Amz-Date must be there, match the credential scope's day and be within the 15 minutes AWS allows. */
83
+ function amzDateProblem(amzDate, day, now) {
84
+ if (!/^\d{8}T\d{6}Z$/.test(amzDate) || amzDate.slice(0, 8) !== day)
85
+ return "X-Amz-Date is missing or does not match the credential scope";
86
+ const at = Date.UTC(+amzDate.slice(0, 4), +amzDate.slice(4, 6) - 1, +amzDate.slice(6, 8), +amzDate.slice(9, 11), +amzDate.slice(11, 13), +amzDate.slice(13, 15));
87
+ return Math.abs(at - now()) > 15 * 60_000 ? "RequestTimeTooSkewed" : null;
88
+ }
89
+ /** Why a SigV4 request is refused, or null when its signature is valid for `config`. */
90
+ export function sigV4Problem(headers, req, config) {
91
+ const auth = parseSigV4(header(headers, "authorization") ?? "");
92
+ if (!auth)
93
+ return "missing or malformed AWS4-HMAC-SHA256 Authorization header";
94
+ const secret = config.keys[auth.key];
95
+ if (secret === undefined)
96
+ return "InvalidAccessKeyId";
97
+ if (auth.region !== config.region || auth.service !== config.service)
98
+ return `credential scope ${auth.region}/${auth.service} is not ${config.region}/${config.service}`;
99
+ const amzDate = header(headers, "x-amz-date") ?? "";
100
+ const dateProblem = amzDateProblem(amzDate, auth.date, config.now ?? Date.now);
101
+ if (dateProblem)
102
+ return dateProblem;
103
+ if (!auth.signed.includes("host") || !auth.signed.includes("x-amz-date"))
104
+ return "SignedHeaders must include host and x-amz-date";
105
+ const claimed = header(headers, "x-amz-content-sha256");
106
+ if (claimed !== undefined && claimed !== sha256Hex(req.raw))
107
+ return "XAmzContentSHA256Mismatch";
108
+ const expected = expectedSigV4(req, headers, secret, { date: auth.date, region: auth.region, service: auth.service, signed: auth.signed, amzDate });
109
+ return sameText(expected, auth.signature) ? null : "SignatureDoesNotMatch";
110
+ }
111
+ const DEFAULT_REALM = "Sponson Sim API";
112
+ function digestParams(value) {
113
+ const out = {};
114
+ for (const m of value.replace(/^Digest\s+/i, "").matchAll(/([a-z0-9-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))/gi))
115
+ out[m[1].toLowerCase()] = m[2] !== undefined ? m[2].replace(/\\(.)/g, "$1") : m[3];
116
+ return out;
117
+ }
118
+ /** A 401 carrying a fresh Digest challenge. */
119
+ export function digestChallenge(config, state, n, stale = false) {
120
+ const nonce = `sim-nonce-${n}-${createHash("sha256").update(String(n)).digest("hex").slice(0, 16)}`;
121
+ state.nonces.push(nonce);
122
+ const challenge = `Digest realm="${config.realm ?? DEFAULT_REALM}", domain="", nonce="${nonce}", algorithm=${config.algorithm ?? "MD5"}, qop="auth", stale=${stale ? "TRUE" : "FALSE"}`;
123
+ return new Reply(401, { error: "unauthorized", detail: "Digest authentication required" }, { "www-authenticate": challenge });
124
+ }
125
+ /** What is wrong with a Digest answer's parameters, before its response is checked. */
126
+ function digestFormProblem(p, req, algorithm, state) {
127
+ if (!p.nonce || !state.nonces.includes(p.nonce))
128
+ return "unknown nonce";
129
+ if (p.qop !== "auth" || !/^[0-9a-f]{8}$/.test(p.nc ?? "") || !p.cnonce)
130
+ return "qop=auth with nc and cnonce is required";
131
+ if ((p.algorithm ?? "MD5").toUpperCase() !== algorithm)
132
+ return "wrong algorithm";
133
+ if (p.uri !== req.target)
134
+ return "uri does not match the request";
135
+ return null;
136
+ }
137
+ /** Why a Digest `Authorization` does not authenticate this request, or null when it does. */
138
+ export function digestProblem(headers, req, config, state) {
139
+ const value = header(headers, "authorization") ?? "";
140
+ if (!/^Digest\s/i.test(value))
141
+ return "no Digest credentials";
142
+ const p = digestParams(value);
143
+ const algorithm = config.algorithm ?? "MD5";
144
+ const password = p.username === undefined ? undefined : config.users[p.username];
145
+ if (password === undefined)
146
+ return "unknown user";
147
+ const problem = digestFormProblem(p, req, algorithm, state);
148
+ if (problem)
149
+ return problem;
150
+ const h = (s) => createHash(algorithm === "MD5" ? "md5" : "sha256").update(s, "utf8").digest("hex");
151
+ const ha1 = h(`${p.username}:${config.realm ?? DEFAULT_REALM}:${password}`);
152
+ const ha2 = h(`${req.method}:${p.uri}`);
153
+ const expected = h(`${ha1}:${p.nonce}:${p.nc}:${p.cnonce}:auth:${ha2}`);
154
+ return sameText(expected, p.response ?? "") ? null : "wrong response";
155
+ }
156
+ function form(v) {
157
+ if (typeof v !== "object" || v === null)
158
+ return {};
159
+ return Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === "string"));
160
+ }
161
+ function oauthError(status, error, description) {
162
+ return new Reply(status, { error, error_description: description });
163
+ }
164
+ /** The client a token request authenticates as (Basic or form, never both); the refusal otherwise. */
165
+ function clientOf(state, headers, f) {
166
+ const basic = /^Basic\s+(\S+)$/i.exec(headers.authorization ?? "");
167
+ if (basic && (f.client_id !== undefined || f.client_secret !== undefined))
168
+ return oauthError(400, "invalid_request", "client authenticated twice");
169
+ const [client, secret] = basic ? Buffer.from(basic[1], "base64").toString("utf8").split(/:(.*)/s) : [f.client_id, f.client_secret];
170
+ const expected = client === undefined ? undefined : state.clients[client];
171
+ if (!client || secret === undefined || expected === undefined || !sameText(expected, secret))
172
+ return oauthError(401, "invalid_client", "client authentication failed");
173
+ return { client, basic: basic !== null };
174
+ }
175
+ /**
176
+ * RFC 6749 §4.4 at a token endpoint: `grant_type=client_credentials`, the client authenticated by HTTP Basic
177
+ * (`client_secret_basic`) or by `client_id`/`client_secret` in the form (`client_secret_post`), never both.
178
+ */
179
+ export function issueToken(state, headers, body, now = Date.now()) {
180
+ const f = form(body);
181
+ if (f.grant_type !== "client_credentials")
182
+ return oauthError(400, "unsupported_grant_type", "only client_credentials is supported");
183
+ const who = clientOf(state, headers, f);
184
+ if (who instanceof Reply)
185
+ return who;
186
+ const { client, basic } = who;
187
+ const token = `oauth-access-token-${state.issued.length + 1}`;
188
+ state.issued.push({ token, client, method: basic ? "client_secret_basic" : "client_secret_post", ...(f.audience ? { audience: f.audience } : {}), ...(f.scope ? { scope: f.scope } : {}), expiresAt: now + state.ttlSeconds * 1000 });
189
+ return new Reply(200, { access_token: token, token_type: "Bearer", expires_in: state.ttlSeconds, ...(f.scope ? { scope: f.scope } : {}) });
190
+ }
191
+ /** True when the bearer token was issued by the endpoint, is not revoked and has not expired. */
192
+ export function tokenValid(state, token, now = Date.now()) {
193
+ return state.issued.some((t) => t.token === token && !t.revoked && t.expiresAt > now);
194
+ }
195
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEtE,OAAO,EAAE,KAAK,EAAoB,MAAM,eAAe,CAAC;AAExD,SAAS,SAAS,CAAC,CAAS;IAC1B,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,QAAQ,CAAC,CAAS,EAAE,CAAS;IACpC,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,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,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAC7I,CAAC;AAED,iGAAiG;AACjG,MAAM,UAAU,UAAU,CAAC,KAAiB,EAAE,KAAa,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE;IAC3E,OAAO,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC;AACxF,CAAC"}
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { runSimCli } from "./cli.js";
3
+ const { code, sim } = await runSimCli(process.argv.slice(2), {
4
+ stdout: (s) => process.stdout.write(s),
5
+ stderr: (s) => process.stderr.write(s),
6
+ env: process.env,
7
+ cwd: process.cwd(),
8
+ });
9
+ if (!sim)
10
+ process.exit(code);
11
+ const stop = () => {
12
+ void sim.close().finally(() => process.exit(0));
13
+ };
14
+ process.on("SIGINT", stop);
15
+ process.on("SIGTERM", stop);
16
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IAC3D,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACtC,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACtC,GAAG,EAAE,OAAO,CAAC,GAAG;IAChB,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE;CACnB,CAAC,CAAC;AACH,IAAI,CAAC,GAAG;IAAE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAE7B,MAAM,IAAI,GAAG,GAAG,EAAE;IAChB,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAClD,CAAC,CAAC;AACF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC3B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC"}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Chaos configuration: what the fake cloud does wrong on purpose, and which requests it does it to. Set it with
3
+ * `POST /_chaos` or a seed's `chaos:`; counters (`*_next`) decrement per matching request.
4
+ */
5
+ export interface ChaosConfig {
6
+ latency_ms: number;
7
+ /** Remaining requests (matching `fail_on`) that will fail with `status`. */
8
+ fail_next: number;
9
+ status: number;
10
+ /** Sent as `Retry-After` (seconds) with chaos 429s. */
11
+ retry_after?: number;
12
+ /** Remaining requests (matching `fail_on`) that are performed, then answered by destroying the socket. */
13
+ drop_response_next: number;
14
+ /** Remaining requests (matching `fail_on`) that are accepted and never answered. */
15
+ hang_next: number;
16
+ /**
17
+ * Remaining requests (matching `fail_on`) that are held, neither performed nor answered, until released
18
+ * (`POST /_release` or `state.release()`); then they are performed and answered as usual. Lets a test pin
19
+ * one client inside a request while another runs, instead of hoping timing makes them overlap.
20
+ */
21
+ hold_next: number;
22
+ /**
23
+ * Which requests the counters above apply to: `"METHOD /path-glob"` or a list of them.
24
+ * Absent means every write. Reads are only affected by a rule whose method is GET.
25
+ */
26
+ fail_on?: string | string[];
27
+ /** Deployment mode: ok | never | fail | stale | double | cancel | delay:<seconds>. */
28
+ deploy: string;
29
+ /** QUEUED → BUILDING → READY takes this long for deployments created through the API (and `ok` auto-deploys). */
30
+ deploy_ms: number;
31
+ /** After a Neon branch create, writes to that branch and further creates in the project answer 423 for this long. */
32
+ neon_op_ms: number;
33
+ /** A PlanetScale branch created through the API reports `ready: false` for this long (0: ready at its first read). */
34
+ planetscale_ready_ms: number;
35
+ /** A Supabase branch created through the API reports `COMING_UP` for this long, then `ACTIVE_HEALTHY`. */
36
+ supabase_ready_ms: number;
37
+ /** When > 0, Neon branches, Vercel envs and Clerk redirect URLs are listed in pages of this size. */
38
+ page_size: number;
39
+ /** Keys a Vercel bulk upsert reports under `failed` (and does not write). */
40
+ env_upsert_fail: string[];
41
+ }
42
+ /** The body of `POST /_chaos`: any chaos settings to merge, plus drift to apply immediately. */
43
+ export interface ChaosRequest extends Partial<ChaosConfig> {
44
+ /** Applied immediately to state, not stored. */
45
+ drift?: Record<string, string>;
46
+ }
47
+ /** What chaos does to one request. */
48
+ export type ChaosAction = {
49
+ kind: "hold";
50
+ } | {
51
+ kind: "hang";
52
+ } | {
53
+ kind: "drop";
54
+ } | {
55
+ kind: "fail";
56
+ status: number;
57
+ headers: Record<string, string>;
58
+ };
59
+ /** No chaos: every request is answered normally and immediately. */
60
+ export declare const DEFAULT_CHAOS: ChaosConfig;
61
+ /**
62
+ * Every key `POST /_chaos` accepts besides `drift`; anything else is rejected so a misspelt key cannot silently
63
+ * do nothing.
64
+ */
65
+ export declare const CHAOS_KEYS: Set<string>;
66
+ /** A fresh default config (no shared arrays). */
67
+ export declare function defaultChaos(): ChaosConfig;
68
+ /**
69
+ * Decide what chaos does to this request, consuming one count of `c` when it does something.
70
+ * Writes are eligible when `fail_on` is absent or matches; reads only when a GET rule matches.
71
+ */
72
+ export declare function chaosFor(c: ChaosConfig, method: string, path: string): ChaosAction | null;
73
+ /** `"DELETE /neon/*"`: method must match exactly (or be `*`), `*` in the path matches anything. */
74
+ export declare function matchesRule(rule: string, method: string, path: string): boolean;