@jskit-ai/oidc-issuer-core 0.1.10 → 0.1.12

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.
@@ -3,6 +3,7 @@ import { existsSync, readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { createKnexMigrationConfigFromApp } from "@jskit-ai/database-runtime/server/knexMigrationConfig";
5
5
  import createKnex from "knex";
6
+ import { systemClock } from "../src/server/clock.js";
6
7
  import { resolveHubConfig } from "../src/server/config.js";
7
8
  import { describeImport, importAccounts } from "../src/server/importAccounts.js";
8
9
  import { runPreviewIdentityCommand } from "../src/server/previewIdentity.js";
@@ -11,20 +12,23 @@ import { createSigningKeyStore } from "../src/server/signingKeys.js";
11
12
  const USAGE = `Usage:
12
13
  jskit-oidc-issuer keys rotate
13
14
  jskit-oidc-issuer import-accounts --in <file> [--apply]
14
- jskit-oidc-issuer preview-identity
15
+ jskit-oidc-issuer preview-identity [--protocol <id>] [--local-hostname <pattern>]...
15
16
 
16
- Run from the hub application's folder; it reads the same .env and database settings.`;
17
+ Run from the hub application's folder; it reads the same .env and database settings.
18
+ preview-identity answers one request on stdin: --protocol names the preview host's
19
+ protocol id, and each --local-hostname a regular expression for a hostname, besides
20
+ loopback, that the host serves the hub on.`;
17
21
 
18
22
  function loadDotEnv() {
19
23
  try {
20
- process.loadEnvFile?.(".env");
24
+ process.loadEnvFile(".env");
21
25
  } catch (error) {
22
26
  if (error?.code !== "ENOENT") throw error;
23
27
  }
24
28
  }
25
29
 
26
30
  async function withKnex(work) {
27
- const config = await createKnexMigrationConfigFromApp({ client: process.env.DB_CLIENT || "mysql2" });
31
+ const config = await createKnexMigrationConfigFromApp({ client: process.env.DB_CLIENT || "mysql2", environment: process.env });
28
32
  const knex = createKnex({ client: config.client, connection: config.connection });
29
33
  try {
30
34
  return await work(knex);
@@ -33,15 +37,28 @@ async function withKnex(work) {
33
37
  }
34
38
  }
35
39
 
40
+ /** The preview host's protocol id and hostnames, from `--protocol` and `--local-hostname` arguments. */
41
+ function previewIdentityHost(args) {
42
+ const host = { localHostnames: [] };
43
+ for (let index = 0; index < args.length; index += 2) {
44
+ const [flag, value] = [args[index], args[index + 1]];
45
+ if (!value) throw new Error(USAGE);
46
+ if (flag === "--protocol") host.protocol = value;
47
+ else if (flag === "--local-hostname") host.localHostnames.push(new RegExp(value, "u"));
48
+ else throw new Error(USAGE);
49
+ }
50
+ return host;
51
+ }
52
+
36
53
  async function main(argv) {
37
54
  const [command, ...rest] = argv;
38
55
  if (command === "preview-identity") {
39
- return runPreviewIdentityCommand();
56
+ return runPreviewIdentityCommand({ ...previewIdentityHost(rest), env: process.env });
40
57
  }
41
58
  loadDotEnv();
42
59
  if (command === "keys" && rest[0] === "rotate") {
43
60
  const config = resolveHubConfig(process.env, { appRoot: process.cwd() });
44
- const kid = await withKnex((knex) => createSigningKeyStore(knex, { secret: config.secret }).rotate());
61
+ const kid = await withKnex((knex) => createSigningKeyStore({ knex, secret: config.secret, now: systemClock }).rotate());
45
62
  console.log(`New signing key ${kid} is active. The previous key keeps verifying for two hours. A running hub picks it up within a minute.`);
46
63
  return 0;
47
64
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/oidc-issuer-core",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -17,7 +17,8 @@
17
17
  },
18
18
  "exports": {
19
19
  "./server": "./src/server/index.js",
20
- "./server/providers/OidcIssuerProvider": "./src/server/providers/OidcIssuerProvider.js"
20
+ "./server/providers/OidcIssuerProvider": "./src/server/providers/OidcIssuerProvider.js",
21
+ "./server/types": "./src/server/types.js"
21
22
  },
22
23
  "description": "OpenID Connect accounts hub: one sign-in for all of an owner's apps, with approval of every production app.",
23
24
  "jskit": {
@@ -81,6 +82,10 @@
81
82
  {
82
83
  "subpath": "./server/providers/OidcIssuerProvider",
83
84
  "summary": "Mounts the accounts hub (OpenID Connect issuer, hub API and Google sign-in) on the application's Fastify server."
85
+ },
86
+ {
87
+ "subpath": "./server/types",
88
+ "summary": "Type of the auth.oidc-issuer capability, for features that require it."
84
89
  }
85
90
  ],
86
91
  "capability": "auth.oidc-issuer"
@@ -106,16 +111,16 @@
106
111
  }
107
112
  },
108
113
  "dependencies": {
109
- "@jskit-ai/database-runtime": "0.1.252",
114
+ "@jskit-ai/database-runtime": "0.1.254",
110
115
  "jose": "6.2.12",
111
116
  "knex": "^3.1.0",
112
117
  "nodemailer": "10.2.1",
113
118
  "oidc-provider": "9.12.2"
114
119
  },
115
120
  "devDependencies": {
116
- "@jskit-ai/auth-provider-local-core": "0.2.5"
121
+ "@jskit-ai/auth-provider-local-core": "0.2.7"
117
122
  },
118
123
  "peerDependencies": {
119
- "@jskit-ai/kernel": "0.2.3"
124
+ "@jskit-ai/kernel": "0.2.5"
120
125
  }
121
126
  }
@@ -66,7 +66,8 @@ server's global UI paths so a surface-filtered server still serves them.
66
66
  Pages send `x-hub-request: 1` on every state-changing call.
67
67
 
68
68
  Commands (`jskit-oidc-issuer`): `keys rotate`, `import-accounts --in <file>
69
- [--apply]` (dry run by default), `preview-identity`.
69
+ [--apply]` (dry run by default), `preview-identity [--protocol <id>]
70
+ [--local-hostname <pattern>]...`.
70
71
 
71
72
  ## Example files
72
73
 
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@jskit-ai/database-runtime-mysql": "0.1.250",
6
- "@jskit-ai/oidc-issuer-core": "0.1.10"
5
+ "@jskit-ai/database-runtime-mysql": "0.1.252",
6
+ "@jskit-ai/oidc-issuer-core": "0.1.12"
7
7
  }
