@aiti-ai/ddns-mocks 0.0.0-stage → 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.
package/dist/rest.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ /** Generic REST zone-API mock — in-memory implementation driven by a
2
+ * RestSpec, so every spec'd provider gets a working mock automatically. */
3
+ import type { RestSpec } from "@aiti-ai/ddns";
4
+ export interface RestMockOptions {
5
+ spec: RestSpec;
6
+ /** Credential to accept (matches spec auth type). Default "test-token". */
7
+ cred?: string;
8
+ /** Pre-seed records: {type,name,value,ttl?}. */
9
+ records?: Array<{
10
+ type: string;
11
+ name: string;
12
+ value: string;
13
+ ttl?: number;
14
+ }>;
15
+ /** Zone name for zoneIdLookup providers. */
16
+ zone?: string;
17
+ port?: number;
18
+ }
19
+ export interface RestMockState {
20
+ /** Standard records {id,type,name,value,ttl}. */
21
+ records: Array<{
22
+ id: string;
23
+ type: string;
24
+ name: string;
25
+ value: string;
26
+ ttl?: number;
27
+ }>;
28
+ requests: Array<{
29
+ method: string;
30
+ url: string;
31
+ body?: unknown;
32
+ }>;
33
+ }
34
+ export interface RestMockHandle {
35
+ url: string;
36
+ state: RestMockState;
37
+ stop(): Promise<void>;
38
+ }
39
+ /** Generic mock: routes by the spec's endpoint templates. Works for the
40
+ * list/create/update/delete shapes in the REST_SPECS registry. */
41
+ export declare function startRestMock(opts: RestMockOptions): Promise<RestMockHandle>;
package/dist/rest.js ADDED
@@ -0,0 +1,279 @@
1
+ /** Generic REST zone-API mock — in-memory implementation driven by a
2
+ * RestSpec, so every spec'd provider gets a working mock automatically. */
3
+ import { createServer } from "node:http";
4
+ import { randomUUID } from "node:crypto";
5
+ /** Generic mock: routes by the spec's endpoint templates. Works for the
6
+ * list/create/update/delete shapes in the REST_SPECS registry. */
7
+ export async function startRestMock(opts) {
8
+ const spec = opts.spec;
9
+ const zone = opts.zone ?? "example.com";
10
+ const state = {
11
+ records: (opts.records ?? []).map((r) => ({ id: randomUUID(), type: r.type, name: r.name, value: r.value, ttl: r.ttl })),
12
+ requests: [],
13
+ };
14
+ /** Locate a record: by captured id, or by (name, type) when the template
15
+ * carries {name}/{type} (gandi-style composite ids). */
16
+ const findRec = (m) => {
17
+ const a = m[1];
18
+ const b = m[2];
19
+ const nameMatches = (name) => name === a || name.endsWith(`.${a}`) || name === `${a}.${zone}`;
20
+ return state.records.find((r) => r.id === a ||
21
+ // single {id} capture may address the record by name (zonomi)
22
+ (b === undefined && nameMatches(r.name)) ||
23
+ // {name}/{type} template order (gandi)
24
+ (b !== undefined && nameMatches(r.name) && r.type === b) ||
25
+ // {type}/{name} template order (godaddy)
26
+ (b !== undefined && r.type === a && (r.name === b || r.name.endsWith(`.${b}`) || r.name === `${b}.${zone}`)));
27
+ };
28
+ /** Expand a standard record into the superset shape every spec.fields
29
+ * reads (id/type/name + content/data/target/answer/value/rrset_*). */
30
+ const apiShape = (r) => {
31
+ const [host, ...rest] = r.name.split(".");
32
+ return {
33
+ id: r.id,
34
+ type: r.type,
35
+ name: r.name,
36
+ content: r.value,
37
+ data: r.value,
38
+ target: r.value,
39
+ answer: r.value,
40
+ value: r.value,
41
+ ttl: r.ttl ?? 300,
42
+ host: r.name.includes(".") ? host : "",
43
+ rrset_name: host,
44
+ rrset_type: r.type,
45
+ rrset_values: [r.value],
46
+ rrset_ttl: r.ttl ?? 300,
47
+ rrset_domain: rest.join("."),
48
+ domain: rest.join("."),
49
+ rrdata: r.value,
50
+ record: r.value, // cloudns-style string record
51
+ rdata: r.value,
52
+ records: [r.value], // flexibleengine recordsets style
53
+ answers: [{ answer: [r.value] }], // nsone rr-set style
54
+ // nested record object (pointhq style)
55
+ record_details: { id: r.id, record_type: r.type, name: r.name, data: r.value, ttl: r.ttl ?? 300 },
56
+ // sakuracloud deep nesting
57
+ CommonServiceItem: { Settings: { DNS: { ResourceRecordSets: [{ Name: r.name, Type: r.type, RData: r.value, TTL: r.ttl ?? 300 }] } } },
58
+ };
59
+ };
60
+ /** Extract a standard record from a create/update body (any of the common
61
+ * field vocabularies; gandi-style name/type come from path captures). */
62
+ const stdRec = (body, nameFromPath, typeFromPath) => {
63
+ let b = (Array.isArray(body) ? (body[0] ?? {}) : (body ?? {}));
64
+ // sakuracloud nested CommonServiceItem.Settings.DNS.ResourceRecordSets
65
+ const nested = b.CommonServiceItem
66
+ ?.Settings;
67
+ const saku = nested?.DNS?.ResourceRecordSets?.[0];
68
+ if (saku)
69
+ b = saku;
70
+ // b.record may be a string (cloudns) or a nested object (pointhq)
71
+ const recField = typeof b.record === "string" ? b.record : b.record?.data;
72
+ // onapp nests the record under dns_record
73
+ const dnsRec = b.dns_record;
74
+ if (dnsRec)
75
+ b = dnsRec;
76
+ const nsoneAnswer = b.answers?.[0]?.answer?.[0];
77
+ const val = String(b.data ?? b.content ?? b.target ?? b.answer ?? b.value ?? b.Value ?? b.RData ??
78
+ nsoneAnswer ?? recField ?? b.records?.[0] ?? b.rrset_values?.[0] ?? "");
79
+ let name = nameFromPath ?? String(b.name ?? b.host ?? b.Name ?? b.domain ?? b.record?.name ?? "");
80
+ // short names ("home", host-only) are joined with the mock's zone; "@"
81
+ // (root) stays as-is; full fqdns pass through
82
+ if (name && name !== "@" && !name.includes("."))
83
+ name = `${name}.${zone}`;
84
+ const recType = typeof b.record === "string" ? undefined : b.record?.record_type;
85
+ return {
86
+ type: typeFromPath ?? String(b.type ?? b.record_type ?? b.Type ?? recType ?? ""),
87
+ name,
88
+ value: val,
89
+ ttl: b.ttl !== undefined ? Number(b.ttl) : b.TTL !== undefined ? Number(b.TTL) : b.rrset_ttl !== undefined ? Number(b.rrset_ttl) : undefined,
90
+ };
91
+ };
92
+ const zoneId = randomUUID();
93
+ const authOk = (req) => {
94
+ const a = spec.auth;
95
+ const expected = opts.cred ?? "test-token";
96
+ if (a.type === "bearer")
97
+ return req.headers.authorization === `Bearer ${expected}`;
98
+ if (a.type === "header") {
99
+ const want = a.headerValue ? a.headerValue({ provider: spec.name, token: opts.cred, secret: opts.cred }) : `${a.headerPrefix ?? ""}${expected}`;
100
+ return req.headers[(a.header ?? "x-api-key").toLowerCase()] === want;
101
+ }
102
+ if (a.type === "basic")
103
+ return req.headers.authorization === `Basic ${Buffer.from(expected).toString("base64")}`;
104
+ return true; // query/body auth — skip in generic mock
105
+ };
106
+ const json = (res, status, body) => {
107
+ res.writeHead(status, { "content-type": "application/json" });
108
+ res.end(JSON.stringify(body));
109
+ };
110
+ const server = createServer((req, res) => {
111
+ const url = new URL(req.url ?? "/", "http://localhost");
112
+ let body = "";
113
+ req.on("data", (c) => (body += c));
114
+ req.on("end", () => {
115
+ const parsed = body ? JSON.parse(body) : undefined;
116
+ state.requests.push({ method: req.method ?? "GET", url: url.pathname + url.search, body: parsed });
117
+ if (!authOk(req))
118
+ return json(res, 401, { error: "unauthorized" });
119
+ const p = url.pathname;
120
+ const fullPath = url.pathname + url.search;
121
+ const method = req.method ?? "GET";
122
+ const stripQuery = (t) => t.split("?")[0];
123
+ // regex matcher for path templates with {id}/{name}/{type} placeholders
124
+ const pathRegex = (template) => {
125
+ const esc = template.replace(/[.+^${}()|[\]?&\\]/g, "\\$&");
126
+ const rx = esc.replace(/\\\{id\\\}/g, "([^/]+)").replace(/\\\{name\\\}/g, "([^/]+)").replace(/\\\{type\\\}/g, "([^/]+)");
127
+ return new RegExp(`^${rx}$`);
128
+ };
129
+ // match against pathname only (query dropped) — for templates carrying ?query
130
+ const querylessPathRegex = (template) => pathRegex(template.split("?")[0] ?? template);
131
+ // full-path match where {id} stops at ? or & (query-carrying templates);
132
+ // the tail is left open: providers may append auth query params
133
+ const queryTplRegex = (template) => {
134
+ const esc = template.replace(/[.+^${}()|[\]?&\\]/g, "\\$&");
135
+ const rx = esc
136
+ .replace(/\\\{id\\\}/g, "([^?&/]+)")
137
+ .replace(/\\\{name\\\}/g, "([^?&/]+)")
138
+ .replace(/\\\{type\\\}/g, "([^?&/]+)");
139
+ return new RegExp(`^${rx}(?:&.*)?$`);
140
+ };
141
+ // pre-lookups (dnsimple account etc.) — return a fake id array shape
142
+ for (const pl of spec.preLookups ?? []) {
143
+ if (p === stripQuery(pl.path())) {
144
+ return json(res, 200, [{ id: "acct1" }, { data: [{ id: "acct1" }] }]);
145
+ }
146
+ }
147
+ // zone-id lookup endpoint (query-stripped compare) — superset shape:
148
+ // zones[] / items[] / data[] / response.records[] all carry the id
149
+ if (spec.zoneIdLookup && p === stripQuery(spec.zoneIdLookup.path(zone))) {
150
+ const wrapper = {
151
+ zones: [{ id: zoneId, name: zone }],
152
+ items: [{ id: zoneId, name: zone }],
153
+ data: [{ id: zoneId, domain: zone }],
154
+ response: { records: [{ id: zoneId, domainname: zone }] },
155
+ };
156
+ // idPath "data.domain.id" style (arvancloud): serve the object form
157
+ if (spec.zoneIdLookup.idPath.includes("domain.")) {
158
+ return json(res, 200, { data: { domain: { id: zoneId, name: zone } } });
159
+ }
160
+ // top-level array form (onapp-style idPath "0.id")
161
+ const arr = [{ id: zoneId, name: zone, domain: zone }];
162
+ return json(res, 200, spec.zoneIdLookup.idPath === "0.id" ? arr : wrapper);
163
+ }
164
+ // list (query-stripped compare; empty recordsPath = bare array body)
165
+ const listTpl = spec.list.path(zone, zoneId, "acct1");
166
+ const listMethod = spec.list.method ?? "GET";
167
+ if (method === listMethod && (p === stripQuery(spec.list.path(zone, zoneId)) || p === stripQuery(listTpl))) {
168
+ const shaped = state.records.map(apiShape);
169
+ if (spec.list.recordsPath.length === 0)
170
+ return json(res, 200, shaped);
171
+ const wrapped = {};
172
+ setPath(wrapped, spec.list.recordsPath, shaped);
173
+ if (spec.list.pagesPath)
174
+ setPath(wrapped, spec.list.pagesPath, shaped);
175
+ return json(res, 200, wrapped);
176
+ }
177
+ // create: matches POST to the collection path, or the create template
178
+ // with {name}/{type} placeholders (gandi-style)
179
+ const createTemplate = spec.create.path(zone, zoneId, { name: "x", type: "A", value: "x" }, "acct1");
180
+ // nsone-style create paths embed the record TYPE as a real segment
181
+ // (`/zones/:z/{name}/:type`) — dummy-expanded template fixes the type,
182
+ // so also match with the type segment wildcarded. Only meaningful when the
183
+ // create template is a PURE path (no query string) — otherwise the replace
184
+ // would strip the query and produce a bare `/path/{type}` that falsely
185
+ // matches unrelated endpoints (e.g. zonomi's `/dns/delete.jsp`).
186
+ const createTypeFlex = createTemplate.includes("?")
187
+ ? ""
188
+ : createTemplate.replace(/\/[^/]+\/?$/, "/{type}");
189
+ const createMatch = p === stripQuery(spec.list.path(zone, zoneId))
190
+ || p === stripQuery(spec.create.path(zone, zoneId, { name: "x", type: "A", value: "x" }))
191
+ || p === stripQuery(createTemplate)
192
+ || pathRegex(createTemplate).test(p)
193
+ || (createTypeFlex ? pathRegex(createTypeFlex).test(p) : false);
194
+ if (method === (spec.create.method ?? "POST") && createMatch) {
195
+ const cap = pathRegex(createTemplate).exec(p);
196
+ const std = stdRec(parsed, cap?.[1], cap?.[2]);
197
+ // idempotent SET-style APIs (zonomi modify.jsp): update in place when
198
+ // a record with the same name/type already exists
199
+ const existing = std.name
200
+ ? state.records.find((r) => r.name === std.name && r.type === std.type)
201
+ : undefined;
202
+ const rec = existing ?? { id: spec.idFromName ? std.name || randomUUID() : randomUUID(), type: std.type, name: std.name, value: std.value, ttl: std.ttl };
203
+ if (existing) {
204
+ rec.value = std.value;
205
+ if (std.ttl !== undefined)
206
+ rec.ttl = std.ttl;
207
+ }
208
+ else {
209
+ state.records.push(rec);
210
+ }
211
+ const shaped = apiShape(rec);
212
+ const wrapped = { id: rec.id, record: shaped, domain_record: shaped };
213
+ if (spec.create.idPath)
214
+ setPath(wrapped, spec.create.idPath, rec.id);
215
+ return json(res, 200, wrapped);
216
+ }
217
+ // update / delete: match the spec's path templates against the request
218
+ const updateTpl = spec.update.path(zone, "{id}", zoneId, "acct1");
219
+ // pathname match first (query-carrying templates use queryless form);
220
+ // fullPath only when the template itself contains a query we must see
221
+ // (there {id} must not eat ? or &)
222
+ const qlMatch = querylessPathRegex(updateTpl).exec(p);
223
+ const qtMatch = updateTpl.includes("?") ? queryTplRegex(updateTpl).exec(fullPath) : null;
224
+ // id-less templates (zonomi modify.jsp): match by body name/type
225
+ const bodyMatch = (qlMatch && qlMatch[1] === undefined && !qtMatch)
226
+ ? { 1: stdRec(parsed).name }
227
+ : null;
228
+ const updateMatch = (qlMatch && qlMatch[1] !== undefined ? qlMatch : null)
229
+ ?? qtMatch
230
+ ?? bodyMatch;
231
+ if (method === (spec.update.method ?? "PUT") && updateMatch) {
232
+ const rec = findRec(updateMatch);
233
+ if (!rec)
234
+ return json(res, 404, { error: "not found" });
235
+ const std = stdRec(parsed);
236
+ if (std.type)
237
+ rec.type = std.type;
238
+ if (std.name)
239
+ rec.name = std.name;
240
+ if (std.value)
241
+ rec.value = std.value;
242
+ if (std.ttl !== undefined)
243
+ rec.ttl = std.ttl;
244
+ return json(res, 200, apiShape(rec));
245
+ }
246
+ const deleteTpl = spec.delete.path(zone, "{id}", zoneId, "acct1");
247
+ const dqMatch = querylessPathRegex(deleteTpl).exec(p);
248
+ const deleteMatch = (dqMatch && dqMatch[1] !== undefined ? dqMatch : null)
249
+ ?? (deleteTpl.includes("?") ? queryTplRegex(deleteTpl).exec(fullPath) : null)
250
+ ?? (method === (spec.delete.method ?? "DELETE") && dqMatch ? { 1: stdRec(parsed).name } : null);
251
+ if (method === (spec.delete.method ?? "DELETE") && deleteMatch) {
252
+ const idx = state.records.findIndex((r) => r.id === findRec(deleteMatch)?.id);
253
+ if (idx < 0)
254
+ return json(res, 404, { error: "not found" });
255
+ state.records.splice(idx, 1);
256
+ return json(res, 200, { id: deleteMatch[1] });
257
+ }
258
+ return json(res, 404, { error: `unknown endpoint ${method} ${p}` });
259
+ });
260
+ });
261
+ await new Promise((resolve) => server.listen(opts.port ?? 0, "127.0.0.1", resolve));
262
+ const addr = server.address();
263
+ const port = typeof addr === "object" && addr ? addr.port : 0;
264
+ return {
265
+ url: `http://127.0.0.1:${port}`,
266
+ state,
267
+ stop: () => new Promise((resolve) => server.close(() => resolve())),
268
+ };
269
+ }
270
+ /** Set a dotted path on an object (creates intermediate objects). */
271
+ function setPath(obj, path, value) {
272
+ let cur = obj;
273
+ for (let i = 0; i < path.length - 1; i++) {
274
+ const k = path[i];
275
+ cur[k] ??= {};
276
+ cur = cur[k];
277
+ }
278
+ cur[path[path.length - 1]] = value;
279
+ }
@@ -0,0 +1,32 @@
1
+ /** route53 mock — AWS Route53 XML API (SigV4 header accepted loosely, XML
2
+ * ListResourceRecordSets / ChangeResourceRecordSets responses like the real
3
+ * service so the provider's #parseRrsets works). */
4
+ export interface Route53MockOptions {
5
+ zoneId?: string;
6
+ records?: Array<{
7
+ name: string;
8
+ type: string;
9
+ value: string;
10
+ ttl?: number;
11
+ }>;
12
+ port?: number;
13
+ }
14
+ export interface Route53MockState {
15
+ records: Array<{
16
+ name: string;
17
+ type: string;
18
+ value: string;
19
+ ttl: number;
20
+ }>;
21
+ requests: Array<{
22
+ method: string;
23
+ url: string;
24
+ body?: string;
25
+ }>;
26
+ }
27
+ export interface Route53MockHandle {
28
+ url: string;
29
+ state: Route53MockState;
30
+ stop(): Promise<void>;
31
+ }
32
+ export declare function startRoute53Mock(opts?: Route53MockOptions): Promise<Route53MockHandle>;
@@ -0,0 +1,64 @@
1
+ /** route53 mock — AWS Route53 XML API (SigV4 header accepted loosely, XML
2
+ * ListResourceRecordSets / ChangeResourceRecordSets responses like the real
3
+ * service so the provider's #parseRrsets works). */
4
+ import { createServer } from "node:http";
5
+ export async function startRoute53Mock(opts = {}) {
6
+ const state = {
7
+ records: (opts.records ?? []).map((r) => ({ ttl: r.ttl ?? 300, ...r })),
8
+ requests: [],
9
+ };
10
+ const rrsetsXml = () => state.records
11
+ .map((r) => `<ResourceRecordSet><Name>${r.name}.</Name><Type>${r.type}</Type><TTL>${r.ttl}</TTL><ResourceRecords><ResourceRecord><Value>${r.value}</Value></ResourceRecord></ResourceRecords></ResourceRecordSet>`)
12
+ .join("");
13
+ const server = createServer((req, res) => {
14
+ let body = "";
15
+ req.on("data", (c) => (body += c));
16
+ req.on("end", () => {
17
+ state.requests.push({ method: req.method ?? "GET", url: req.url ?? "", body: body || undefined });
18
+ res.writeHead(200, { "content-type": "application/xml" });
19
+ if (req.method === "GET") {
20
+ // ListResourceRecordSets — provider parses <ResourceRecordSet> blocks
21
+ res.end(`<ListResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><ResourceRecordSets>${rrsetsXml()}</ResourceRecordSets></ListResourceRecordSetsResponse>`);
22
+ return;
23
+ }
24
+ if (req.method === "POST" && body.includes("<Action>CREATE</Action>")) {
25
+ const name = /<Name>([^<]+)<\/Name>/.exec(body)?.[1] ?? "";
26
+ const type = /<Type>([^<]+)<\/Type>/.exec(body)?.[1] ?? "";
27
+ const value = /<Value>([^<]+)<\/Value>/.exec(body)?.[1] ?? "";
28
+ const ttl = Number(/<TTL>([^<]+)<\/TTL>/.exec(body)?.[1] ?? 300);
29
+ if (name && type)
30
+ state.records.push({ name: name.replace(/\.$/, ""), type, value, ttl });
31
+ res.end(`<ChangeResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><ChangeInfo><Id>/change/C1</Id><Status>PENDING</Status></ChangeInfo></ChangeResourceRecordSetsResponse>`);
32
+ return;
33
+ }
34
+ if (req.method === "POST" && body.includes("<Action>UPSERT</Action>")) {
35
+ const name = /<Name>([^<]+)<\/Name>/.exec(body)?.[1] ?? "";
36
+ const type = /<Type>([^<]+)<\/Type>/.exec(body)?.[1] ?? "";
37
+ const value = /<Value>([^<]+)<\/Value>/.exec(body)?.[1] ?? "";
38
+ const rec = state.records.find((r) => r.name === name.replace(/\.$/, "") && r.type === type);
39
+ if (rec)
40
+ rec.value = value;
41
+ res.end(`<ChangeResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><ChangeInfo><Id>/change/C2</Id><Status>PENDING</Status></ChangeInfo></ChangeResourceRecordSetsResponse>`);
42
+ return;
43
+ }
44
+ if (req.method === "POST" && body.includes("<Action>DELETE</Action>")) {
45
+ const name = /<Name>([^<]+)<\/Name>/.exec(body)?.[1] ?? "";
46
+ const type = /<Type>([^<]+)<\/Type>/.exec(body)?.[1] ?? "";
47
+ const idx = state.records.findIndex((r) => r.name === name.replace(/\.$/, "") && r.type === type);
48
+ if (idx >= 0)
49
+ state.records.splice(idx, 1);
50
+ res.end(`<ChangeResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><ChangeInfo><Id>/change/C3</Id><Status>PENDING</Status></ChangeInfo></ChangeResourceRecordSetsResponse>`);
51
+ return;
52
+ }
53
+ res.end(`<ChangeResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><ChangeInfo><Id>/change/C9</Id><Status>PENDING</Status></ChangeInfo></ChangeResourceRecordSetsResponse>`);
54
+ });
55
+ });
56
+ await new Promise((resolve) => server.listen(opts.port ?? 0, "127.0.0.1", resolve));
57
+ const addr = server.address();
58
+ const port = typeof addr === "object" && addr ? addr.port : 0;
59
+ return {
60
+ url: `http://127.0.0.1:${port}`,
61
+ state,
62
+ stop: () => new Promise((resolve) => server.close(() => resolve())),
63
+ };
64
+ }
package/dist/tls.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /** TLS proxy face for mocks — lets REAL third-party clients (Go
2
+ * ddns-updater's statically-linked binary, Python lexicon via requests)
3
+ * reach a mock over HTTPS with zero root and zero LD_PRELOAD:
4
+ *
5
+ * Go/Python client ──HTTPS_PROXY=proxyUrl──► CONNECT api.cloudflare.com:443
6
+ * → 200 → TLS ClientHello → bridged to the TLS face → mock HTTP backend
7
+ *
8
+ * The client only needs two standard Go/requests knobs:
9
+ * HTTPS_PROXY=http://127.0.0.1:<proxyPort>
10
+ * SSL_CERT_FILE=<caPath> (Go) / REQUESTS_CA_BUNDLE=<caPath> (Python)
11
+ *
12
+ * The bundled CA (assets/mock-ca.pem) signs a server cert whose SAN covers
13
+ * every provider hostname (api.cloudflare.com, dnsapi.cn,
14
+ * alidns.aliyuncs.com, www.duckdns.org), so TLS verification passes for any
15
+ * provider while the traffic lands on the local mock.
16
+ *
17
+ * SMART ROUTING: CONNECT targets on the mock host list are bridged to the
18
+ * local TLS face (mock); ANY OTHER host is forwarded to the real network
19
+ * (plain CONNECT tunnel) — so github.com, ipify.org etc. keep working when
20
+ * the whole client runs behind HTTPS_PROXY.
21
+ */
22
+ /** Hosts the mock answers for — everything else tunnels to the real network. */
23
+ export declare const MOCK_HOSTS: ReadonlySet<string>;
24
+ export declare function caCertPath(): string;
25
+ export declare function serverCertPath(): string;
26
+ export interface TlsProxyHandle {
27
+ /** Direct TLS endpoint: https://127.0.0.1:<port> (curl --resolve works). */
28
+ tlsUrl: string;
29
+ /** HTTP CONNECT proxy endpoint for HTTPS_PROXY. */
30
+ proxyUrl: string;
31
+ /** Bundled CA cert — point SSL_CERT_FILE / REQUESTS_CA_BUNDLE here. */
32
+ caPath: string;
33
+ stop(): Promise<void>;
34
+ }
35
+ /** Wrap a running mock (its plain-HTTP `url`) with a TLS face + a CONNECT
36
+ * proxy face. `target` is the mock's base URL (http://127.0.0.1:<port>).
37
+ * Pass `certs` (dir containing ca.pem/ca.key/srv.pem/srv.key) to override the
38
+ * bundled assets — verify-all uses a freshly generated CA whose SAN covers
39
+ * every provider hostname WITHOUT clobbering the committed test assets. */
40
+ export declare function startTlsProxy(target: string, certs?: {
41
+ dir: string;
42
+ }): Promise<TlsProxyHandle>;
package/dist/tls.js ADDED
@@ -0,0 +1,140 @@
1
+ /** TLS proxy face for mocks — lets REAL third-party clients (Go
2
+ * ddns-updater's statically-linked binary, Python lexicon via requests)
3
+ * reach a mock over HTTPS with zero root and zero LD_PRELOAD:
4
+ *
5
+ * Go/Python client ──HTTPS_PROXY=proxyUrl──► CONNECT api.cloudflare.com:443
6
+ * → 200 → TLS ClientHello → bridged to the TLS face → mock HTTP backend
7
+ *
8
+ * The client only needs two standard Go/requests knobs:
9
+ * HTTPS_PROXY=http://127.0.0.1:<proxyPort>
10
+ * SSL_CERT_FILE=<caPath> (Go) / REQUESTS_CA_BUNDLE=<caPath> (Python)
11
+ *
12
+ * The bundled CA (assets/mock-ca.pem) signs a server cert whose SAN covers
13
+ * every provider hostname (api.cloudflare.com, dnsapi.cn,
14
+ * alidns.aliyuncs.com, www.duckdns.org), so TLS verification passes for any
15
+ * provider while the traffic lands on the local mock.
16
+ *
17
+ * SMART ROUTING: CONNECT targets on the mock host list are bridged to the
18
+ * local TLS face (mock); ANY OTHER host is forwarded to the real network
19
+ * (plain CONNECT tunnel) — so github.com, ipify.org etc. keep working when
20
+ * the whole client runs behind HTTPS_PROXY.
21
+ */
22
+ import { createServer as createHttpServer, request as httpRequest } from "node:http";
23
+ import { createServer as createTlsServer } from "node:https";
24
+ import { connect as tcpConnect } from "node:net";
25
+ import { readFileSync } from "node:fs";
26
+ import { fileURLToPath } from "node:url";
27
+ import { dirname, join } from "node:path";
28
+ const ASSETS = join(dirname(fileURLToPath(import.meta.url)), "assets");
29
+ /** Hosts the mock answers for — everything else tunnels to the real network. */
30
+ export const MOCK_HOSTS = new Set([
31
+ "api.cloudflare.com",
32
+ "dnsapi.cn",
33
+ "alidns.aliyuncs.com",
34
+ "www.duckdns.org",
35
+ "localhost",
36
+ "127.0.0.1",
37
+ ]);
38
+ export function caCertPath() {
39
+ return join(ASSETS, "mock-ca.pem");
40
+ }
41
+ export function serverCertPath() {
42
+ return join(ASSETS, "mock-server.pem");
43
+ }
44
+ /** Wrap a running mock (its plain-HTTP `url`) with a TLS face + a CONNECT
45
+ * proxy face. `target` is the mock's base URL (http://127.0.0.1:<port>).
46
+ * Pass `certs` (dir containing ca.pem/ca.key/srv.pem/srv.key) to override the
47
+ * bundled assets — verify-all uses a freshly generated CA whose SAN covers
48
+ * every provider hostname WITHOUT clobbering the committed test assets. */
49
+ export async function startTlsProxy(target, certs) {
50
+ const targetUrl = new URL(target);
51
+ const dir = certs?.dir ?? ASSETS;
52
+ const key = readFileSync(join(dir, certs ? "srv.key" : "mock-server.key"), "utf8");
53
+ const cert = readFileSync(join(dir, certs ? "srv.pem" : "mock-server.pem"), "utf8");
54
+ // --- TLS face: terminates TLS, forwards the plain HTTP request to the mock
55
+ const tlsServer = createTlsServer({ key, cert }, (req, res) => {
56
+ // Rebuild the request against the mock backend, preserving method,
57
+ // URL path/query, headers (authorization etc.) and body.
58
+ const headers = { ...req.headers, host: targetUrl.host };
59
+ const chunks = [];
60
+ req.on("data", (c) => chunks.push(c));
61
+ req.on("end", () => {
62
+ const upstream = httpRequest({
63
+ host: targetUrl.hostname,
64
+ port: Number(targetUrl.port),
65
+ method: req.method,
66
+ path: req.url,
67
+ headers,
68
+ }, (up) => {
69
+ res.writeHead(up.statusCode ?? 502, up.headers);
70
+ up.pipe(res);
71
+ });
72
+ upstream.on("error", () => {
73
+ res.writeHead(502, { "content-type": "text/plain" });
74
+ res.end("mock backend unreachable");
75
+ });
76
+ if (chunks.length)
77
+ upstream.write(Buffer.concat(chunks));
78
+ upstream.end();
79
+ });
80
+ });
81
+ // --- CONNECT proxy face: 200, then bridge the raw socket into the TLS face
82
+ let tlsPort = 0;
83
+ const proxyServer = createHttpServer();
84
+ const tunnels = new Set();
85
+ proxyServer.on("connect", (req, clientSocket) => {
86
+ const target = (req.url ?? "").split(" ")[0] ?? "";
87
+ const host = target.split(":")[0]?.toLowerCase() ?? "";
88
+ const port = Number(target.split(":")[1] ?? 443) || 443;
89
+ // Standard proxy reply first.
90
+ clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
91
+ tunnels.add(clientSocket);
92
+ const drop = () => { tunnels.delete(clientSocket); };
93
+ clientSocket.on("close", drop);
94
+ if (MOCK_HOSTS.has(host)) {
95
+ // Mock host → bridge to the local TLS face (terminates TLS → mock HTTP).
96
+ const tlsSocket = tcpConnect(tlsPort, "127.0.0.1", () => {
97
+ clientSocket.pipe(tlsSocket);
98
+ tlsSocket.pipe(clientSocket);
99
+ });
100
+ tunnels.add(tlsSocket);
101
+ const dropTls = () => { tunnels.delete(tlsSocket); };
102
+ tlsSocket.on("error", () => clientSocket.destroy());
103
+ clientSocket.on("error", () => tlsSocket.destroy());
104
+ clientSocket.on("close", () => { tlsSocket.destroy(); dropTls(); });
105
+ tlsSocket.on("close", () => { clientSocket.destroy(); dropTls(); });
106
+ return;
107
+ }
108
+ // Non-mock host → real CONNECT tunnel (client speaks TLS to the real server).
109
+ const realSocket = tcpConnect(port, host, () => {
110
+ clientSocket.pipe(realSocket);
111
+ realSocket.pipe(clientSocket);
112
+ });
113
+ tunnels.add(realSocket);
114
+ const dropReal = () => { tunnels.delete(realSocket); };
115
+ realSocket.on("error", () => clientSocket.destroy());
116
+ clientSocket.on("error", () => realSocket.destroy());
117
+ clientSocket.on("close", () => { realSocket.destroy(); dropReal(); });
118
+ realSocket.on("close", () => { clientSocket.destroy(); dropReal(); });
119
+ });
120
+ await Promise.all([
121
+ new Promise((r) => tlsServer.listen(0, "127.0.0.1", r)),
122
+ new Promise((r) => proxyServer.listen(0, "127.0.0.1", r)),
123
+ ]);
124
+ tlsPort = tlsServer.address().port;
125
+ const proxyPort = proxyServer.address().port;
126
+ return {
127
+ tlsUrl: `https://127.0.0.1:${tlsPort}`,
128
+ proxyUrl: `http://127.0.0.1:${proxyPort}`,
129
+ caPath: caCertPath(),
130
+ stop: async () => {
131
+ for (const s of tunnels)
132
+ s.destroy();
133
+ tunnels.clear();
134
+ await Promise.all([
135
+ new Promise((r) => tlsServer.close(() => r(undefined))),
136
+ new Promise((r) => proxyServer.close(() => r(undefined))),
137
+ ]);
138
+ },
139
+ };
140
+ }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@aiti-ai/ddns-mocks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "ddns provider 的 in-memory mock server(联调/测试用,独立于运行时包)",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc -p tsconfig.build.json && node -e \"fs.cpSync('src/assets','dist/assets',{recursive:true})\"",
19
+ "typecheck": "tsc --noEmit"
20
+ },
21
+ "dependencies": {},
22
+ "peerDependencies": {
23
+ "@aiti-ai/ddns": "^0.2.0"
24
+ },
25
+ "devDependencies": {
26
+ "@aiti-ai/ddns": "file:.."
27
+ }
28
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.