@jskit-ai/oidc-issuer-core 0.1.41 → 0.1.43

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/oidc-issuer-core",
3
- "version": "0.1.41",
3
+ "version": "0.1.43",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -119,10 +119,10 @@
119
119
  "oidc-provider": "9.12.2"
120
120
  },
121
121
  "devDependencies": {
122
- "@jskit-ai/auth-provider-local-core": "0.2.35"
122
+ "@jskit-ai/auth-provider-local-core": "0.2.37"
123
123
  },
124
124
  "peerDependencies": {
125
- "@jskit-ai/database-runtime": "0.1.275",
126
- "@jskit-ai/kernel": "0.2.26"
125
+ "@jskit-ai/database-runtime": "0.1.276",
126
+ "@jskit-ai/kernel": "0.2.27"
127
127
  }
128
128
  }
@@ -2,8 +2,8 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@jskit-ai/database-runtime": "0.1.275",
6
- "@jskit-ai/database-runtime-mysql": "0.1.273",
7
- "@jskit-ai/oidc-issuer-core": "0.1.41"
5
+ "@jskit-ai/database-runtime": "0.1.276",
6
+ "@jskit-ai/database-runtime-mysql": "0.1.274",
7
+ "@jskit-ai/oidc-issuer-core": "0.1.43"
8
8
  }
9
9
  }
@@ -1,8 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
- import { isProductionEnv } from "@jskit-ai/kernel/server/runtime/runtimeMode";
5
- import { sideEffectsAreLive } from "@jskit-ai/kernel/shared/support/sideEffects";
4
+ import { isDeployed } from "@jskit-ai/kernel/shared/support/appEnvironment";
6
5
 
7
6
  const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
8
7
  const MIN_SECRET_BYTES = 32;
@@ -27,11 +26,11 @@ function isLoopbackHostname(hostname) {
27
26
  return LOOPBACK_HOSTS.has(host) || host.endsWith(".localhost") || /^127(?:\.\d{1,3}){3}$/u.test(host);
28
27
  }
29
28
 