8
8
  }
@@ -1,7 +1,13 @@
1
1
  import { HUB_GLOBAL_PATHS } from "@jskit-ai/oidc-issuer-core/server";
2
2
 
3
- // Pass these to registerSurfaceRequestConstraint({ globalUiPaths }) next to
4
- // the runtime's own global paths, so every surface server serves the hub.
5
- export function hubGlobalUiPaths(runtimeGlobalUiPaths = []) {
3
+ /**
4
+ * The global UI paths with the hub's added to the runtime's own. Pass them to
5
+ * registerSurfaceRequestConstraint({ globalUiPaths }), so every surface server
6
+ * serves the hub.
7
+ * @param {string[]} runtimeGlobalUiPaths
8
+ */
9
+ function hubGlobalUiPaths(runtimeGlobalUiPaths) {
6
10
  return [...new Set([...runtimeGlobalUiPaths, ...HUB_GLOBAL_PATHS])];
7
11
  }
12
+
13
+ export { hubGlobalUiPaths };
@@ -14,11 +14,16 @@ function isCommonPassword(password) {
14
14
  return commonPasswords.has(String(password).toLowerCase());
15
15
  }
16
16
 
17
+ /**
18
+ * Why a password is refused, as its own code and English, or null when it is acceptable.
19
+ * @param {unknown} password
20
+ * @returns {{ code: string, message: string } | null}
21
+ */
17
22
  function passwordProblem(password) {
18
23
  const value = String(password ?? "");
19
- if (value.length < PASSWORD_MIN_LENGTH) return "Use at least 8 characters.";
20
- if (value.length > PASSWORD_MAX_LENGTH) return "Use at most 128 characters.";
21
- if (isCommonPassword(value)) return "That password is too common. Choose one that is harder to guess.";
24
+ if (value.length < PASSWORD_MIN_LENGTH) return { code: "password_too_short", message: "Use at least 8 characters." };
25
+ if (value.length > PASSWORD_MAX_LENGTH) return { code: "password_too_long", message: "Use at most 128 characters." };
26
+ if (isCommonPassword(value)) return { code: "password_too_common", message: "That password is too common. Choose one that is harder to guess." };
22
27
  return null;
23
28
  }
24
29
 
@@ -77,7 +82,13 @@ class AccountError extends Error {
77
82
  }
78
83
  }
79
84
 
