@hogsend/engine 0.63.0 → 0.65.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/package.json +13 -12
- package/src/account-links/__fixtures__/fake-fetch.test.ts +57 -0
- package/src/account-links/__fixtures__/fake-fetch.ts +114 -0
- package/src/account-links/__fixtures__/steam.json +21 -0
- package/src/account-links/__fixtures__/twitch.json +22 -0
- package/src/account-links/index.ts +8 -0
- package/src/account-links/steam.test.ts +243 -0
- package/src/account-links/steam.ts +48 -0
- package/src/account-links/twitch.test.ts +157 -0
- package/src/account-links/twitch.ts +99 -0
- package/src/container.account-links.env.test.ts +65 -0
- package/src/container.account-links.halfenv.test.ts +48 -0
- package/src/container.account-links.test.ts +185 -0
- package/src/container.ts +120 -0
- package/src/env.ts +60 -0
- package/src/index.ts +104 -1
- package/src/journeys/journey-boundary.ts +8 -0
- package/src/lib/account-link-emit.ts +126 -0
- package/src/lib/account-link-events.ts +180 -0
- package/src/lib/account-link-hooks.test.ts +158 -0
- package/src/lib/account-link-hooks.ts +73 -0
- package/src/lib/account-link-ingest.ts +364 -0
- package/src/lib/account-link-nonce.test.ts +52 -0
- package/src/lib/account-link-nonce.ts +57 -0
- package/src/lib/account-link-origins.test.ts +72 -0
- package/src/lib/account-link-origins.ts +87 -0
- package/src/lib/account-link-pkce.test.ts +91 -0
- package/src/lib/account-link-pkce.ts +106 -0
- package/src/lib/account-link-provider-registry.test.ts +52 -0
- package/src/lib/account-link-provider-registry.ts +61 -0
- package/src/lib/account-link-throttle.test.ts +178 -0
- package/src/lib/account-link-throttle.ts +130 -0
- package/src/lib/account-link-url.ts +85 -0
- package/src/lib/account-links-emit.test.ts +525 -0
- package/src/lib/account-links-env.test.ts +40 -0
- package/src/lib/account-links-from-env.test.ts +187 -0
- package/src/lib/account-links-from-env.ts +126 -0
- package/src/lib/account-links.ts +1300 -0
- package/src/lib/app-secret.ts +34 -0
- package/src/lib/attachments.ts +81 -0
- package/src/lib/connector-actions.test.ts +13 -4
- package/src/lib/connector-state.account-link.test.ts +114 -0
- package/src/lib/connector-state.ts +48 -3
- package/src/lib/contacts.ts +320 -6
- package/src/lib/domain-status.return-path.test.ts +68 -0
- package/src/lib/domain-status.ts +19 -0
- package/src/lib/email-provider-boot.hogsend.test.ts +48 -0
- package/src/lib/email-provider-boot.test.ts +33 -0
- package/src/lib/email-providers-from-env.hogsend.test.ts +110 -0
- package/src/lib/email-providers-from-env.test.ts +52 -0
- package/src/lib/email-providers-from-env.ts +67 -0
- package/src/lib/email-service-types.ts +11 -0
- package/src/lib/email.ts +17 -0
- package/src/lib/mailer-bounce-idempotency.test.ts +469 -0
- package/src/lib/mailer-rejected.test.ts +229 -0
- package/src/lib/mailer-replied.test.ts +379 -0
- package/src/lib/mailer.ts +359 -24
- package/src/lib/outbound-account-payloads.test.ts +137 -0
- package/src/lib/outbound.ts +126 -0
- package/src/lib/provider-credentials.ts +19 -5
- package/src/lib/sending-domain-guidance.test.ts +99 -0
- package/src/lib/sending-domain-guidance.ts +84 -0
- package/src/lib/tracked-attachments.test.ts +376 -0
- package/src/lib/tracked-idempotency-header.test.ts +437 -0
- package/src/lib/tracked.ts +116 -4
- package/src/lib/tracking-event-names.ts +9 -0
- package/src/lib/webhook-catalog-sync.test.ts +24 -0
- package/src/lib/webhook-signing.ts +25 -1
- package/src/routes/accounts/callback.ts +597 -0
- package/src/routes/accounts/emit.ts +231 -0
- package/src/routes/accounts/import-links.ts +210 -0
- package/src/routes/accounts/index.ts +75 -0
- package/src/routes/accounts/lookup.ts +177 -0
- package/src/routes/accounts/me.ts +215 -0
- package/src/routes/accounts/mint.ts +279 -0
- package/src/routes/accounts/pages.ts +62 -0
- package/src/routes/accounts/resolve.ts +61 -0
- package/src/routes/accounts/serialize.ts +96 -0
- package/src/routes/accounts/shared.ts +107 -0
- package/src/routes/accounts/start.ts +229 -0
- package/src/routes/accounts/unlink.ts +98 -0
- package/src/routes/admin/agent.ts +2 -0
- package/src/routes/admin/api-keys.ts +7 -0
- package/src/routes/admin/contacts.ts +38 -2
- package/src/routes/admin/domain-conflict.test.ts +188 -0
- package/src/routes/admin/domain-return-path.test.ts +274 -0
- package/src/routes/admin/domain.ts +214 -1
- package/src/routes/connectors/index.ts +17 -0
- package/src/routes/contacts/index.ts +8 -0
- package/src/routes/index.ts +75 -0
- package/src/testing-barrel.test.ts +74 -0
- package/src/testing.ts +17 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeReturnPathLabel } from "@hogsend/core";
|
|
1
2
|
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
2
3
|
import type { AppEnv } from "../../app.js";
|
|
3
4
|
import { errorSchema } from "../../lib/schemas.js";
|
|
@@ -47,13 +48,25 @@ const TestModeStateSchema = z.object({
|
|
|
47
48
|
fromOverride: z.string().nullable(),
|
|
48
49
|
});
|
|
49
50
|
|
|
50
|
-
// Mirrors the pinned `
|
|
51
|
+
// Mirrors the pinned `SendingDomainGuidance` shape (lib/sending-domain-guidance.ts).
|
|
52
|
+
// `.readonly()` matches the interface's frozen `readonly string[]` labels.
|
|
53
|
+
const SendingDomainGuidanceSchema = z.object({
|
|
54
|
+
title: z.string(),
|
|
55
|
+
body: z.string(),
|
|
56
|
+
note: z.string(),
|
|
57
|
+
recommendedLabels: z.array(z.string()).readonly(),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// Mirrors the pinned `EngineDomainStatus` shape. `returnPathSupported` is
|
|
61
|
+
// optional there for wire skew only — this engine always sends it.
|
|
51
62
|
const EngineDomainStatusSchema = z.object({
|
|
52
63
|
domain: z.string().nullable(),
|
|
53
64
|
providerId: z.string(),
|
|
54
65
|
supported: z.boolean(),
|
|
66
|
+
returnPathSupported: z.boolean().optional(),
|
|
55
67
|
status: DomainStatusSchema.nullable(),
|
|
56
68
|
testMode: TestModeStateSchema,
|
|
69
|
+
guidance: SendingDomainGuidanceSchema,
|
|
57
70
|
});
|
|
58
71
|
|
|
59
72
|
/** Pinned domain validation regex (PROJECT_SPEC §e). */
|
|
@@ -76,6 +89,62 @@ const providerErrorResponse = {
|
|
|
76
89
|
description: "The provider rejected or failed the domains request",
|
|
77
90
|
} as const;
|
|
78
91
|
|
|
92
|
+
/**
|
|
93
|
+
* A provider refusal that is the OPERATOR'S to act on, forwarded verbatim
|
|
94
|
+
* instead of being buried under the blanket 502.
|
|
95
|
+
*
|
|
96
|
+
* The case this exists for: Hogsend Email answers `409 domain_not_owned` when a
|
|
97
|
+
* domain is claimed by another account, and its message carries the remedy.
|
|
98
|
+
* Flattened to "domains request to provider failed: …" with a 502, Studio
|
|
99
|
+
* rendered an opaque gateway error for a request that was well-formed,
|
|
100
|
+
* authenticated, and had a real answer waiting in it.
|
|
101
|
+
*
|
|
102
|
+
* 409 ONLY, and the narrowness is the point. A provider's 401 or 403 is OUR
|
|
103
|
+
* misconfiguration — a bad API key, a revoked token — and forwarding those
|
|
104
|
+
* would tell the customer their request was at fault for an outage they cannot
|
|
105
|
+
* fix. 502 stays the answer for everything genuinely opaque.
|
|
106
|
+
*
|
|
107
|
+
* The shape is matched STRUCTURALLY (a numeric `status`, a non-empty string
|
|
108
|
+
* `error` slug) rather than by class: the engine must not import a provider
|
|
109
|
+
* package to type-check a provider's error, and every plugin already models a
|
|
110
|
+
* refusal this way.
|
|
111
|
+
*/
|
|
112
|
+
const conflictResponse = {
|
|
113
|
+
content: {
|
|
114
|
+
"application/json": {
|
|
115
|
+
schema: z.object({
|
|
116
|
+
/** The provider's own slug, verbatim — e.g. `domain_not_owned`. */
|
|
117
|
+
error: z.string(),
|
|
118
|
+
/** The provider's sentence. It carries the remedy; render it. */
|
|
119
|
+
message: z.string(),
|
|
120
|
+
}),
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
description:
|
|
124
|
+
"The provider refused because the request conflicts with the world " +
|
|
125
|
+
"(e.g. the domain is already claimed by another account). The message " +
|
|
126
|
+
"carries the remedy.",
|
|
127
|
+
} as const;
|
|
128
|
+
|
|
129
|
+
/** The forwarded refusal, or `null` when this is an opaque provider failure. */
|
|
130
|
+
const providerConflictBody = (
|
|
131
|
+
err: unknown,
|
|
132
|
+
): { error: string; message: string } | null => {
|
|
133
|
+
if (typeof err !== "object" || err === null) return null;
|
|
134
|
+
const { status, error, message } = err as {
|
|
135
|
+
status?: unknown;
|
|
136
|
+
error?: unknown;
|
|
137
|
+
message?: unknown;
|
|
138
|
+
};
|
|
139
|
+
if (status !== 409) return null;
|
|
140
|
+
if (typeof error !== "string" || error.length === 0) return null;
|
|
141
|
+
return {
|
|
142
|
+
error,
|
|
143
|
+
message:
|
|
144
|
+
typeof message === "string" && message.length > 0 ? message : error,
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
|
|
79
148
|
const getDomainRoute = createRoute({
|
|
80
149
|
method: "get",
|
|
81
150
|
path: "/",
|
|
@@ -121,6 +190,7 @@ const addDomainRoute = createRoute({
|
|
|
121
190
|
},
|
|
122
191
|
description: "Domain registered (idempotent) — fresh status",
|
|
123
192
|
},
|
|
193
|
+
409: conflictResponse,
|
|
124
194
|
501: {
|
|
125
195
|
content: { "application/json": { schema: errorSchema } },
|
|
126
196
|
description: "The active provider has no domains capability",
|
|
@@ -145,6 +215,7 @@ const verifyDomainRoute = createRoute({
|
|
|
145
215
|
content: { "application/json": { schema: errorSchema } },
|
|
146
216
|
description: "No sending domain configured (EMAIL_DOMAIN / EMAIL_FROM)",
|
|
147
217
|
},
|
|
218
|
+
409: conflictResponse,
|
|
148
219
|
501: {
|
|
149
220
|
content: { "application/json": { schema: errorSchema } },
|
|
150
221
|
description: "The active provider has no domains capability",
|
|
@@ -153,6 +224,74 @@ const verifyDomainRoute = createRoute({
|
|
|
153
224
|
},
|
|
154
225
|
});
|
|
155
226
|
|
|
227
|
+
/**
|
|
228
|
+
* The branded return path, both directions (PRD 20). It carries BOUNCE
|
|
229
|
+
* traffic: on routes bounces via `<label>.<domain>` (two extra DNS records,
|
|
230
|
+
* MX + SPF) so mailbox UIs stop showing "via <provider>" and SPF aligns with
|
|
231
|
+
* the customer's own domain; off reverts to the provider default and the
|
|
232
|
+
* domain stays fully verified on its base records. It changes nothing about
|
|
233
|
+
* where a customer's incoming mail lands. Off is the default — nothing here
|
|
234
|
+
* may switch it on implicitly.
|
|
235
|
+
*/
|
|
236
|
+
const setReturnPathRoute = createRoute({
|
|
237
|
+
method: "post",
|
|
238
|
+
path: "/return-path",
|
|
239
|
+
tags: ["Admin — Domain"],
|
|
240
|
+
summary: "Switch the branded return path (custom MAIL FROM) on or off",
|
|
241
|
+
description:
|
|
242
|
+
"The return path carries bounce traffic. On adds two DNS records (MX + " +
|
|
243
|
+
'SPF) at `<label>.<domain>` so mailbox UIs stop showing "via ' +
|
|
244
|
+
'<provider>"; off reverts to the provider default and the domain stays ' +
|
|
245
|
+
"fully verified on its base records. Off is the default.",
|
|
246
|
+
request: {
|
|
247
|
+
body: {
|
|
248
|
+
content: {
|
|
249
|
+
"application/json": {
|
|
250
|
+
schema: z.object({
|
|
251
|
+
enabled: z.boolean(),
|
|
252
|
+
// Single DNS label (`notifications` → `notifications.<domain>`).
|
|
253
|
+
// Validated in the handler with the core rule so the rejection
|
|
254
|
+
// can NAME the offending label, not cite a pattern.
|
|
255
|
+
label: z.string().optional(),
|
|
256
|
+
}),
|
|
257
|
+
},
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
},
|
|
261
|
+
responses: {
|
|
262
|
+
200: {
|
|
263
|
+
content: {
|
|
264
|
+
"application/json": {
|
|
265
|
+
schema: z.object({
|
|
266
|
+
// What the provider now holds — read back after the write, never
|
|
267
|
+
// an echo of the request.
|
|
268
|
+
returnPath: z.object({
|
|
269
|
+
enabled: z.boolean(),
|
|
270
|
+
mailFromDomain: z.string().nullable(),
|
|
271
|
+
}),
|
|
272
|
+
status: EngineDomainStatusSchema,
|
|
273
|
+
}),
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
description:
|
|
277
|
+
"Return path switched — read-back state plus fresh domain status " +
|
|
278
|
+
"(the MX + SPF records report as pending when switched on)",
|
|
279
|
+
},
|
|
280
|
+
400: {
|
|
281
|
+
content: { "application/json": { schema: errorSchema } },
|
|
282
|
+
description: "Invalid return-path label, or no sending domain configured",
|
|
283
|
+
},
|
|
284
|
+
409: conflictResponse,
|
|
285
|
+
501: {
|
|
286
|
+
content: { "application/json": { schema: errorSchema } },
|
|
287
|
+
description:
|
|
288
|
+
"The active provider has no domains capability, or its domains " +
|
|
289
|
+
"capability cannot manage the return path",
|
|
290
|
+
},
|
|
291
|
+
502: providerErrorResponse,
|
|
292
|
+
},
|
|
293
|
+
});
|
|
294
|
+
|
|
156
295
|
export const domainRouter = new OpenAPIHono<AppEnv>()
|
|
157
296
|
.openapi(getDomainRoute, async (c) => {
|
|
158
297
|
const { domainStatus, emailProvider } = c.get("container");
|
|
@@ -183,6 +322,8 @@ export const domainRouter = new OpenAPIHono<AppEnv>()
|
|
|
183
322
|
const status = await domainStatus.getStatus({ refresh: true });
|
|
184
323
|
return c.json(status, 200);
|
|
185
324
|
} catch (err) {
|
|
325
|
+
const conflict = providerConflictBody(err);
|
|
326
|
+
if (conflict) return c.json(conflict, 409);
|
|
186
327
|
return c.json(
|
|
187
328
|
providerErrorBody(emailProvider.meta?.id ?? "email", err),
|
|
188
329
|
502,
|
|
@@ -214,6 +355,78 @@ export const domainRouter = new OpenAPIHono<AppEnv>()
|
|
|
214
355
|
const status = await domainStatus.getStatus({ refresh: true });
|
|
215
356
|
return c.json(status, 200);
|
|
216
357
|
} catch (err) {
|
|
358
|
+
const conflict = providerConflictBody(err);
|
|
359
|
+
if (conflict) return c.json(conflict, 409);
|
|
360
|
+
return c.json(
|
|
361
|
+
providerErrorBody(emailProvider.meta?.id ?? "email", err),
|
|
362
|
+
502,
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
})
|
|
366
|
+
.openapi(setReturnPathRoute, async (c) => {
|
|
367
|
+
const { domainStatus, emailProvider } = c.get("container");
|
|
368
|
+
const { enabled, label } = c.req.valid("json");
|
|
369
|
+
|
|
370
|
+
// TWO different unsupported cases, one deliberate answer each: no
|
|
371
|
+
// `domains` capability at all, and a `domains` capability without
|
|
372
|
+
// `setReturnPath`. Both are capability gaps, not engine errors — a throw
|
|
373
|
+
// on the second would read as a bug in a deploy that simply cannot do
|
|
374
|
+
// this. Same idiom as the other POSTs, no second one invented.
|
|
375
|
+
if (!emailProvider.domains) {
|
|
376
|
+
return c.json({ error: "provider_unsupported" }, 501);
|
|
377
|
+
}
|
|
378
|
+
const capability = emailProvider.domains;
|
|
379
|
+
if (!capability.setReturnPath) {
|
|
380
|
+
return c.json({ error: "provider_unsupported" }, 501);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// PRD 15's label rule, reused from core — rejected BEFORE any provider
|
|
384
|
+
// traffic, and the rejection names the offending label.
|
|
385
|
+
let normalizedLabel: string | undefined;
|
|
386
|
+
if (label !== undefined) {
|
|
387
|
+
const normalized = normalizeReturnPathLabel(label);
|
|
388
|
+
if (normalized === null) {
|
|
389
|
+
return c.json(
|
|
390
|
+
{
|
|
391
|
+
error:
|
|
392
|
+
`"${label}" is not a valid subdomain label. Use one DNS ` +
|
|
393
|
+
"label: lowercase letters, digits and hyphens, starting and " +
|
|
394
|
+
"ending alphanumeric, 63 characters or fewer, no dots.",
|
|
395
|
+
},
|
|
396
|
+
400,
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
normalizedLabel = normalized;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
try {
|
|
403
|
+
const current = await domainStatus.getStatus();
|
|
404
|
+
if (!current.domain) {
|
|
405
|
+
return c.json({ error: "no_domain_configured" }, 400);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const returnPath = await capability.setReturnPath({
|
|
409
|
+
domain: current.domain,
|
|
410
|
+
enabled,
|
|
411
|
+
...(normalizedLabel === undefined ? {} : { label: normalizedLabel }),
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
// Bust + refresh so this answer AND every subsequent GET reflect the
|
|
415
|
+
// switch rather than a pre-toggle cache entry.
|
|
416
|
+
const status = await domainStatus.getStatus({ refresh: true });
|
|
417
|
+
return c.json(
|
|
418
|
+
{
|
|
419
|
+
returnPath: {
|
|
420
|
+
enabled: returnPath.enabled,
|
|
421
|
+
mailFromDomain: returnPath.mailFromDomain,
|
|
422
|
+
},
|
|
423
|
+
status,
|
|
424
|
+
},
|
|
425
|
+
200,
|
|
426
|
+
);
|
|
427
|
+
} catch (err) {
|
|
428
|
+
const conflict = providerConflictBody(err);
|
|
429
|
+
if (conflict) return c.json(conflict, 409);
|
|
217
430
|
return c.json(
|
|
218
431
|
providerErrorBody(emailProvider.meta?.id ?? "email", err),
|
|
219
432
|
502,
|
|
@@ -114,6 +114,23 @@ export function registerConnectorRoutes(app: OpenAPIHono<AppEnv>) {
|
|
|
114
114
|
});
|
|
115
115
|
return c.json({ error: "Invalid state" }, 400);
|
|
116
116
|
}
|
|
117
|
+
// Bind the state to THIS SURFACE. One secret signs every state in the
|
|
118
|
+
// process, so an `account_link` state (PRD 07's hosted flow) is
|
|
119
|
+
// signature-valid here too. The `connectorId` check below rejects it
|
|
120
|
+
// incidentally — an account-link state carries none, and
|
|
121
|
+
// `undefined !== id` — but incidental is not a statement of the rule,
|
|
122
|
+
// and `plugin-discord`'s exhaustive `else` is a plugin's defence that a
|
|
123
|
+
// new plugin can drop. State the allowlist here, at the dispatcher.
|
|
124
|
+
if (
|
|
125
|
+
stateCheck.intent.purpose !== "install" &&
|
|
126
|
+
stateCheck.intent.purpose !== "member_link"
|
|
127
|
+
) {
|
|
128
|
+
logger.warn("connector oauth callback: unsupported state purpose", {
|
|
129
|
+
connectorId: id,
|
|
130
|
+
purpose: stateCheck.intent.purpose,
|
|
131
|
+
});
|
|
132
|
+
return c.json({ error: "Invalid state" }, 400);
|
|
133
|
+
}
|
|
117
134
|
// Bind the state to THIS connector: `BETTER_AUTH_SECRET` signs every
|
|
118
135
|
// connector's state, so a state minted for connector A is
|
|
119
136
|
// signature-valid here too. Reject a state whose `connectorId` does not
|
|
@@ -287,6 +287,14 @@ export const contactsRouter = new OpenAPIHono<AppEnv>()
|
|
|
287
287
|
return c.json({ error: "Contact not found" }, 404);
|
|
288
288
|
}
|
|
289
289
|
|
|
290
|
+
// NOT an `account.unlinked` emit point, though `result.linkUnlinks` is
|
|
291
|
+
// right there: `softDeleteContact` already fanned those out post-commit
|
|
292
|
+
// (PRD 08 T3), once for all three of its callers. Emitting again here
|
|
293
|
+
// would be silently swallowed by the `(endpointId, dedupeKey)` index, so
|
|
294
|
+
// the duplicate would cost a build cycle and hide which layer owns the
|
|
295
|
+
// fact rather than failing a test. The field stays on the result as the
|
|
296
|
+
// route's reporting channel.
|
|
297
|
+
//
|
|
290
298
|
// The widened `softDeleteContact` returns the deleted row's identity so the
|
|
291
299
|
// `contact.deleted` outbound webhook carries it without a second read-back.
|
|
292
300
|
if (result.id) {
|
package/src/routes/index.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { HogsendClient } from "../container.js";
|
|
|
4
4
|
import { requireApiKey, requireScope } from "../middleware/api-key.js";
|
|
5
5
|
import { requirePublishableOrIngest } from "../middleware/publishable-key.js";
|
|
6
6
|
import { createRateLimit } from "../middleware/rate-limit.js";
|
|
7
|
+
import { createAccountsRouter } from "./accounts/index.js";
|
|
7
8
|
import { adminRouter } from "./admin/index.js";
|
|
8
9
|
import { campaignsRouter } from "./campaigns/index.js";
|
|
9
10
|
import { registerConnectorRoutes } from "./connectors/index.js";
|
|
@@ -148,6 +149,80 @@ export function registerRoutes(
|
|
|
148
149
|
// per request), halving the effective per-key budget (decision #16 / risk 15).
|
|
149
150
|
v1.use("/emails/*", emailRateLimit);
|
|
150
151
|
|
|
152
|
+
// ---- Account links (PRD 07's hosted flow + PRD 09's data plane) ----
|
|
153
|
+
//
|
|
154
|
+
// THREE TIERS ON ONE PREFIX, and every path is enumerated EXPLICITLY. There
|
|
155
|
+
// is deliberately NO `/accounts/*` catch-all: a `/<prefix>/*` `use` in Hono
|
|
156
|
+
// also matches the bare `/<prefix>` path AND every literal sibling, so one
|
|
157
|
+
// would 401 the browser-reachable `/accounts/me` + `/accounts/link-url` and
|
|
158
|
+
// the unauthenticated `/accounts/manage` — the same trap documented for
|
|
159
|
+
// `/contacts/*` and `/lists/*` above, which fails CLOSED and silently
|
|
160
|
+
// (DECISIONS §15.1).
|
|
161
|
+
//
|
|
162
|
+
// Tier 1 — browser-reachable literals (publishable OR secret-ingest), each
|
|
163
|
+
// `userToken`-gated INSIDE its handler. Both `/me` entries are enumerated
|
|
164
|
+
// rather than written `/accounts/me/*`: the wildcard trap applies at every
|
|
165
|
+
// depth.
|
|
166
|
+
v1.use("/accounts/me", requirePublishableOrIngest);
|
|
167
|
+
v1.use("/accounts/me/revoke", requirePublishableOrIngest);
|
|
168
|
+
v1.use("/accounts/link-url", requirePublishableOrIngest);
|
|
169
|
+
// Tier 2 — secret-only literals, in the style of `/contacts/find` and
|
|
170
|
+
// `/flags/evaluate` above. `accounts` is an ORTHOGONAL scope
|
|
171
|
+
// (`middleware/api-key.ts:35-40`): an explicit grant or `full-admin`, and no
|
|
172
|
+
// SCOPE_HIERARCHY edit.
|
|
173
|
+
v1.use("/accounts", requireApiKey, requireScope("accounts"));
|
|
174
|
+
v1.use("/accounts/import", requireApiKey, requireScope("accounts"));
|
|
175
|
+
v1.use("/accounts/mint-link", requireApiKey, requireScope("accounts"));
|
|
176
|
+
// `/accounts/manage` (PRD 11) gets NO guard: it is the unauthenticated,
|
|
177
|
+
// token-bearing player page, the same posture as `/v1/email` at :45.
|
|
178
|
+
//
|
|
179
|
+
// Tier 3 — the two-segment param pattern gets ONE BRANCHING guard, never a
|
|
180
|
+
// stacked `requireApiKey, requireScope` pair. This is the most dangerous
|
|
181
|
+
// registration in the file: Hono runs EVERY matching `use`, so this pattern
|
|
182
|
+
// also fires on `/accounts/me/revoke`, `/accounts/:provider/start` and
|
|
183
|
+
// `/accounts/:provider/callback`. Stacking would 401 the entire hosted OAuth
|
|
184
|
+
// flow (PRD 07's routes carry no Authorization header) and 403 the primary
|
|
185
|
+
// player revoke (a pk_ key holds only `["ingest-public"]`). Branch, exactly
|
|
186
|
+
// like the method-branching `/contacts` guard above.
|
|
187
|
+
//
|
|
188
|
+
// `start`, `callback` and `me` are all in `RESERVED_ACCOUNT_LINK_IDS`, so no
|
|
189
|
+
// real provider or providerUserId can reach these branches by accident.
|
|
190
|
+
const accountsScopeGuard = requireScope("accounts");
|
|
191
|
+
v1.use("/accounts/:provider/:providerUserId", async (c, next) => {
|
|
192
|
+
const provider = c.req.param("provider");
|
|
193
|
+
const second = c.req.param("providerUserId");
|
|
194
|
+
// PRD 07's unauthenticated, self-verifying hosted flow. No guard at all.
|
|
195
|
+
//
|
|
196
|
+
// GATED ON METHOD, and that is load-bearing. A `use` matches EVERY method,
|
|
197
|
+
// but the routes this exemption exists for are GET-only. Without the method
|
|
198
|
+
// check, `DELETE /v1/accounts/steam/start` passes no guard here, then finds
|
|
199
|
+
// no matching GET literal, and falls through to the param route's DELETE —
|
|
200
|
+
// the secret-key operator unlink — with no API key at all.
|
|
201
|
+
const method = c.req.method;
|
|
202
|
+
if (method === "GET" && (second === "start" || second === "callback")) {
|
|
203
|
+
return next();
|
|
204
|
+
}
|
|
205
|
+
// The browser-reachable player revoke. Publishable tier; ownership comes
|
|
206
|
+
// from the userToken inside the handler, never from the request. Also
|
|
207
|
+
// method-gated: the literal is POST-only, so a DELETE on this same shape
|
|
208
|
+
// would otherwise reach the operator unlink holding only a `pk_` key.
|
|
209
|
+
if (method === "POST" && provider === "me" && second === "revoke") {
|
|
210
|
+
return requirePublishableOrIngest(c, next);
|
|
211
|
+
}
|
|
212
|
+
// Everything else on this shape is the operator reverse lookup / unlink.
|
|
213
|
+
// `requireApiKey` only runs its `next` on a successful auth, so use a flag
|
|
214
|
+
// to detect a short-circuit and surface its response (the `/contacts`
|
|
215
|
+
// DELETE idiom above).
|
|
216
|
+
let authed = false;
|
|
217
|
+
const res = await requireApiKey(c, async () => {
|
|
218
|
+
authed = true;
|
|
219
|
+
});
|
|
220
|
+
if (!authed) return res;
|
|
221
|
+
return accountsScopeGuard(c, next);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
v1.route("/accounts", createAccountsRouter());
|
|
225
|
+
|
|
151
226
|
v1.route("/contacts", contactsRouter);
|
|
152
227
|
v1.route("/events", eventsRouter);
|
|
153
228
|
v1.route("/feed", feedRouter);
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import test from "node:test";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `src/testing.ts` — the `@hogsend/engine/testing` entry point — is documented
|
|
8
|
+
* side-effect-free, and `@hogsend/testing` re-exports from it. Consumers import
|
|
9
|
+
* that package from an app that may have NO environment at all: the scaffold's
|
|
10
|
+
* `[2c] clean packed-consumer runtime import` gate builds a throwaway project
|
|
11
|
+
* whose only dependency is `@hogsend/testing`, writes a two-line file importing
|
|
12
|
+
* `createJourneyTest`, and runs it with plain `tsx` and an empty environment.
|
|
13
|
+
*
|
|
14
|
+
* `src/env.ts` calls `createEnv` at MODULE SCOPE, so ANY static
|
|
15
|
+
* `import { env }` anywhere in the barrel's import graph turns that into
|
|
16
|
+
* "Invalid environment variables" — including one added several modules deep
|
|
17
|
+
* (the barrel exports `softDeleteContact` from `lib/contacts.ts`, which reaches
|
|
18
|
+
* `lib/account-links.ts`, which reaches `lib/provider-credentials.ts`).
|
|
19
|
+
*
|
|
20
|
+
* This has to run in a CHILD PROCESS: `env.ts` caches its validation on first
|
|
21
|
+
* import, and this package's own suite runs with a full environment, so an
|
|
22
|
+
* in-process `await import()` here would pass no matter what. And it strips the
|
|
23
|
+
* environment rather than reading source, so it catches the edge WHEREVER in
|
|
24
|
+
* the graph it reappears — not just in the files we already know about.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** Every var `src/env.ts` declares with no `.default()` / `.optional()`. */
|
|
28
|
+
const REQUIRED_ENGINE_VARS = [
|
|
29
|
+
"DATABASE_URL",
|
|
30
|
+
"BETTER_AUTH_SECRET",
|
|
31
|
+
"HATCHET_CLIENT_TOKEN",
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
test("the testing barrel imports with no environment", () => {
|
|
35
|
+
// Keep PATH/NODE_OPTIONS etc. so the child can still resolve its TypeScript
|
|
36
|
+
// loader; drop exactly what `env.ts` demands.
|
|
37
|
+
const env = { ...process.env };
|
|
38
|
+
for (const name of REQUIRED_ENGINE_VARS) delete env[name];
|
|
39
|
+
|
|
40
|
+
const barrel = pathToFileURL(
|
|
41
|
+
new URL("./testing.ts", import.meta.url).pathname,
|
|
42
|
+
).href;
|
|
43
|
+
|
|
44
|
+
let stdout: string;
|
|
45
|
+
try {
|
|
46
|
+
stdout = execFileSync(
|
|
47
|
+
process.execPath,
|
|
48
|
+
[
|
|
49
|
+
...process.execArgv,
|
|
50
|
+
"--input-type=module",
|
|
51
|
+
"-e",
|
|
52
|
+
`await import(${JSON.stringify(barrel)});\nconsole.log("BARREL_OK");`,
|
|
53
|
+
],
|
|
54
|
+
{ env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },
|
|
55
|
+
);
|
|
56
|
+
} catch (err) {
|
|
57
|
+
const detail =
|
|
58
|
+
err && typeof err === "object" && "stderr" in err
|
|
59
|
+
? String((err as { stderr: unknown }).stderr)
|
|
60
|
+
: String(err);
|
|
61
|
+
assert.fail(
|
|
62
|
+
"`@hogsend/engine/testing` no longer imports without an environment. " +
|
|
63
|
+
"Something in its graph gained an import-time `env.ts` dependency — " +
|
|
64
|
+
"use `lib/app-secret.ts` (or another lazy accessor) instead of a " +
|
|
65
|
+
`static \`import { env }\`. Do NOT fix this by stubbing env vars in a test config; the scaffold gate runs plain \`tsx\` with none. Child stderr:\n${detail}`,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
assert.match(
|
|
70
|
+
stdout,
|
|
71
|
+
/BARREL_OK/,
|
|
72
|
+
"child process did not reach the import — the probe itself is broken",
|
|
73
|
+
);
|
|
74
|
+
});
|
package/src/testing.ts
CHANGED
|
@@ -10,6 +10,23 @@ export {
|
|
|
10
10
|
registerRecordLabel,
|
|
11
11
|
runWithJourneyBoundary,
|
|
12
12
|
} from "./journeys/journey-boundary.js";
|
|
13
|
+
// The account-link store's internal mechanics. These live HERE and not on the
|
|
14
|
+
// main barrel on purpose: `packages/engine/src/index.ts` is the committed
|
|
15
|
+
// semver boundary, and how the store happens to take advisory locks (or signal
|
|
16
|
+
// a stale pre-read) is not a promise to consumers. Tests need them to assert
|
|
17
|
+
// lock ORDER, which is the property the whole module exists to guarantee.
|
|
18
|
+
export {
|
|
19
|
+
AccountLinkLockSetChangedError,
|
|
20
|
+
lockPairs,
|
|
21
|
+
MAX_VERSION_RACE_RETRIES,
|
|
22
|
+
pairLockKey,
|
|
23
|
+
} from "./lib/account-links.js";
|
|
24
|
+
// PRD 04's guard + delete-leg tests. `ALL_IDENTITY_KINDS` is the resolver's
|
|
25
|
+
// internal full-trust grant (deliberately not public API — the test pinning
|
|
26
|
+
// that IdentityKind is never widened reads it here); `softDeleteContact` is
|
|
27
|
+
// route-internal on the main barrel, and the delete-leg tests assert on its
|
|
28
|
+
// returned `linkUnlinks` facts directly.
|
|
29
|
+
export { ALL_IDENTITY_KINDS, softDeleteContact } from "./lib/contacts.js";
|
|
13
30
|
export {
|
|
14
31
|
type EnrollmentPolicyFacts,
|
|
15
32
|
type EnrollmentPolicyResult,
|