30
- function resolveIssuer(env, isProduction) {
29
+ function resolveIssuer(env, deployed) {
31
30
  const configured = text(env.APP_PUBLIC_URL);
32
31
  if (!configured) {
33
- if (isProduction) {
34
- throw new HubConfigError("Set APP_PUBLIC_URL to your hub's https address before starting it in production.");
32
+ if (deployed) {
33
+ throw new HubConfigError("Set APP_PUBLIC_URL to your hub's https address before starting it in staging or production.");
35
34
  }
36
35
  const port = Number.parseInt(text(env.PORT), 10) || 3001;
37
36
  return `http://localhost:${port}`;
@@ -65,10 +64,10 @@ function readOrCreateDevSecret(appRoot) {
65
64
  return generated;
66
65
  }
67
66
 
68
- function resolveSecret(env, { isProduction, appRoot }) {
67
+ function resolveSecret(env, { deployed, appRoot }) {
69
68
  const configured = text(env.OIDC_HUB_SECRET);
70
69
  if (!configured) {
71
- if (isProduction || !appRoot) {
70
+ if (deployed || !appRoot) {
72
71
  throw new HubConfigError("Set OIDC_HUB_SECRET to a random value of at least 32 bytes.");
73
72
  }
74
73
  return readOrCreateDevSecret(appRoot);
@@ -101,11 +100,11 @@ function parseDevOriginPatterns(value) {
101
100
  return Object.freeze(patterns);
102
101
  }
103
102
 
104
- function resolveMail(env, { isProduction }) {
103
+ function resolveMail(env, { deployed }) {
105
104
  const from = text(env.OIDC_HUB_EMAIL_FROM);
106
105
  const resendApiKey = text(env.RESEND_API_KEY);
107
106
  const smtpUrl = text(env.SMTP_URL);
108
- if (isProduction && (!from || (!resendApiKey && !smtpUrl))) {
107
+ if (deployed && (!from || (!resendApiKey && !smtpUrl))) {
109
108
  throw new HubConfigError(
110
109
  "Set OIDC_HUB_EMAIL_FROM and either RESEND_API_KEY or SMTP_URL so the hub can send confirmation and recovery emails."
111
110
  );
@@ -113,9 +112,7 @@ function resolveMail(env, { isProduction }) {
113
112
  return Object.freeze({
114
113
  from,
115
114
  resendApiKey,
116
- smtpUrl,
117
- // A test copy (SIDE_EFFECTS is not live) logs each email instead of sending it, even with a sender configured.
118
- live: sideEffectsAreLive(env)
115
+ smtpUrl
119
116
  });
120
117
  }
121
118
 
@@ -146,7 +143,7 @@ function resolveHubDevAuth(env) {
146
143
  * naming the variable to fix.
147
144
  */
148
145
  function resolveHubConfig(env = {}, { appRoot = "" } = {}) {
149
- const isProduction = isProductionEnv(env);
146
+ const deployed = isDeployed(env);
150
147
  const registrationToken = text(env.OIDC_HUB_REGISTRATION_TOKEN);
151
148
  if (!registrationToken) {
152
149
  throw new HubConfigError("Set OIDC_HUB_REGISTRATION_TOKEN: apps present it when they register with the hub.");
@@ -158,18 +155,18 @@ function resolveHubConfig(env = {}, { appRoot = "" } = {}) {
158
155
  if (!ownerEmail || !ownerEmail.includes("@")) {
159
156
  throw new HubConfigError("Set OIDC_HUB_OWNER_EMAIL to the email address of the hub's owner.");
160
157
  }
161
- const issuer = resolveIssuer(env, isProduction);
158
+ const issuer = resolveIssuer(env, deployed);
162
159
  return Object.freeze({
163
- isProduction,
160
+ isDeployed: deployed,
164
161
  issuer,
165
162
  secure: issuer.startsWith("https:"),
166
- secret: resolveSecret(env, { isProduction, appRoot }),
163
+ secret: resolveSecret(env, { deployed, appRoot }),
167
164
  secretFromEnv: Boolean(text(env.OIDC_HUB_SECRET)),
168
165
  registrationToken,
169
166
  ownerEmail,
170
167
  devOriginPatterns: parseDevOriginPatterns(env.OIDC_HUB_DEV_ORIGIN_PATTERNS),
171
168
  google: resolveGoogle(env),
172
- mail: resolveMail(env, { isProduction })
169
+ mail: resolveMail(env, { deployed })
173
170
  });
174
171
  }
175
172
 
@@ -652,7 +652,7 @@ function registerAdminRoutes(app, hub, support) {
652
652
  await settings.set("email-test", { ok: false, at: hub.now().toISOString() });
653
653
  throw hubError(HUB_ERRORS.testEmailFailed, { reason: error.message });
654
654
  }
655
- // A test copy logged the email instead of sending it, which proves nothing about the sender.
655
+ // A logged email (development and test, or staging without STAGING_EMAIL_TO) proves nothing about the sender.
656
656
  if (delivery?.simulated) {
657
657
  return { ok: true, simulated: true };
658
658
  }
@@ -680,7 +680,7 @@ function registerDevelopmentRoutes(app, hub, support) {
680
680
 
681
681
  app.post("/hub/api/dev/login-as", async (request, reply) => {
682
682
  const { enabled, secret } = hub.devAuth;
683
- if (config.isProduction || !enabled || !secret || !isLoopbackRequest(request)) {
683
+ if (config.isDeployed || !enabled || !secret || !isLoopbackRequest(request)) {
684
684
  throw new HubError(404, "not_found", "Not found.");
685
685
  }
686
686
  if (!constantEquals(request.headers[DEV_AUTH_SECRET_HEADER], secret)) {
@@ -71,7 +71,7 @@ async function createOidcIssuer({
71
71
  config,
72
72
  devAuth: resolveHubDevAuth(env),
73
73
  logger,
74
- mailer: mailer || createMailer({ mail: config.mail, logger, isProduction: config.isProduction, fetchImpl }),
74
+ mailer: mailer || createMailer({ mail: config.mail, env, logger, fetchImpl }),
75
75
  now,
76
76
  googleEndpoints,
77
77
  fetchImpl,
@@ -174,7 +174,7 @@ async function createOidcIssuer({
174
174
  // Hub pages are never framed. Development keeps the app's own pages
175
175
  // frameable so an editor's preview pane can show them.
176
176
  app.addHook("onRequest", async (request, reply) => {
177
- if (config.isProduction || isHubPath(request.url)) {
177
+ if (config.isDeployed || isHubPath(request.url)) {
178
178
  reply.raw.setHeader("x-frame-options", "DENY");
179
179
  reply.raw.setHeader("content-security-policy", "frame-ancestors 'none'");
180
180
  }
@@ -1,4 +1,4 @@
1
- import { logSimulatedSideEffect } from "@jskit-ai/kernel/server/runtime/sideEffects";
1
+ import { deliverMessage, markStagingEmail } from "@jskit-ai/kernel/server/runtime/appEnvironment";
2
2
  import { escapeHtml } from "./http.js";
3
3
 
4
4
  const RESEND_ENDPOINT = "https://api.resend.com/emails";
@@ -17,18 +17,17 @@ function composeMessage({ heading, body, actionLabel, actionUrl, footer }) {
17
17
  }
18
18
 
19
19
  /**
20
- * Sends the hub's emails with the owner's own sender: Resend when
21
- * RESEND_API_KEY is set, otherwise SMTP_URL. Outside production, with neither
22
- * set, messages are written to the log so the developer can follow the link.
23
- * A test copy (SIDE_EFFECTS is not `live`) sends nothing: it logs each message,
24
- * link included, and `send` answers `{ simulated: true }`.
20
+ * Sends the hub's emails with the owner's own sender, as APP_ENV says (`deliverMessage`): Resend when
21
+ * RESEND_API_KEY is set, otherwise SMTP_URL. Production sends each to its recipient; staging only to
22
+ * STAGING_EMAIL_TO, saying who it was for, or logs it when that is unset; development and test log each message,
23
+ * link included. `send` answers `{ simulated: true }` when the message was logged instead of sent.
25
24
  * @param {object} dependencies
26
25
  * @param {import("./types.js").HubConfig["mail"]} dependencies.mail
26
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
27
27
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
28
- * @param {boolean} dependencies.isProduction
29
28
  * @param {typeof fetch} dependencies.fetchImpl
30
29
  */
31
- function createMailer({ mail, logger, isProduction, fetchImpl }) {
30
+ function createMailer({ mail, env, logger, fetchImpl }) {
32
31
  let smtpTransport = null;
33
32
 
34
33
  async function sendWithSmtp(message) {
@@ -43,33 +42,43 @@ function createMailer({ mail, logger, isProduction, fetchImpl }) {
43
42
  const response = await fetchImpl(RESEND_ENDPOINT, {
44
43
  method: "POST",
45
44
  headers: { authorization: `Bearer ${mail.resendApiKey}`, "content-type": "application/json" },
46
- body: JSON.stringify({ from: mail.from, to: [message.to], subject: message.subject, text: message.text, html: message.html })
45
+ body: JSON.stringify({
46
+ from: mail.from,
47
+ to: [message.to],
48
+ subject: message.subject,
49
+ text: message.text,
50
+ html: message.html,
51
+ headers: message.headers
52
+ })
47
53
  });
48
54
  if (!response.ok) {
49
55
  throw new Error(`The email service refused the message (${response.status}).`);
50
56
  }
51
57
  }
52
58
 
53
- /** @returns {Promise<{ simulated: boolean }>} */
54
- async function send(message) {
55
- if (!mail.live) {
56
- logSimulatedSideEffect(logger, {
57
- kind: "email",
58
- summary: `the accounts hub email "${message.subject}" to ${message.to}`,
59
- details: { to: message.to, subject: message.subject, text: message.text }
60
- });
61
- return { simulated: true };
62
- }
59
+ // Staging and production start only with a sender (resolveHubConfig), and only they send.
60
+ async function sendNow(message) {
63
61
  if (mail.from && mail.resendApiKey) {
64
62
  await sendWithResend(message);
65
63
  } else if (mail.from && mail.smtpUrl) {
66
64
  await sendWithSmtp(message);
67
- } else if (isProduction) {
68
- throw new Error("The hub has no email sender.");
69
65
  } else {
70
- logger.info({ to: message.to, subject: message.subject }, `Accounts hub email (not sent: no sender configured)\n${message.text}`);
66
+ throw new Error("The hub has no email sender.");
71
67
  }
72
- return { simulated: false };
68
+ }
69
+
70
+ /** @returns {Promise<{ simulated: boolean }>} */
71
+ async function send(message) {
72
+ const delivery = await deliverMessage({
73
+ env,
74
+ logger,
75
+ channel: "email",
76
+ to: message.to,
77
+ summary: `the accounts hub email "${message.subject}" to ${message.to}`,
78
+ details: { subject: message.subject, text: message.text },
79
+ send: (to, { originalTo }) => sendNow(markStagingEmail({ ...message, to }, originalTo))
80
+ });
81
+ return { simulated: !delivery.sent };
73
82
  }
74
83
 
75
84
  return Object.freeze({
@@ -153,7 +153,7 @@ function createOidcProvider({ config, jwks, Adapter, accounts, clients, hasHubSe
153
153
  // against private addresses, except a development hub calling an app on
154
154
  // this same computer.
155
155
  fetch(url, options) {
156
- if (!config.isProduction && isLoopbackHostname(new URL(url).hostname)) {
156
+ if (!config.isDeployed && isLoopbackHostname(new URL(url).hostname)) {
157
157
  const { dispatcher: _dispatcher, ...direct } = options;
158
158
  return globalThis.fetch(url, direct);
159
159
  }
@@ -40,7 +40,7 @@ function localOrigin(value, localHostnames) {
40
40
  * The hub's side of the editor preview identity protocol: it signs the
41
41
  * preview browser in as an existing hub account through the hub's
42
42
  * development-only exchange, which needs the exchange secret and a loopback
43
- * caller and is absent in production. The preview host names the protocol id
43
+ * caller and is absent in staging and production. The preview host names the protocol id
44
44
  * and any hostnames, besides loopback, that it serves the hub on.
45
45
  * @param {Record<string, any>} request The command's request, which is validated here.
46
46
  * @param {object} options