80
- function createAccountStore(knex, { now = () => new Date() } = {}) {
85
+ /**
86
+ * The hub's accounts: their emails, passwords, Google links and lockouts.
87
+ * @param {object} dependencies
88
+ * @param {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} dependencies.knex
89
+ * @param {import("./types.js").HubClock} dependencies.now
90
+ */
91
+ function createAccountStore({ knex, now }) {
81
92
  const table = () => knex(ACCOUNTS_TABLE);
82
93
 
83
94
  async function rowByEmail(email) {
@@ -89,147 +100,165 @@ function createAccountStore(knex, { now = () => new Date() } = {}) {
89
100
  return toAccount(await table().where({ id }).first());
90
101
  }
91
102
 
92
- return Object.freeze({
93
- async findById(id) {
94
- return toAccount(await table().where({ id: String(id ?? "") }).first());
95
- },
96
-
97
- async findByEmail(email) {
98
- return toAccount(await rowByEmail(email));
99
- },
100
-
101
- async findByGoogleSub(googleSub) {
102
- return toAccount(await table().where({ google_sub: String(googleSub ?? "") }).first());
103
- },
104
-
105
- async list() {
106
- return (await table().orderBy("created_at", "desc")).map(toAccount);
107
- },
108
-
109
- async create({ email, password = null, displayName = "", emailVerified = false, googleSub = null }) {
110
- const normalizedEmail = normalizeEmail(email);
111
- if (!isEmail(normalizedEmail)) {
112
- throw new AccountError("email_invalid", "Enter a valid email address.");
113
- }
114
- if (password !== null) {
115
- const problem = passwordProblem(password);
116
- if (problem) throw new AccountError("password_rejected", problem);
117
- }
118
- if (await rowByEmail(normalizedEmail)) {
119
- throw new AccountError("email_taken", "This email already has an account. Sign in, or reset its password.", 409);
120
- }
121
- const id = createAccountId();
122
- const timestamp = now();
123
- await table().insert({
124
- id,
125
- email: normalizedEmail,
126
- email_verified: Boolean(emailVerified),
127
- display_name: displayNameFor(displayName, normalizedEmail),
128
- ...(password === null ? {} : passwordColumns(await hashPassword(password))),
129
- google_sub: googleSub,
130
- disabled: false,
131
- failed_logins: 0,
132
- created_at: timestamp,
133
- updated_at: timestamp
134
- });
135
- return toAccount(await table().where({ id }).first());
136
- },
137
-
138
- /**
139
- * Checks an email and password. Unknown emails, wrong passwords, disabled
140
- * and locked accounts all fail the same way, so the caller shows one
141
- * generic sentence. A locked account stays locked until recovery, even
142
- * with the right password.
143
- */
144
- async authenticate(email, password) {
145
- const row = await rowByEmail(email);
146
- if (!row || !row.password_hash) {
147
- await verifyPassword(password, { algorithm: "scrypt", version: "v1", salt: "AAAA", hash: "A".repeat(86) });
148
- return null;
149
- }
150
- if (Number(row.failed_logins) >= LOCK_AFTER_FAILURES || row.disabled) {
151
- return null;
152
- }
153
- if (!(await verifyPassword(password, passwordRecord(row)))) {
154
- await table().where({ id: row.id }).increment("failed_logins", 1);
155
- return null;
156
- }
157
- if (Number(row.failed_logins) > 0) {
158
- await table().where({ id: row.id }).update({ failed_logins: 0 });
159
- }
160
- return toAccount(row);
161
- },
162
-
163
- async checkPassword(id, password) {
164
- const row = await table().where({ id }).first();
165
- return Boolean(row?.password_hash) && verifyPassword(password, passwordRecord(row));
166
- },
167
-
168
- async setPassword(id, password) {
103
+ async function findById(id) {
104
+ return toAccount(await table().where({ id: String(id ?? "") }).first());
105
+ }
106
+
107
+ async function findByEmail(email) {
108
+ return toAccount(await rowByEmail(email));
109
+ }
110
+
111
+ async function findByGoogleSub(googleSub) {
112
+ return toAccount(await table().where({ google_sub: String(googleSub ?? "") }).first());
113
+ }
114
+
115
+ async function list() {
116
+ return (await table().orderBy("created_at", "desc")).map(toAccount);
117
+ }
118
+
119
+ async function create({ email, password = null, displayName = "", emailVerified = false, googleSub = null }) {
120
+ const normalizedEmail = normalizeEmail(email);
121
+ if (!isEmail(normalizedEmail)) {
122
+ throw new AccountError("email_invalid", "Enter a valid email address.");
123
+ }
124
+ if (password !== null) {
169
125
  const problem = passwordProblem(password);
170
- if (problem) throw new AccountError("password_rejected", problem);
171
- return update(id, { ...passwordColumns(await hashPassword(password)), failed_logins: 0 });
172
- },
173
-
174
- async clearPassword(id) {
175
- return update(id, {
176
- password_algorithm: null,
177
- password_version: null,
178
- password_salt: null,
179
- password_hash: null
180
- });
181
- },
182
-
183
- async updateProfile(id, { displayName }) {
184
- const name = String(displayName ?? "").trim();
185
- if (!name) throw new AccountError("display_name_required", "Enter the name your apps should show.");
186
- return update(id, { display_name: name.slice(0, 160) });
187
- },
188
-
189
- markEmailVerified(id) {
190
- return update(id, { email_verified: true });
191
- },
192
-
193
- linkGoogle(id, googleSub) {
194
- return update(id, { google_sub: String(googleSub) });
195
- },
196
-
197
- async unlinkGoogle(id) {
198
- const row = await table().where({ id }).first();
199
- if (!row?.password_hash) {
200
- throw new AccountError("password_required", "Set a password first, so you can still sign in without Google.");
201
- }
202
- return update(id, { google_sub: null });
203
- },
204
-
205
- setDisabled(id, disabled) {
206
- return update(id, { disabled: Boolean(disabled) });
207
- },
208
-
209
- /** Imports one exported JSKIT local account, keeping its id and scrypt fields byte for byte. */
210
- async importLocal(row) {
211
- const timestamp = now();
212
- await table().insert({
213
- id: row.id,
214
- email: normalizeEmail(row.email),
215
- email_verified: false,
216
- display_name: displayNameFor(row.display_name, normalizeEmail(row.email)),
217
- password_algorithm: row.password_algorithm,
218
- password_version: row.password_version,
219
- password_salt: row.password_salt,
220
- password_hash: row.password_hash,
221
- google_sub: null,
222
- disabled: Boolean(row.disabled),
223
- failed_logins: 0,
224
- created_at: timestamp,
225
- updated_at: timestamp
226
- });
227
- },
228
-
229
- async rawById(id) {
230
- return table().where({ id }).first();
231
- },
126
+ if (problem) throw new AccountError(problem.code, problem.message);
127
+ }
128
+ if (await rowByEmail(normalizedEmail)) {
129
+ throw new AccountError("email_taken", "This email already has an account. Sign in, or reset its password.", 409);
130
+ }
131
+ const id = createAccountId();
132
+ const timestamp = now();
133
+ await table().insert({
134
+ id,
135
+ email: normalizedEmail,
136
+ email_verified: Boolean(emailVerified),
137
+ display_name: displayNameFor(displayName, normalizedEmail),
138
+ ...(password === null ? {} : passwordColumns(await hashPassword(password))),
139
+ google_sub: googleSub,
140
+ disabled: false,
141
+ failed_logins: 0,
142
+ created_at: timestamp,
143
+ updated_at: timestamp
144
+ });
145
+ return toAccount(await table().where({ id }).first());
146
+ }
147
+
148
+ /**
149
+ * Checks an email and password. Unknown emails, wrong passwords, disabled
150
+ * and locked accounts all fail the same way, so the caller shows one
151
+ * generic sentence. A locked account stays locked until recovery, even
152
+ * with the right password.
153
+ */
154
+ async function authenticate(email, password) {
155
+ const row = await rowByEmail(email);
156
+ if (!row || !row.password_hash) {
157
+ await verifyPassword(password, { algorithm: "scrypt", version: "v1", salt: "AAAA", hash: "A".repeat(86) });
158
+ return null;
159
+ }
160
+ if (Number(row.failed_logins) >= LOCK_AFTER_FAILURES || row.disabled) {
161
+ return null;
162
+ }
163
+ if (!(await verifyPassword(password, passwordRecord(row)))) {
164
+ await table().where({ id: row.id }).increment("failed_logins", 1);
165
+ return null;
166
+ }
167
+ if (Number(row.failed_logins) > 0) {
168
+ await table().where({ id: row.id }).update({ failed_logins: 0 });
169
+ }
170
+ return toAccount(row);
171
+ }
172
+
173
+ async function checkPassword(id, password) {
174
+ const row = await table().where({ id }).first();
175
+ return Boolean(row?.password_hash) && verifyPassword(password, passwordRecord(row));
176
+ }
177
+
178
+ async function setPassword(id, password) {
179
+ const problem = passwordProblem(password);
180
+ if (problem) throw new AccountError(problem.code, problem.message);
181
+ return update(id, { ...passwordColumns(await hashPassword(password)), failed_logins: 0 });
182
+ }
232
183
 
184
+ async function clearPassword(id) {
185
+ return update(id, {
186
+ password_algorithm: null,
187
+ password_version: null,
188
+ password_salt: null,
189
+ password_hash: null
190
+ });
191
+ }
192
+
193
+ async function updateProfile(id, { displayName }) {
194
+ const name = String(displayName ?? "").trim();
195
+ if (!name) throw new AccountError("display_name_required", "Enter the name your apps should show.");
196
+ return update(id, { display_name: name.slice(0, 160) });
197
+ }
198
+
199
+ function markEmailVerified(id) {
200
+ return update(id, { email_verified: true });
201
+ }
202
+
203
+ function linkGoogle(id, googleSub) {
204
+ return update(id, { google_sub: String(googleSub) });
205
+ }
206
+
207
+ async function unlinkGoogle(id) {
208
+ const row = await table().where({ id }).first();
209
+ if (!row?.password_hash) {
210
+ throw new AccountError("password_required", "Set a password first, so you can still sign in without Google.");
211
+ }
212
+ return update(id, { google_sub: null });
213
+ }
214
+
215
+ function setDisabled(id, disabled) {
216
+ return update(id, { disabled: Boolean(disabled) });
217
+ }
218
+
219
+ /** Imports one exported JSKIT local account, keeping its id and scrypt fields byte for byte. */
220
+ async function importLocal(row) {
221
+ const timestamp = now();
222
+ await table().insert({
223
+ id: row.id,
224
+ email: normalizeEmail(row.email),
225
+ email_verified: false,
226
+ display_name: displayNameFor(row.display_name, normalizeEmail(row.email)),
227
+ password_algorithm: row.password_algorithm,
228
+ password_version: row.password_version,
229
+ password_salt: row.password_salt,
230
+ password_hash: row.password_hash,
231
+ google_sub: null,
232
+ disabled: Boolean(row.disabled),
233
+ failed_logins: 0,
234
+ created_at: timestamp,
235
+ updated_at: timestamp
236
+ });
237
+ }
238
+
239
+ async function rawById(id) {
240
+ return table().where({ id }).first();
241
+ }
242
+
243
+ return Object.freeze({
244
+ findById,
245
+ findByEmail,
246
+ findByGoogleSub,
247
+ list,
248
+ create,
249
+ authenticate,
250
+ checkPassword,
251
+ // readable-check: allow setter-seam - not a slot: setPassword changes an account's password
252
+ setPassword,
253
+ clearPassword,
254
+ updateProfile,
255
+ markEmailVerified,
256
+ linkGoogle,
257
+ unlinkGoogle,
258
+ // readable-check: allow setter-seam - not a slot: setDisabled changes an account's status
259
+ setDisabled,
260
+ importLocal,
261
+ rawById,
233
262
  rawByEmail: rowByEmail
234
263
  });
235
264
  }
@@ -15,8 +15,11 @@ function isExpired(row, now) {
15
15
  * codes, grants, clients, registration tokens) is one row, so codes and
16
16
  * sessions survive a hub restart. The hub's own records (hub sessions and
17
17
  * settings) use the same table under their own kinds.
18
+ * @param {object} dependencies
19
+ * @param {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} dependencies.knex
20
+ * @param {import("./types.js").HubClock} dependencies.now
18
21
  */
19
- function createKnexAdapterClass(knex, { now = () => new Date() } = {}) {
22
+ function createKnexAdapterClass({ knex, now }) {
20
23
  return class KnexAdapter {
21
24
  constructor(kind) {
22
25
  this.kind = kind;
@@ -71,7 +74,13 @@ function createKnexAdapterClass(knex, { now = () => new Date() } = {}) {
71
74
  };
72
75
  }
73
76
 
74
- async function deleteExpiredModels(knex, { now = () => new Date() } = {}) {
77
+ /**
78
+ * Deletes every short-lived record whose time is up.
79
+ * @param {object} dependencies
80
+ * @param {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} dependencies.knex
81
+ * @param {import("./types.js").HubClock} dependencies.now
82
+ */
83
+ async function deleteExpiredModels({ knex, now }) {
75
84
  return knex(MODELS_TABLE).whereNotNull("expires_at").where("expires_at", "<=", now()).delete();
76
85
  }
77
86